Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- *
- * @ This file is created by http://DeZender.Net
- * @ deZender (PHP7 Decoder for SourceGuardian Encoder)
- *
- * @ Version : 4.0.9.0
- * @ Author : DeZender
- * @ Release on : 08.08.2019
- * @ Official site : http://DeZender.Net
- *
- */
- if (!defined('_PS_VERSION_')) {
- exit();
- }
- class AnymarketPro extends Module
- {
- protected $config_form = false;
- public $urlany = ['http://sandbox-api.anymarket.com.br/v2/', 'http://api.anymarket.com.br/v2/'];
- public $sendResponse;
- public $orders_qty = 100;
- public $prod_qty = 1200;
- public $mktplaces = [];
- public $horaatual;
- public $ecommerce_active;
- public $hierarquia = false;
- public $referencia = true;
- public $erp = false;
- public function __construct()
- {
- $this->name = 'anymarketpro';
- $this->tab = 'market_place';
- $this->version = '1.6.8.4';
- $this->author = 'PrestaBR';
- $this->need_instance = 1;
- $this->bootstrap = true;
- parent::__construct();
- $this->displayName = $this->l('AnyMarket Integration');
- $this->description = $this->l('Integrate your shop with many Brazilian MarketPlaces');
- $this->confirmUninstall = $this->l('Are you sure to uninstall the Anymarket Integration?');
- $this->ps_versions_compliancy = ['min' => '1.6.0.9', 'max' => _PS_VERSION_];
- $this->horaatual = date('d-m-Y H:i:s');
- if (!Module::isEnabled('anymarketpayment')) {
- $this->warning = $this->l('Don\'t forget to install and enable AnyMarket Payments module, so your shop can process orders from the integrated MarketPlaces.');
- }
- if (Module::isEnabled($this->name)) {
- $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');
- foreach ($this->mktplaces as $mktplace) {
- if ($mktplace['mkt_name'] == 'ecommerce') {
- if ($mktplace['mkt_active'] == 1) {
- $this->ecommerce_active = true;
- }
- }
- }
- }
- }
- /**
- * Installation
- */
- public function install()
- {
- Configuration::updateValue('ANYMARKETPRO_LIVE_MODE', false);
- Configuration::updateValue('ANYMARKETPRO_ENV', 0, false);
- Configuration::updateValue('ANYMARKETPRO_TOKEN', '', false);
- Configuration::updateValue('ANYMARKETPRO_EMAIL', '', false);
- Configuration::updateValue('ANYMARKETPRO_PAGO', Configuration::get('PS_OS_PAYMENT'), false);
- Configuration::updateValue('ANYMARKETPRO_FATURADO', Configuration::get('PS_OS_PREPARATION'), false);
- Configuration::updateValue('ANYMARKETPRO_ENVIADO', Configuration::get('PS_OS_SHIPPING'), false);
- Configuration::updateValue('ANYMARKETPRO_CONCLUIDO', Configuration::get('PS_OS_DELIVERED'), false);
- Configuration::updateValue('ANYMARKETPRO_CANCELADO', Configuration::get('PS_OS_CANCELED'), false);
- Configuration::updateValue('ANYMARKETPRO_WAR', 'Garantia padrão de 3 meses.', false);
- Configuration::updateValue('ANYMARKETPRO_WAR_TIME', 3, false);
- Configuration::updateValue('ANYMARKETPRO_FULLOG', 1, false);
- Configuration::updateValue('ANYMARKETPRO_DELETEDB', 0, false);
- include dirname(__FILE__) . '/sql/install.php';
- 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');
- }
- public function uninstall()
- {
- if ((Configuration::get('ANYMARKETPRO_DELETEDB') !== false) && (Configuration::get('ANYMARKETPRO_DELETEDB') != 0)) {
- include dirname(__FILE__) . '/sql/uninstall.php';
- }
- Configuration::deleteByName('ANYMARKETPRO_LIVE_MODE');
- Configuration::deleteByName('ANYMARKETPRO_ENV');
- Configuration::deleteByName('ANYMARKETPRO_TOKEN');
- Configuration::deleteByName('ANYMARKETPRO_EMAIL');
- Configuration::deleteByName('ANYMARKETPRO_PAGO');
- Configuration::deleteByName('ANYMARKETPRO_FATURADO');
- Configuration::deleteByName('ANYMARKETPRO_ENVIADO');
- Configuration::deleteByName('ANYMARKETPRO_CONCLUIDO');
- Configuration::deleteByName('ANYMARKETPRO_CANCELADO');
- Configuration::deleteByName('ANYMARKETPRO_WAR');
- Configuration::deleteByName('ANYMARKETPRO_WAR_TIME');
- Configuration::deleteByName('ANYMARKETPRO_FULLOG');
- Configuration::deleteByName('ANYMARKETPRO_DELETEDB');
- return parent::uninstall() && $this->uninstallAnyTabs();
- }
- public function installAnyTabs()
- {
- $tab0 = new Tab();
- $tab0->class_name = 'AdminAnyPro';
- $tab0->module = 'anymarketpro';
- $tab0->id_parent = NULL;
- foreach (Language::getLanguages(false) as $lang) {
- $tab0->name[(int) $lang['id_lang']] = $this->l('Integração AnyMarket');
- }
- if (!$tab0->save()) {
- $this->_errors[] = $this->l('Unable to create the "AnyMarket" tab');
- }
- if (!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'logo.gif', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 't' . DIRECTORY_SEPARATOR . 'AdminAnyPro.gif')) {
- $this->_errors[] = sprintf($this->l('Unable to copy logo.gif in %s'), _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 't' . DIRECTORY_SEPARATOR);
- }
- return true;
- }
- public function uninstallAnyTabs()
- {
- $id_tab = Tab::getIdFromClassName('AdminAnyPro');
- $tab = new Tab($id_tab);
- if (!$tab->delete()) {
- return false;
- }
- return true;
- }
- /**
- * Load the configuration form
- */
- public function getContent()
- {
- $groups = Group::getGroups($this->context->language->id, true);
- $output = '';
- $this->mktplaces = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'anymarketpro_places` WHERE `deleted` != 1 ORDER BY `mkt_active` DESC, `id_mkt` ASC;');
- if ((bool) Tools::isSubmit('submitAnymarketProModule')) {
- if (!$this->postProcess()) {
- $output .= $this->displayError($this->l('Configuration not updated!'));
- }
- else {
- $output .= $this->displayConfirmation($this->l('Configuration sucessfully updated.'));
- }
- }
- if ((bool) Tools::isSubmit('submitCategoriesPop')) {
- $this->populateCategories();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitBrandsPop')) {
- $this->populateBrands();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitProductsPop')) {
- $this->populateProducts();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitOrdersPop')) {
- $this->populateOrders();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitStockPop')) {
- $this->updateStock();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitVariationsPop')) {
- $this->populateVariations();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitCategoriesTree')) {
- $this->getAnyMarketCategory();
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- else if ((bool) Tools::isSubmit('submitMktPlaces')) {
- foreach ($this->mktplaces as $mktplace) {
- $active = Tools::getValue('mkt_active_' . $mktplace['id_mkt']);
- if ($active) {
- $mkt_markup = str_replace(',', '.', Tools::getValue('mkt_markup_' . $mktplace['id_mkt']));
- $mkt_group = Tools::getValue('mkt_group_' . $mktplace['id_mkt']);
- 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");
- }
- else {
- Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'anymarketpro_places` SET `mkt_active` = 0 WHERE `id_mkt` = ' . $mktplace['id_mkt'] . ';');
- }
- $deleted = Tools::getValue('mkt_delete_' . $mktplace['id_mkt']);
- if ($deleted === true) {
- Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'anymarketpro_places` SET `deleted` = 1 WHERE `id_mkt` = ' . $mktplace['id_mkt'] . ';');
- }
- }
- $output .= $this->displayConfirmation($this->l('MarketPlaces Updated!'));
- }
- else if ((bool) Tools::isSubmit('submitOrderGet')) {
- $id_any = Tools::getValue('id_order_any');
- $get_all = Tools::getValue('get_all_orders');
- if ($get_all && !$id_any) {
- $this->getAllOrdersAnyMarket();
- }
- else {
- $this->getOrderFromAnyMarket($id_any);
- }
- $this->context->smarty->assign('postresponse', $this->sendResponse);
- }
- $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']);
- $output .= $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
- return $output . $this->renderForm();
- }
- /**
- * Create the form that will be displayed in the configuration of your module.
- */
- protected function renderForm()
- {
- $helper = new HelperForm();
- $helper->show_toolbar = false;
- $helper->table = $this->table;
- $helper->module = $this;
- $helper->default_form_language = $this->context->language->id;
- $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
- $helper->identifier = $this->identifier;
- $helper->submit_action = 'submitAnymarketProModule';
- $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
- $helper->token = Tools::getAdminTokenLite('AdminModules');
- $helper->tpl_vars = ['fields_value' => $this->getConfigFormValues(), 'languages' => $this->context->controller->getLanguages(), 'id_language' => $this->context->language->id];
- return $helper->generateForm([$this->getConfigForm()]);
- }
- /**
- * Create the structure of your form.
- */
- protected function getConfigForm()
- {
- $groups = Group::getGroups($this->context->language->id, true);
- $statuses = OrderState::getOrderStates($this->context->language->id);
- return [
- 'form' => [
- 'legend' => ['title' => $this->l('Settings'), 'icon' => 'icon-cogs'],
- 'input' => [
- [
- 'type' => 'switch',
- 'label' => $this->l('Production Environment'),
- 'name' => 'ANYMARKETPRO_ENV',
- 'is_bool' => false,
- 'desc' => $this->l('Use the test environment to check if everything is OK before going live'),
- 'values' => [
- ['id' => 'active_on', 'value' => 1, 'label' => $this->l('Production')],
- ['id' => 'active_off', 'value' => 0, 'label' => $this->l('Sandbox')]
- ]
- ],
- ['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')],
- ['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)')],
- ['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.')],
- ['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.')],
- [
- 'type' => 'select',
- 'label' => $this->l('Order Paid State'),
- 'name' => 'ANYMARKETPRO_PAGO',
- 'desc' => $this->l('Set the status which the orders are considered paid.'),
- 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
- ],
- [
- 'type' => 'select',
- 'label' => $this->l('Order Invoiced State'),
- 'name' => 'ANYMARKETPRO_FATURADO',
- 'desc' => $this->l('Set the status which the orders are considered invoiced.'),
- 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
- ],
- [
- 'type' => 'select',
- 'label' => $this->l('Order Sent State'),
- 'name' => 'ANYMARKETPRO_ENVIADO',
- 'desc' => $this->l('Set the status which the orders are considered sent.'),
- 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
- ],
- [
- 'type' => 'select',
- 'label' => $this->l('Order Concluded State'),
- 'name' => 'ANYMARKETPRO_CONCLUIDO',
- 'desc' => $this->l('Set the status which the orders are considered concluded.'),
- 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
- ],
- [
- 'type' => 'select',
- 'label' => $this->l('Order Canceled State'),
- 'name' => 'ANYMARKETPRO_CANCELADO',
- 'desc' => $this->l('Set the status which the orders are considered canceled.'),
- 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
- ],
- ['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')],
- [
- 'type' => 'switch',
- 'label' => $this->l('Generate Full LOGs'),
- 'name' => 'ANYMARKETPRO_FULLOG',
- 'is_bool' => true,
- 'desc' => $this->l('Full Logs register everything sent and received.'),
- 'values' => [
- ['id' => 'logs_on', 'value' => 1, 'label' => $this->l('Yes')],
- ['id' => 'logs_off', 'value' => 0, 'label' => $this->l('No')]
- ]
- ],
- [
- 'type' => 'switch',
- 'label' => $this->l('Delete Database?'),
- 'name' => 'ANYMARKETPRO_DELETEDB',
- 'is_bool' => true,
- 'desc' => $this->l('Delete Database upon uninstall only if you are sure you won\'t use it anymore.'),
- 'values' => [
- ['id' => 'deletebd_on', 'value' => 1, 'label' => $this->l('Yes')],
- ['id' => 'deletebd_off', 'value' => 0, 'label' => $this->l('No')]
- ]
- ]
- ],
- 'submit' => ['title' => $this->l('Save')]
- ]
- ];
- }
- /**
- * Set values for the inputs.
- */
- protected function getConfigFormValues()
- {
- 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'))];
- }
- /**
- * Save form data.
- */
- protected function postProcess()
- {
- $form_values = $this->getConfigFormValues();
- $erro = false;
- foreach (array_keys($form_values) as $key) {
- if (!Configuration::updateValue($key, Tools::getValue($key))) {
- $erro = true;
- }
- }
- if ($erro) {
- return false;
- }
- else {
- return true;
- }
- }
- /**
- * Add the CSS & JavaScript files you want to be loaded in the BO.
- */
- public function hookBackOfficeHeader()
- {
- $id_product = Tools::getValue('id_product');
- if (isset($id_product) && ($id_product != '')) {
- $id_prod_any = $this->getAnymarketData('products', $id_product);
- $this->context->controller->addJquery();
- $this->context->controller->addJS($this->_path . 'views/js/button.js');
- if ((bool) Tools::isSubmit('submitProductInitial')) {
- $this->sendProductData($id_product, 'POST');
- }
- if ((bool) Tools::isSubmit('submitUpdateAnyImages')) {
- $this->sendProdImages($id_product, $id_prod_any);
- }
- if ((bool) Tools::isSubmit('submitDeleteFromDb')) {
- $this->deleteAnymarketData('products', $id_product);
- }
- $this->context->smarty->assign('id_prod_any', $id_prod_any);
- return $this->display(__FILE__, 'admin_product.tpl');
- }
- if ((Tools::getValue('module_name') == $this->name) || (Tools::getValue('configure') == $this->name)) {
- $this->context->controller->addJS($this->_path . 'views/js/anymarketpro.js');
- }
- $this->context->controller->addCSS($this->_path . 'views/css/anymarketpro.css');
- }
- public function curl_post($post_url, $method, $post_string, $action = false)
- {
- if (is_array($post_string)) {
- $post_string = json_encode($post_string);
- }
- $any_base_url = $this->urlany[Configuration::get('ANYMARKETPRO_ENV')];
- $post_header = ['Content-Type: application/json', 'gumgaToken: ' . Configuration::get('ANYMARKETPRO_TOKEN') . ''];
- $request = curl_init($any_base_url . $post_url);
- curl_setopt($request, CURLOPT_HTTPHEADER, $post_header);
- curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 0);
- curl_setopt($request, CURLOPT_TIMEOUT, 500);
- curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
- if ($method == 'POST') {
- curl_setopt($request, CURLOPT_POST, true);
- curl_setopt($request, CURLOPT_POSTFIELDS, $post_string);
- }
- else if ($method == 'PUT') {
- curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'PUT');
- curl_setopt($request, CURLOPT_POSTFIELDS, $post_string);
- }
- else if ($method == 'DELETE') {
- curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'DELETE');
- }
- $post_response = curl_exec($request);
- $err = curl_error($request);
- $status = curl_getinfo($request, CURLINFO_HTTP_CODE);
- if (($status == 200) || ($status == 204) || ($status == 201)) {
- $retorno = ['error' => '0', 'json' => $post_string, 'return' => json_decode($post_response)];
- }
- else if ($err) {
- $retorno = ['error' => '1', 'json' => $post_string, 'return' => 'Error Curl: ' . $err];
- }
- else {
- $retJsonCurlResp = json_decode($post_response);
- $retString = '';
- if (isset($retJsonCurlResp->message)) {
- $retString = 'Message: ' . utf8_encode($retJsonCurlResp->message);
- }
- if (isset($retJsonCurlResp->details)) {
- $retString .= '; Details: ' . utf8_encode($retJsonCurlResp->details);
- }
- if (isset($retJsonCurlResp->fieldErrors)) {
- $retString .= '; Field Erros: (';
- foreach ($retJsonCurlResp->fieldErrors as $error) {
- $retString .= 'Field: ' . utf8_encode($error->field);
- $retString .= ', Message: ' . utf8_encode($error->message) . ';';
- }
- $retString .= ')';
- }
- if ($retString != '') {
- $retorno = ['error' => '1', 'json' => '', 'return' => $retString];
- }
- else {
- $retorno = ['error' => '1', 'json' => '', 'return' => utf8_encode($post_response)];
- }
- }
- curl_close($request);
- if ((bool) Configuration::get('ANYMARKETPRO_FULLOG') !== false) {
- $this->saveLog('curl', $method, $post_string, json_encode($retorno), $post_url);
- }
- $this->sendResponse[] = $post_response;
- $r_json = json_decode($post_response);
- if (isset($r_json->id)) {
- if ($post_url == 'products') {
- $p_json = json_decode($post_string);
- $this->updateAnymarketData('products', $p_json->product_id, $r_json->id);
- }
- else if ($post_url == 'categories') {
- $this->updateAnymarketData($post_url, $r_json->partnerId, $r_json->id);
- }
- else if (strpos($post_url, 'brands') !== false) {
- $brand = json_decode($post_string);
- $this->updateAnymarketData('brands', $r_json->partnerId, $r_json->id);
- }
- else if ((strpos($post_url, 'variations') !== false) && !strpos($post_url, '/values')) {
- $this->updateAnymarketData('variations', $r_json->partnerId, $r_json->id);
- $this->updateVariations();
- }
- else if ((strpos($post_url, 'variations') !== false) && (strpos($post_url, '/values') !== false)) {
- $attribute = json_decode($post_string);
- $this->updateAnymarketData('var_value', $r_json->partnerId, $r_json->id);
- }
- else {
- $type = substr($post_url, 0, strpos($post_url, '/'));
- if (!$type || ($type == '')) {
- $type = $post_url;
- }
- }
- }
- if (empty($post_response)) {
- $retorno = 'Curl error.';
- }
- return $retorno;
- }
- public function saveLog($type, $method, $json, $response = false, $url = false)
- {
- if (!$response) {
- $response = '';
- }
- if (!$url) {
- $url = '';
- }
- $query = 'INSERT INTO `' . _DB_PREFIX_ . 'anymarketpro_logs` (`datetime`, `type`, `method`, `url`, `json`, `response`) VALUES (NOW(), "' . $type . '", "' . $method . '", "' . addslashes($url) . '", "' . addslashes($json) . '", "' . addslashes($response) . '")';
- if (Db::getInstance()->execute($query) === false) {
- return false;
- }
- return true;
- }
- public function populateCategories()
- {
- $categories = Category::getCategories($this->context->language->id, false, false);
- $this->sendResponse = [];
- foreach ($categories as $category) {
- $id_any = $this->getAnymarketData('categories', $category['id_category']);
- $cat = new Category($category['id_category']);
- $cat_name = '';
- $parents = $cat->getParentsCategories($this->context->language->id);
- foreach (array_reverse($parents) as $parent) {
- if ($parent !== end($parents)) {
- $cat_name .= $parent['name'];
- }
- if (($parent !== reset($parents)) && ($parent !== end($parents))) {
- $cat_name .= ' > ';
- }
- }
- if (!$id_any || ($id_any == '')) {
- if ($category['id_parent'] < 2) {
- $id_parent = (int) Configuration::get('PS_HOME_CATEGORY');
- }
- else {
- $id_parent = (int) $category['id_parent'];
- }
- if (1 < $category['id_category']) {
- $this->sendCategoryData($cat_name, $category['id_category'], $id_parent);
- }
- }
- }
- $this->getAnyMarketCategory();
- }
- public function sendCategoryData($cat_name, $cat_id, $cat_id_parent)
- {
- $cat_name = substr($cat_name, 0, 78);
- if ($this->hierarquia === true) {
- $id_parent_category = (int) $this->getAnymarketData('categories', $cat_id_parent);
- }
- else {
- $id_parent_category = (int) $this->getAnymarketData('categories', Configuration::get('PS_HOME_CATEGORY'));
- }
- if (1 < $cat_id) {
- if ($cat_id != Configuration::get('PS_HOME_CATEGORY')) {
- $cat_array = [
- 'name' => str_replace('/', '-', $cat_name),
- 'partnerId' => $cat_id,
- 'parent' => ['id' => isset($id_parent_category) && $id_parent_category ? $id_parent_category : 'null'],
- 'priceFactor' => 1,
- 'calculatedPrice' => true
- ];
- }
- else {
- $category = new Category($cat_id);
- $cat_array = ['name' => str_replace('/', '-', $category->name[$this->context->language->id]), 'partnerId' => $cat_id, 'priceFactor' => 1, 'calculatedPrice' => true];
- }
- }
- $cat_exists = $this->getAnymarketData('categories', $cat_id);
- if ($cat_exists === false) {
- $this->curl_post('categories', 'POST', $cat_array);
- }
- else {
- $this->curl_post('categories/' . $cat_exists, 'PUT', $cat_array);
- }
- }
- public function populateBrands()
- {
- $brands = Manufacturer::getManufacturers(false, $this->context->language->id);
- $this->sendResponse = [];
- foreach ($brands as $brand) {
- if (!$this->getAnymarketData('brands', $brand['id_manufacturer'])) {
- $this->sendBrandData($brand['id_manufacturer'], $brand['name']);
- }
- }
- if (!$this->getAnymarketData('brands', 'loja')) {
- $this->sendBrandData('loja', Configuration::get('PS_SHOP_NAME'));
- }
- }
- public function sendBrandData($id_manufacturer, $manu_name)
- {
- $man_array = ['name' => str_replace('/', '-', $manu_name), 'partnerId' => $id_manufacturer];
- $this->curl_post('brands', 'POST', $man_array);
- }
- public function updateBrandData($id_any, $id_manufacturer, $manu_name)
- {
- $man_array = ['name' => str_replace('/', '-', $manu_name), 'partnerId' => $id_manufacturer];
- $this->curl_post('brands/' . $id_any, 'PUT', $man_array);
- }
- public function populateVariations()
- {
- $attribute_groups = AttributeGroup::getAttributesGroups($this->context->language->id);
- foreach ($attribute_groups as $group) {
- $id_variation_any = $this->getAnymarketData('variations', $group['id_attribute_group']);
- $attributes = AttributeGroup::getAttributes($this->context->language->id, $group['id_attribute_group']);
- $values = [];
- foreach ($attributes as $attribute) {
- $values[] = [
- 'description' => $attribute['name'],
- 'partnerId' => $attribute['id_attribute'],
- 'type' => ['id' => $id_variation_any, 'name' => $group['name']]
- ];
- }
- if ($id_variation_any !== false) {
- $variation = ['id' => $id_variation_any, 'name' => $group['name'], 'partnerId' => $group['id_attribute_group'], 'visualVariation' => $group['is_color_group'] == 1 ? 'true' : 'false', 'values' => $values];
- $this->sendVariationData($variation, $id_variation_any);
- }
- else {
- $variation = ['name' => $group['name'], 'partnerId' => $group['id_attribute_group'], 'visualVariation' => $group['is_color_group'] == 1 ? 'true' : 'false', 'values' => $values];
- $this->sendVariationData($variation);
- }
- }
- }
- public function sendVariationData($variation, $id_variation_any = false)
- {
- if (!$id_variation_any) {
- $this->curl_post('variations', 'POST', $variation);
- }
- else {
- $this->curl_post('variations/' . $id_variation_any, 'PUT', $variation);
- }
- }
- public function sendVariationValue($attribute, $id_variation_any, $id_attribute_any = false)
- {
- if (!$id_attribute_any) {
- $this->curl_post('variations/' . $id_variation_any . '/values', 'POST', $attribute);
- }
- else {
- $this->curl_post('variations/' . $id_variation_any . '/values/' . $id_attribute_any, 'PUT', $attribute);
- }
- }
- public function populateProducts()
- {
- $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");
- $this->sendResponse = [];
- foreach ($prods as $prod) {
- $id_any = $this->getAnymarketData('products', $prod['id_product']);
- if (!$id_any || ($id_any == '')) {
- $this->sendProductData($prod['id_product'], 'POST');
- }
- }
- }
- public function sendProductData($id_product, $post_type)
- {
- $product = new Product($id_product);
- if ((bool) $product->active !== true) {
- return NULL;
- }
- $id_any = $this->checkProductAnyMarket($id_product);
- $imgs = $product->getImages($this->context->language->id);
- $comb_imgs = $product->getCombinationImages($this->context->language->id);
- $img_var = '';
- $prod_img = [];
- foreach ($imgs as $k => $img) {
- foreach ($comb_imgs as $k => $comb_img) {
- foreach ($comb_img as $attrib) {
- if ($attrib['id_image'] == $img['id_image']) {
- $var = $product->getAttributeCombinationsById($attrib['id_product_attribute'], $this->context->language->id);
- foreach ($var as $combination) {
- $var_name = '';
- if ((bool) $combination['is_color_group'] !== false) {
- $var_name .= trim($combination['attribute_name']);
- if (end($var) !== $combination) {
- $var_name .= ' / ';
- }
- }
- }
- }
- }
- }
- $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 : ''];
- }
- $features = $product->getFrontFeatures($this->context->language->id);
- $prod_features = [];
- foreach ($features as $k => $feature) {
- $prod_features[] = ['index' => $k, 'name' => $feature['name'], 'value' => $feature['value']];
- }
- $combination_ids = $product->getProductAttributesIds($product->id);
- $skus = [];
- if (isset($combination_ids) && !empty($combination_ids)) {
- foreach ($combination_ids as $attribute) {
- $combinations = $product->getAttributeCombinationsById($attribute['id_product_attribute'], $this->context->language->id);
- $attribute_name = '';
- $variations = [];
- foreach ($combinations as $combination) {
- $attribute_name .= trim($combination['group_name']) . '(' . trim($combination['attribute_name']) . ') ';
- $cod_barras = $combination['ean13'];
- $variations = array_merge($variations, [trim($combination['group_name']) => trim($combination['attribute_name'])]);
- if ($this->referencia === true) {
- $partId = (isset($combination['reference']) && $combination['reference'] ? $combination['reference'] : $product->reference);
- }
- else {
- $partId = $product->id . '-' . $attribute['id_product_attribute'];
- }
- }
- if (!$cod_barras) {
- $cod_barras = $product->ean13;
- }
- $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];
- }
- }
- else {
- if ($this->referencia === true) {
- $partId = $product->reference;
- }
- else {
- $partId = $product->id;
- }
- $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)];
- }
- if ($post_type == 'PUT') {
- $this->updateProductSkus($product->id);
- }
- $prod_brand = (isset($product->id_manufacturer) && $product->id_manufacturer ? $product->id_manufacturer : 'loja');
- if (isset($product->id_manufacturer) && ($product->id_manufacturer != '')) {
- $marca = new Manufacturer($product->id_manufacturer);
- $prod_manu = $marca->name;
- }
- else {
- $prod_manu = htmlentities(Configuration::get('PS_SHOP_NAME'), ENT_QUOTES, 'UTF-8');
- }
- $permitted = '<p><b><strong><i><br>';
- if (isset($product->description[$this->context->language->id]) && $product->description[$this->context->language->id]) {
- $prod_desc = strip_tags($product->description[$this->context->language->id], $permitted);
- }
- else {
- $prod_desc = strip_tags($product->description_short[$this->context->language->id], $permitted);
- }
- if (strtoupper($prod_desc) == $prod_desc) {
- $prod_desc = ucwords($prod_desc);
- }
- $prod_desc = substr(nl2br($prod_desc), 0, 10000);
- $id_cat_any = $this->getAnymarketData('categories', $product->id_category_default);
- if (!$id_cat_any && $id_any) {
- $id_cat_any = $this->getProductCategoryFromAnyMarket($id_any);
- }
- $prod_array = [
- 'product_id' => $product->id,
- 'title' => str_replace('/', '-', substr($product->name[$this->context->language->id], 0, 145)),
- 'description' => $prod_desc,
- 'category' => ['id' => $id_cat_any, 'partnerId' => $product->id_category_default],
- 'brand' => ['id' => $this->getAnymarketData('brands', $prod_brand), 'name' => $prod_manu, 'partnerId' => $prod_brand],
- 'nbm' => ['id' => isset($product->ncm[$this->context->language->id]) ? $product->ncm[$this->context->language->id] : ''],
- 'origin' => ['id' => isset($product->orig[$this->context->language->id]) ? $product->orig[$this->context->language->id] : 0],
- 'model' => $product->reference,
- 'gender' => $product->gender,
- 'warrantyTime' => Configuration::get('ANYMARKETPRO_WAR_TIME'),
- 'warrantyText' => Configuration::get('ANYMARKETPRO_WAR'),
- 'height' => 0 < $product->height ? $product->height : '',
- 'width' => 0 < $product->width ? $product->width : '',
- 'weight' => 0 < $product->weight ? $product->weight : '',
- 'length' => 0 < $product->depth ? $product->depth : '',
- 'priceFactor' => 1,
- 'calculatedPrice' => true,
- 'videoUrl' => '',
- 'characteristics' => $prod_features,
- 'images' => $prod_img,
- 'skus' => $skus
- ];
- if ($post_type == 'POST') {
- $this->curl_post('products', $post_type, $prod_array);
- }
- else {
- if (!$id_any || ($id_any == '')) {
- $id_any = $this->getAnymarketData('products', $product->id);
- }
- $this->curl_post('products/' . $id_any, $post_type, $prod_array);
- }
- }
- public function updateProductSkus($id_product, $action = false)
- {
- if ($this->erp === true) {
- return NULL;
- }
- $product = new Product($id_product);
- $idAny = $this->getAnymarketData('products', $id_product);
- if (!$idAny || ($idAny == '')) {
- $idAny = $this->checkProductAnyMarket($id_product);
- }
- $skus = [];
- $combs = [];
- $estoques = [];
- $callback = $this->curl_post('products/' . $idAny . '/skus', 'GET', '', $action);
- if (is_array($callback['return'])) {
- $skusAnymarket = json_decode(json_encode($callback['return']));
- }
- else if (!is_object($callback['return'])) {
- $skusAnymarket = json_decode($callback['return']);
- }
- else {
- $skusAnymarket = $callback['return'];
- }
- foreach ($skusAnymarket as $skuAny) {
- $skus[$skuAny->partnerId] = $skuAny->id;
- }
- $combination_ids = $product->getProductAttributesIds($product->id);
- if (isset($combination_ids) && !empty($combination_ids)) {
- foreach ($combination_ids as $attribute) {
- $stock = StockAvailable::getQuantityAvailableByProduct($product->id, $attribute['id_product_attribute']);
- $cost = $product->getPrice(true, $attribute['id_product_attribute'], 2);
- $combinations = $product->getAttributeCombinationsById($attribute['id_product_attribute'], $this->context->language->id);
- $attribute_name = false;
- $cod_barras = false;
- $variations = [];
- foreach ($combinations as $combination) {
- if ($combination['id_product_attribute'] == $attribute['id_product_attribute']) {
- $attribute_name .= trim($combination['group_name']) . '(' . trim($combination['attribute_name']) . ') ';
- $cod_barras = $combination['ean13'];
- $variations = array_merge($variations, [trim($combination['group_name']) => trim($combination['attribute_name'])]);
- if ($this->referencia === true) {
- $partId = (isset($combination['reference']) && $combination['reference'] ? $combination['reference'] : $product->reference);
- }
- else {
- $partId = $product->id . '-' . $attribute['id_product_attribute'];
- }
- if (!$cod_barras) {
- $cod_barras = $product->ean13;
- }
- if ((bool) $skus[$partId] !== false) {
- $p_type = 'PUT';
- $idSkuAny = $skus[$partId];
- }
- else {
- $p_type = 'POST';
- $idSkuAny = false;
- }
- $combs[$partId] = $attribute['id_product_attribute'];
- $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];
- }
- }
- if (($p_type == 'PUT') && ((bool) $idSkuAny !== false)) {
- if (!$this->curl_post('products/' . $idAny . '/skus/' . $idSkuAny, 'PUT', $skuAtual)) {
- $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao atualizado');
- }
- $estoques[] = ['id' => $idSkuAny, 'partnerId' => $partId, 'quantity' => $stock, 'cost' => $cost, 'additionalTime' => 0];
- }
- else if (!$this->curl_post('products/' . $idAny . '/skus/', 'POST', $skuAtual)) {
- $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao incluido');
- }
- }
- foreach ($skus as $k => $sku) {
- if (array_key_exists($k, $combs) === false) {
- }
- }
- }
- else {
- $stock = StockAvailable::getQuantityAvailableByProduct($product->id);
- $cost = $product->getPrice(true, NULL, 2);
- $cod_barras = $product->ean13;
- if ($this->referencia === true) {
- $partId = $product->reference;
- }
- else {
- $partId = $product->id;
- }
- if ((bool) $skus[$partId] !== false) {
- $p_type = 'PUT';
- $idSkuAny = $skus[$partId];
- }
- else {
- $p_type = 'POST';
- $idSkuAny = false;
- }
- $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];
- if (($p_type == 'PUT') && ((bool) $idSkuAny !== false)) {
- if (!$this->curl_post('products/' . $idAny . '/skus/' . $idSkuAny, 'PUT', $skuAtual)) {
- $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao atualizado');
- }
- $estoques[] = ['id' => $idSkuAny, 'partnerId' => $partId, 'quantity' => $stock, 'cost' => $cost, 'additionalTime' => 0];
- }
- else if (!$this->curl_post('products/' . $idAny . '/skus/', 'POST', $skuAtual)) {
- $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao incluido');
- }
- }
- if (!$this->curl_post('stocks/', 'PUT', $estoques)) {
- $this->saveLog('error', 'stocks', json_encode($estoques), 'Estoque nao atualizado.');
- }
- }
- public function sendProdImages($id_product, $id_prod_any = false)
- {
- if (!$id_prod_any) {
- $id_prod_any = $this->getAnymarketData('products', $id_product);
- }
- if (!$id_prod_any) {
- return NULL;
- }
- $callback = $this->curl_post('products/' . $id_prod_any . '/images', 'GET', '');
- if (is_array($callback['return'])) {
- $prod_imgs_any = json_decode(json_encode($callback['return']));
- }
- else if (!is_object($callback['return'])) {
- $prod_imgs_any = json_decode($callback['return']);
- }
- else {
- $prod_imgs_any = $callback['return'];
- }
- foreach ($prod_imgs_any as $img_any) {
- $this->curl_post('products/' . $id_prod_any . '/images/' . $img_any->id, 'DELETE', '');
- $this->saveLog('delete', 'images', $img_any->id, 'Imagem do Produto ' . $id_prod_any . ' apagada ');
- }
- $product = new Product($id_product);
- $imgs = $product->getImages($this->context->language->id);
- $comb_imgs = $product->getCombinationImages($this->context->language->id);
- foreach ($imgs as $k => $img) {
- foreach ($comb_imgs as $k => $comb_img) {
- foreach ($comb_img as $attrib) {
- if ($attrib['id_image'] == $img['id_image']) {
- $var = $product->getAttributeCombinationsById($attrib['id_product_attribute'], $this->context->language->id);
- foreach ($var as $combination) {
- $var_name = '';
- if ((bool) $combination['is_color_group'] !== false) {
- $var_name .= trim($combination['attribute_name']);
- if (end($var) !== $combination) {
- $var_name .= ' / ';
- }
- }
- }
- }
- }
- }
- $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 : ''];
- $this->curl_post('products/' . $id_prod_any . '/images', 'POST', $prod_img);
- }
- return true;
- }
- public function getAttributeIdFromReference($reference)
- {
- $query = 'SELECT * FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `reference` = "' . $reference . '";';
- if (!($attribute = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query))) {
- return false;
- }
- else {
- return $attribute['id_product_attribute'];
- }
- }
- public function getIdProductFromReference($reference)
- {
- $query = 'SELECT * FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `reference` = "' . $reference . '";';
- if (!($attribute = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query))) {
- return false;
- }
- else {
- return $attribute['id_product'];
- }
- }
- public function populateOrders()
- {
- if ($this->ecommerce_active !== true) {
- return NULL;
- }
- $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";
- $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query_orders);
- $this->sendResponse = [];
- foreach ($result as $order) {
- $any_order = $this->getAnymarketData('orders', (int) $order['id_order']);
- if (!$any_order) {
- $this->sendOrderData((int) $order['id_order']);
- }
- }
- }
- public function sendOrderData($id_order)
- {
- if ($this->ecommerce_active !== true) {
- return NULL;
- }
- if ($this->getAnymarketData('orders', $id_order)) {
- return NULL;
- }
- $order = new Order($id_order);
- if (isset($order->shipping_number) && ($order->shipping_number != '')) {
- if (isset($order->delivery_number) && ($order->delivery_number != '')) {
- $ship_status = 'ENTREGUE';
- }
- else {
- $ship_status = 'ENVIADO';
- }
- }
- else {
- $ship_status = '';
- }
- $customer = new Customer($order->id_customer);
- $address_delivery = new Address($order->id_address_delivery);
- $address_invoice = new Address($order->id_address_invoice);
- $state_delivery = new State($address_delivery->id_state);
- $nfe = $this->getNfeData($order->id);
- $carrier = new Carrier($order->id_carrier);
- $cart = new Cart($order->id_cart);
- $prods = $order->getProducts();
- $cpf_field = false;
- $cnpj_field = false;
- if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "cpf"')) {
- $cpf_field = 'cpf';
- $cnpj_field = 'siret';
- }
- 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"')) {
- $cpf_field = 'cpf_cnpj';
- $cnpj_field = 'cpf_cnpj';
- }
- else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "document"')) {
- $cpf_field = 'document';
- $cnpj_field = 'document';
- if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "doc_type"')) {
- $doc_type = true;
- }
- }
- 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')) {
- $cpf_field = 'doc';
- $cnpj_field = 'doc';
- }
- else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'djtalbrazilianregister" AND COLUMN_NAME = "cpf"')) {
- $cpf_field = 'djtal';
- $cnpj_field = 'djtal';
- }
- if (($cpf_field === false) || ($cnpj_field === false)) {
- $this->saveLog('error', 'cpf/cnpj', json_encode($customer), 'Campo CPF/CNPJ nao encontrado.');
- }
- if (($cpf_field == 'djtal') || ($cnpj_field == 'djtal')) {
- $document = Db::getInstance()->getValue('SELECT `cpf` FROM `' . _DB_PREFIX_ . 'djtalbrazilianregister` WHERE `id_customer` = ' . $customer->id);
- if (!$document) {
- $document = Db::getInstance()->getValue('SELECT `cnpj` FROM `' . _DB_PREFIX_ . 'djtalbrazilianregister` WHERE `id_customer` = ' . $customer->id);
- }
- }
- else if ($cnpj_field == 'doc') {
- $document = Db::getInstance()->getValue('SELECT `doc` FROM `' . _DB_PREFIX_ . 'cpfmodule` WHERE`id_customer` = ' . $customer->id);
- }
- else {
- $document = $customer->{$cpf_field};
- if (!$document) {
- $document = $customer->{$cnpj_field};
- }
- }
- $items = [];
- foreach ($prods as $prod) {
- $product_id = $prod['product_id'];
- $prod_reference = $prod['product_reference'];
- if (isset($prod['product_attribute_id']) && ($prod['product_attribute_id'] != '')) {
- if ($this->referencia === true) {
- $ps_sku = $prod['product_reference'];
- }
- else {
- $ps_sku = $product_id;
- }
- }
- else if ($this->referencia === true) {
- $ps_sku = $prod_reference;
- }
- else {
- $ps_sku = $product_id;
- }
- $id_prod_any = $this->getAnymarketData('products', $product_id);
- $callback = $this->curl_post('products/' . $id_prod_any . '/skus', 'GET', '');
- if (is_array($callback['return'])) {
- $skusAnymarket = json_decode(json_encode($callback['return']));
- }
- else if (!is_object($callback['return'])) {
- $skusAnymarket = json_decode($callback['return']);
- }
- else {
- $skusAnymarket = $callback['return'];
- }
- foreach ($skusAnymarket as $sku) {
- if ($sku->partnerId == $ps_sku) {
- $id_sku = $sku->id;
- }
- }
- if ($this->referencia === true) {
- $partnerId = $prod_reference;
- }
- else {
- $partnerId = $product_id;
- }
- $prod_name = $prod['product_name'];
- if (isset($prod_reference) && ($prod_reference != '')) {
- $prod_name = $prod_name . ' (' . $prod_reference . ')';
- }
- if (isset($prod['attributes']) && ($prod['attributes'] != '')) {
- $prod_name = $prod_name . ' - ' . $prod['attributes'];
- }
- $prod_amount = $prod['product_quantity'];
- $prod_price = (float) $prod['original_product_price'];
- $prod_discount = (float) ($prod['original_product_price'] - $prod['product_price']) * $prod['product_quantity'];
- $prod_gross = (float) $prod['product_price'] * $prod['product_quantity'];
- $prod_total = (float) $prod['total_price'];
- $items[] = [
- 'sku' => ['id' => $id_sku, 'title' => substr($prod_name, 0, 145), 'partnerId' => $partnerId],
- 'product' => ['id' => id_prod_any, 'title' => substr($prod_name, 0, 145)],
- 'amount' => $prod_amount,
- 'unit' => $prod_price,
- 'discount' => $prod_discount,
- 'gross' => $prod_gross,
- 'total' => $prod_total,
- 'shippings' => [
- ['id' => id_prod_any, 'shippingtype' => $carrier->name]
- ..............................................................................................
- ...........................................................
- ........................
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement