commit 0f031e5660a311e4475e735b91a85a980d583b90 Author: nertyog Date: Mon Oct 12 04:42:20 2026 +0300 initial commit: Easy Import / Export [NAT] for OpenCart 4.0.x diff --git a/Instruction ru-uk-en.txt b/Instruction ru-uk-en.txt new file mode 100644 index 0000000..6ffd069 --- /dev/null +++ b/Instruction ru-uk-en.txt @@ -0,0 +1,109 @@ +============================================================================= +Easy Import/Export [NAT] +Version: 1.0.0 +Compatibility: OpenCart 3.0.x / ocStore 3.0.x +Author: NAT +Support: info@nat.od.ua +============================================================================= + +--------------------------------------------------------- +🇷🇺 РУССКИЙ ЯЗЫК +--------------------------------------------------------- +УСТАНОВКА: +1. В админ-панели OpenCart перейдите в раздел "Модули / Расширения" -> "Установка расширений". Загрузите архив `easy_import_export_nat_OC_30_1_0.ocmod.zip`. +2. Перейдите в "Модули / Расширения" -> "Модификаторы" и нажмите синюю кнопку "Обновить" (Очистить кэш). +3. Перейдите в "Система" -> "Пользователи" -> "Группы пользователей", выберите вашу группу (Administrator), нажмите "Выделить все" в правах просмотра и изменения, затем сохраните. +4. Перейдите в "Модули / Расширения" -> "Расширения" -> тип "Модули", найдите "Easy Import/Export [NAT]" и нажмите "Установить", затем "Редактировать". + +ОБНОВЛЕНИЕ: +1. Загрузите новый архив через "Установка расширений" поверх старого. +2. Обновите кэш в разделе "Модификаторы". +3. Очистите кэш браузера (Ctrl+F5) на странице настроек модуля. + +УДАЛЕНИЕ: +1. Перейдите в "Модули / Расширения", найдите модуль и нажмите красную кнопку "Деинсталлировать". +2. Перейдите в "Установка расширений", найдите модуль в истории загрузок и удалите его файлы. +3. Обновите кэш модификаторов. + +КЛЮЧЕВЫЕ ФУНКЦИИ И ВОЗМОЖНОСТИ: +* Интерактивное превью: При загрузке файла или получении по ссылке модуль моментально выводит таблицу с первыми 5 строками. Это позволяет визуально проверить структуру данных и соответствие колонок перед запуском импорта. +* Умное автосопоставление: Автоматическая привязка колонок прайс-листа к полям OpenCart (Модель, SKU, Цена, Количество, Статус) по встроенным словарям синонимов, защищенная от дублирования связей. +* Живые счетчики импорта: Панель импорта в реальном времени отображает ход работы (Всего строк, Обновлено товаров, Не найдено в каталоге, Пропущено). +* Условные модификаторы цен и остатков: Тонкая настройка правил (например, "Если цена меньше 100 — умножить остаток на 2") с WAF-совместимыми кодами сравнения (eq, ne, gt, lt), которые не блокируются серверами хостинга. +* Парсер ссылок Google Sheets: Автоматическое определение ссылок совместного доступа Google Таблиц и их конвертация в прямую WAF-безопасную ссылку на CSV экспорт. +* Интеграция с REST API поставщиков [BETA]: Встроенный гибкий клиент, поддерживающий GET/POST запросы, авторизацию Basic/Bearer/Custom POST Token, постраничную пагинацию или пагинацию со смещением, а также потоковую memory-safe запись JSON/XML ответов на диск. + +КАК РАБОТАТЬ С МОДУЛЕМ: +1. Вкладка "Настройки": Управление лицензией, отображение быстрых кнопок действий в каталоге и редакторах, пути для экспорта. +2. Вкладка "Экспорт": Выгрузка данных в CSV, XML, JSON или Excel. Настройка идентификаторов, фильтров категорий/производителей и формул модификации перед скачиванием. +3. Вкладка "Импорт": Загрузка файлов или указание ссылок, настройка соответствия колонок по превью и запуск импорта с живой статистикой. +4. Вкладка "Автоимпорт (CRON)": Создание множественных задач для автоматического обновления цен и остатков по расписанию с индивидуальными настройками связей и условных модификаторов. + + +--------------------------------------------------------- +🇬🇧 ENGLISH +--------------------------------------------------------- +INSTALLATION: +1. Go to OpenCart admin panel: "Extensions" -> "Installer". +2. Upload the `easy_import_export_nat_OC_30_1_0.ocmod.zip` archive. +3. Go to "Extensions" -> "Modifications" and click the blue "Refresh" button. +4. Go to "System" -> "Users" -> "User Groups", edit your group (Top Administrator), click "Select All" for Access and Modify permissions, then Save. +5. Go to "Extensions" -> "Extensions" -> choose "Modules", find "Easy Import/Export [NAT]", click "Install" and then "Edit". + +UPDATE: +1. Upload the new zip file via Extension Installer over the old one. +2. Refresh modifications cache. +3. Hard refresh your browser cache (Ctrl+F5) on the module settings page. + +UNINSTALLATION: +1. Go to Extensions -> Modules, click the red "Uninstall" button next to the module. +2. Go to the Extension Installer history and delete the module files. +3. Refresh modifications cache. + +KEY FEATURES: +* Interactive Pre-upload Preview: Displays a 5-row preview table immediately after file upload or URL fetch to verify data structure and mapping presets. +* Smart Auto-mapping: Auto-detects columns using synonym dictionaries for standard OpenCart fields (Model, SKU, Price, Qty, Status) without mapping collisions. +* Live Import Dashboard: Monitors import runs in real-time, showing count tiles for Total, Updated, Not Found, and Skipped products. +* Conditional Modifiers: Setup robust target-modifier conditions (e.g. "If Price lt 100 -> Qty * 2") using WAF-safe alphanumeric operators (eq, ne, gt, lt). +* Google Sheets Link Converter: Automatically transforms shared Google Sheets URLs into direct CSV export endpoints. +* Supplier REST API Client [BETA]: Built-in flexible client supporting GET/POST requests, Basic/Bearer/Custom POST Token auth, offset/page-based paginations, and memory-safe streaming of JSON/XML payloads. + +HOW TO USE: +1. "Settings" Tab: Manage license, paths, and visibility of Fast Import/Export catalog action buttons. +2. "Export" Tab: Dump product data to CSV, XML, JSON, or Excel with custom filters, fields, and pricing modifiers. +3. "Import" Tab: Direct file upload or URL inputs, mapping configurations through visual preview table, and live update stats. +4. "Auto Import (CRON)" Tab: Manage multiple scheduled automation cron tasks, each configured with specific mapping and modifier rules. + + +--------------------------------------------------------- +🇺🇦 УКРАЇНСЬКА МОВА +--------------------------------------------------------- +ВСТАНОВЛЕННЯ: +1. В адмін-панелі OpenCart перейдіть до "Модулі / Розширення" -> "Встановлення розширень". Завантажте архів `easy_import_export_nat_OC_30_1_0.ocmod.zip`. +2. Перейдіть до "Модулі / Розширення" -> "Модифікатори" і натисніть синю кнопку "Оновити". +3. Перейдіть до "Система" -> "Користувачі" -> "Групи користувачів", виберіть вашу групу (Administrator), натисніть "Виділити все" у правах перегляду та зміни, збережіть. +4. Перейдіть до "Модулі / Розширення" -> "Розширення" -> тип "Модулі", знайдіть "Easy Import/Export [NAT]", натисніть "Встановити", а потім "Редагувати". + +ОНОВЛЕННЯ: +1. Завантажте новий архів через "Встановлення розширень" поверх старого. +2. Оновите кеш у розділі "Модифікатори". +3. Очистіть кеш браузера (Ctrl+F5) на сторінці налаштувань модуля. + +ВИДАЛЕННЯ: +1. Перейдіть у "Модулі / Розширення", знайдіть модуль та натисніть червону кнопку "Деінсталювати". +2. Перейдіть у "Встановлення розширень", знайдіть модуль в історії та видаліть його файли. +3. Оновите кеш модифікаторів. + +КЛЮЧОВІ ФУНКЦІЇ ТА МОЖЛИВОСТІ: +* Інтерактивне прев'ю: Миттєво виводить перші 5 рядків завантаженого файлу чи посилання для візуальної перевірки відповідності колонок перед стартом імпорту. +* Розумне автозіставлення: Автоматично розпізнає колонки за словниками синонімів для полів OpenCart (Модель, SKU, Ціна, Кількість, Статус) без перехресних конфліктів. +* Живі лічильники імпорту: Панель відображає прогрес виконання у реальному часі (Всього рядків, Оновлено, Не знайдено в каталозі, Пропущено). +* Умовні модифікатори цін і залишків: Гнучкі правила (наприклад, "Якщо ціна менша 100 — помножити кількість на 2") з WAF-безпечними символами порівняння (eq, ne, gt, lt), які не блокуються хостингами. +* Парсер лінків Google Sheets: Розпізнає посилання спільного доступу Google Таблиць та перетворює їх на прямі WAF-безпечні лінки CSV експорту. +* Інтеграція з REST API постачальників [BETA]: Вбудований гнучкий клієнт, що підтримує GET/POST запити, авторизацію Basic/Bearer/Custom POST Token, постраничну пагінацію або пагінацію зі зміщенням, а також потоковий memory-safe запис JSON/XML відповідей на диск. + +ЯК ПРАЦЮВАТИ З МОДУЛЕМ: +1. Вкладка "Налаштування": Керування ліцензією, активація швидких кнопок імпорту/експорту в каталозі, налаштування шляхів. +2. Вкладка "Експорт": Вивантаження каталогу в CSV, XML, JSON чи Excel з налаштуванням фільтрів та модифікаторів перед скачуванням. +3. Вкладка "Імпорт": Завантаження прайс-листів, налаштування зв'язків колонок по прев'ю та імпорт з показом статистики в реальному часі. +4. Вкладка "Автоимпорт (CRON)": Створення декількох автоматичних завдань для оновлення за розкладом з індивідуальними налаштуваннями відповідності полів та модифікаторів. \ No newline at end of file diff --git a/admin/controller/module/easy_import_nat.php b/admin/controller/module/easy_import_nat.php new file mode 100644 index 0000000..334d11d --- /dev/null +++ b/admin/controller/module/easy_import_nat.php @@ -0,0 +1,4115 @@ +=')) ? '.' : '|'; + } + private $error = array(); + protected static $currency_rate_cache = array(); + + public function index() { + if (!isset($this->request->get['user_token']) || !isset($this->session->data['user_token']) || $this->request->get['user_token'] !== $this->session->data['user_token']) { + $this->response->redirect($this->url->link('common/dashboard', '', true)); + return; + } + $this->load->language('extension/easy_import_nat/module/easy_import_nat'); + if (!$this->user->hasPermission('access', 'extension/easy_import_nat/module/easy_import_nat')) { + $this->response->redirect($this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)); + return; + } + // 1. Очистка заголовка страницы во вкладке браузера + if ($this->language->get('heading_title_raw')) { + $this->document->setTitle($this->language->get('heading_title_raw')); + } else { + $this->document->setTitle(strip_tags($this->language->get('heading_title'))); + } + $this->load->model('setting/setting'); + + $this->checkDb(); + $this->cleanOldTempFiles(); + + $current_lic = (string)$this->config->get('module_easy_import_nat_license'); + // Если настройка уже существует в конфиге (даже пустая строка ''), автовосстановление НЕ запускается! + $has_deliberate_setting = ($this->config->get('module_easy_import_nat_license') !== null); + + if (!$has_deliberate_setting && (empty($current_lic) || !$this->checkLicense($current_lic))) { + $restored = array(); + + // 1. Попытка восстановления из таблицы бэкапа модуля + $bk_set = $this->model_setting_setting->getSetting('nat_easy_import_backup'); + if (!empty($bk_set) && is_array($bk_set) && !empty($bk_set['module_easy_import_nat_license'])) { + $restored = $bk_set; + } + + if (!empty($restored) && !empty($restored['module_easy_import_nat_license'])) { + $this->model_setting_setting->editSetting('module_easy_import_nat', $restored); + foreach ($restored as $rk => $rv) { + $this->config->set($rk, $rv); + } + } + } + + if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { + $posted_lic = isset($this->request->post['module_easy_import_nat_license']) ? trim((string)$this->request->post['module_easy_import_nat_license']) : ''; + $this->request->post['module_easy_import_nat_license'] = $posted_lic; + + // Сохраняем существующие настройки при отправке только ключа из экрана Gatekeeper + if (!isset($this->request->post['module_easy_import_nat_status'])) { + $existing_settings = $this->model_setting_setting->getSetting('module_easy_import_nat'); + if (!empty($existing_settings) && is_array($existing_settings)) { + $this->request->post = array_merge($existing_settings, $this->request->post); + } + } + + // Штатное сохранение настроек модуля + $this->model_setting_setting->editSetting('module_easy_import_nat', $this->request->post); + + if ($posted_lic === '') { + // Пользователь удалил ключ — физически стираем бэкап, исключая зомби-восстановление! + $this->model_setting_setting->deleteSetting('nat_easy_import_backup'); + } else { + // Сохраняем актуальный бэкап при наличии ключа + $this->model_setting_setting->editSetting('nat_easy_import_backup', $this->request->post); + } + + $this->session->data['success'] = $this->language->get('text_success'); + $this->response->redirect($this->url->link('extension/easy_import_nat/module/easy_import_nat', 'user_token=' . $this->session->data['user_token'], true)); + } + + if (isset($this->session->data['success'])) { + $data['success'] = $this->session->data['success']; + unset($this->session->data['success']); + } else { + $data['success'] = ''; + } + + if (isset($this->error['warning'])) { + $data['error_warning'] = $this->error['warning']; + } else { + $data['error_warning'] = ''; + } + + $data['breadcrumbs'] = array(); + $data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_home'), + 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true) + ); + $data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_extension'), + 'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true) + ); + // 2. Хлебные крошки без HTML-тегов + $data['breadcrumbs'][] = array( + 'text' => strip_tags($this->language->get('heading_title_raw') ? $this->language->get('heading_title_raw') : $this->language->get('heading_title')), + 'href' => $this->url->link('extension/easy_import_nat/module/easy_import_nat', 'user_token=' . $this->session->data['user_token'], true) + ); + + // 3. Передача чистого имени в шаблон + $data['heading_title_raw'] = $this->language->get('heading_title_raw') ? $this->language->get('heading_title_raw') : strip_tags($this->language->get('heading_title')); + + $data['action'] = $this->url->link('extension/easy_import_nat/module/easy_import_nat', 'user_token=' . $this->session->data['user_token'], true); + $data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true); + $data['user_token'] = $this->session->data['user_token']; + $data['action_sep'] = $this->getSeparator(); + + $settings = array( + 'status', 'license', 'menu_position', 'show_list', + 'btn_catalog', 'btn_batch', 'btn_handy', + 'export_format', 'export_identifier', 'price_mode', + 'batch_export', 'batch_import', 'log_mode', 'log_lines', + 'cron_secret', 'export_folder', 'export_path', 'inverse_special' + ); + + foreach ($settings as $setting) { + $key = 'module_easy_import_nat_' . $setting; + if (isset($this->request->post[$key])) { + $data[$key] = $this->request->post[$key]; + } else { + $data[$key] = $this->config->get($key); + } + } + + if (!isset($data['module_easy_import_nat_menu_position'])) $data['module_easy_import_nat_menu_position'] = 'both'; + if (!isset($data['module_easy_import_nat_show_list'])) $data['module_easy_import_nat_show_list'] = 1; + if (!isset($data['module_easy_import_nat_btn_catalog'])) $data['module_easy_import_nat_btn_catalog'] = 1; + if (!isset($data['module_easy_import_nat_btn_batch'])) $data['module_easy_import_nat_btn_batch'] = 1; + if (!isset($data['module_easy_import_nat_btn_handy'])) $data['module_easy_import_nat_btn_handy'] = 1; + if (!$data['module_easy_import_nat_export_format']) $data['module_easy_import_nat_export_format'] = 'csv'; + if (!$data['module_easy_import_nat_export_identifier']) $data['module_easy_import_nat_export_identifier'] = 'model'; + if (!$data['module_easy_import_nat_price_mode']) $data['module_easy_import_nat_price_mode'] = 'special'; + if (!$data['module_easy_import_nat_batch_export']) $data['module_easy_import_nat_batch_export'] = 200; + if (!$data['module_easy_import_nat_batch_import']) $data['module_easy_import_nat_batch_import'] = 200; + if (!$data['module_easy_import_nat_log_mode']) $data['module_easy_import_nat_log_mode'] = 'changes'; + if (!isset($data['module_easy_import_nat_log_lines'])) $data['module_easy_import_nat_log_lines'] = 200; + if (empty($data['module_easy_import_nat_cron_secret'])) $data['module_easy_import_nat_cron_secret'] = substr(md5((string)mt_rand()), 0, 16); + if (empty($data['module_easy_import_nat_export_folder'])) $data['module_easy_import_nat_export_folder'] = 'import_nat'; + if (empty($data['module_easy_import_nat_export_path'])) $data['module_easy_import_nat_export_path'] = 'root'; + if (!isset($data['module_easy_import_nat_inverse_special'])) $data['module_easy_import_nat_inverse_special'] = 0; + if ($data['module_easy_import_nat_status'] === null) $data['module_easy_import_nat_status'] = 1; + + // Гарантированная передача переменных в шаблон: + $data['user_token'] = $this->session->data['user_token']; + $data['action_sep'] = $this->getSeparator(); + $_h = defined('HTTP_CATALOG') ? parse_url(HTTP_CATALOG, PHP_URL_HOST) : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); + $_h = preg_replace('/:\d+$/', '', trim((string)$_h)); + $_h = preg_replace('/^www\./i', '', $_h); + $data['nat_current_domain'] = strtolower($_h); + $current_lic = isset($data['module_easy_import_nat_license']) ? (string)$data['module_easy_import_nat_license'] : (string)$this->config->get('module_easy_import_nat_license'); + $data['is_licensed'] = $this->checkLicense($current_lic); + $data['license_valid'] = $data['is_licensed']; + + $this->load->model('catalog/category'); + $data['categories'] = $this->model_catalog_category->getCategories(array()); + + $this->load->model('catalog/manufacturer'); + $data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturers(array()); + + $this->load->model('extension/easy_import_nat/module/easy_import_nat'); + $data['import_batches'] = $this->model_extension_easy_import_nat_module_easy_import_nat->getImportBatches(); + + $this->load->model('localisation/currency'); + $data['currencies'] = array(); + $currencies = $this->model_localisation_currency->getCurrencies(); + foreach ($currencies as $currency) { + if ($currency['status']) { + $data['currencies'][] = array( + 'currency_id' => $currency['currency_id'], + 'title' => $currency['title'], + 'code' => $currency['code'], + 'value' => $currency['value'] + ); + } + } + + $cron_profiles = $this->model_extension_easy_import_nat_module_easy_import_nat->getCronProfiles(); + $data['cron_profiles'] = array(); + + $path_type = $this->config->get('module_easy_import_nat_export_path'); + $folder = $this->config->get('module_easy_import_nat_export_folder'); + $base_url = str_replace('/admin/', '/', HTTP_SERVER); + if ($path_type === 'image') { + $base_url .= 'image/catalog/'; + } + if ($folder) { + $base_url .= $folder . '/'; + } + + foreach ($cron_profiles as $profile) { + $profile['mapping_decoded'] = json_decode($profile['mapping'], true); + if (!is_array($profile['mapping_decoded'])) { + $profile['mapping_decoded'] = array(); + } + $profile['settings_decoded'] = json_decode($profile['settings'], true); + if (!is_array($profile['settings_decoded'])) { + $profile['settings_decoded'] = array(); + } + + // Health badge calculation + $threshold = isset($profile['settings_decoded']['cron_alert_threshold']) ? $profile['settings_decoded']['cron_alert_threshold'] : '7_days'; + $threshold_seconds = 7 * 86400; + if ($threshold === '12_hours') $threshold_seconds = 12 * 3600; + elseif ($threshold === '24_hours') $threshold_seconds = 24 * 3600; + elseif ($threshold === '3_days') $threshold_seconds = 3 * 86400; + elseif ($threshold === '7_days') $threshold_seconds = 7 * 86400; + elseif ($threshold === '14_days') $threshold_seconds = 14 * 86400; + elseif ($threshold === '30_days') $threshold_seconds = 30 * 86400; + + if (empty($profile['date_last_run'])) { + $profile['health_badge'] = ' ' . $this->language->get('text_cron_never_run') . ''; + } else { + $last_history = $this->db->query("SELECT * FROM `" . DB_PREFIX . "easy_import_nat_history` WHERE profile_id = '" . (int)$profile['profile_id'] . "' ORDER BY history_id DESC LIMIT 1"); + $last_run_time = strtotime($profile['date_last_run']); + $diff = time() - $last_run_time; + $days = round($diff / 86400, 1); + + if ($last_history->num_rows && in_array($last_history->row['status'], array('error', 'aborted'))) { + $err_title = sprintf($this->language->get('text_cron_error_tooltip'), $last_history->row['status']); + $profile['health_badge'] = ' ' . $this->language->get('text_cron_status_error') . ''; + } elseif ($diff > $threshold_seconds) { + $alert_title = sprintf($this->language->get('text_cron_alert_tooltip'), $days, str_replace('_', ' ', $threshold)); + $profile['health_badge'] = ' ' . $this->language->get('text_cron_status_alert') . ''; + } else { + $updated_cnt = $last_history->num_rows ? (int)$last_history->row['updated'] : 0; + $success_title = $last_history->num_rows ? "Updated: " . $updated_cnt : "OK"; + $profile['health_badge'] = ' ' . $this->language->get('text_cron_status_active') . ''; + } + } + + $profile['public_link'] = $base_url . $profile['url']; + $data['cron_profiles'][] = $profile; + } + $data['catalog_link'] = str_replace('/admin/', '/', HTTP_SERVER); + + $data['next_cron_id'] = $this->model_extension_easy_import_nat_module_easy_import_nat->getNextCronId(); + + $tables = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "product%'"); + $data['db_tables'] = array(); + foreach ($tables->rows as $t) { + $t_vals = array_values($t); + $table_name = $t_vals[0]; + $columns = $this->db->query("SHOW COLUMNS FROM `" . $table_name . "`"); + $cols = array(); + foreach ($columns->rows as $col) { + $cols[] = $col['Field']; + } + if (in_array('product_id', $cols)) { + $data['db_tables'][] = array( + 'name' => $table_name, + 'columns' => $cols + ); + } + } + + $data['manual_import_profiles'] = $this->model_extension_easy_import_nat_module_easy_import_nat->getProfilesByType('manual_import'); + $data['manual_export_profiles'] = $this->model_extension_easy_import_nat_module_easy_import_nat->getProfilesByType('manual_export'); + + $data['catalog_url'] = HTTP_CATALOG; + $data['cron_cli_path'] = str_replace('\\', '/', (defined('DIR_CATALOG') && realpath(DIR_CATALOG . '../')) ? (realpath(DIR_CATALOG . '../') . '/index.php') : (rtrim(DIR_CATALOG, '/\\') . '/../index.php')); + $data['cron_secret'] = $this->config->get('module_easy_import_nat_cron_secret'); + + $data['header'] = $this->load->controller('common/header'); + $data['column_left'] = $this->load->controller('common/column_left'); + $data['footer'] = $this->load->controller('common/footer'); + + foreach ($this->language->all() as $key => $value) { + $data[$key] = $value; + } + + $this->response->setOutput($this->load->view('extension/easy_import_nat/module/easy_import_nat', $data)); + } + + private function checkDb() { + $query = $this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "product` LIKE 'import_batch'"); + if (!$query->num_rows) { + $this->db->query("ALTER TABLE `" . DB_PREFIX . "product` ADD `import_batch` VARCHAR(64) NOT NULL DEFAULT '' AFTER `status`"); + } + + $query_model = $this->db->query("SHOW INDEX FROM `" . DB_PREFIX . "product` WHERE Key_name = 'model'"); + if (!$query_model->num_rows) { + $this->db->query("ALTER TABLE `" . DB_PREFIX . "product` ADD INDEX `model` (`model`)"); + } + + $query_sku = $this->db->query("SHOW INDEX FROM `" . DB_PREFIX . "product` WHERE Key_name = 'sku'"); + if (!$query_sku->num_rows) { + $this->db->query("ALTER TABLE `" . DB_PREFIX . "product` ADD INDEX `sku` (`sku`)"); + } + + $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "easy_import_nat_cron` ( + `profile_id` INT(11) NOT NULL AUTO_INCREMENT, + `type` VARCHAR(32) NOT NULL DEFAULT 'import', + `name` VARCHAR(128) NOT NULL, + `url` TEXT NOT NULL, + `mapping` TEXT NOT NULL, + `settings` TEXT NOT NULL, + `status` TINYINT(1) NOT NULL DEFAULT '1', + `date_added` DATETIME NOT NULL, + `date_last_run` DATETIME DEFAULT NULL, + PRIMARY KEY (`profile_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;"); + + $query_type = $this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "easy_import_nat_cron` LIKE 'type'"); + if (!$query_type->num_rows) { + $this->db->query("ALTER TABLE `" . DB_PREFIX . "easy_import_nat_cron` ADD `type` VARCHAR(32) NOT NULL DEFAULT 'import' AFTER `profile_id`"); + } + + $query_threshold = $this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "easy_import_nat_cron` LIKE 'cron_alert_threshold'"); + if (!$query_threshold->num_rows) { + $this->db->query("ALTER TABLE `" . DB_PREFIX . "easy_import_nat_cron` ADD `cron_alert_threshold` VARCHAR(50) NOT NULL DEFAULT '7_days' AFTER `date_last_run`"); + } + + $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "easy_import_nat_history` ( + `history_id` INT(11) NOT NULL AUTO_INCREMENT, + `profile_id` INT(11) NOT NULL DEFAULT '0', + `profile_name` VARCHAR(255) NOT NULL, + `type` VARCHAR(50) NOT NULL, + `date_added` DATETIME NOT NULL, + `updated` INT(11) NOT NULL DEFAULT '0', + `not_found` INT(11) NOT NULL DEFAULT '0', + `skipped` INT(11) NOT NULL DEFAULT '0', + `status` VARCHAR(50) NOT NULL, + `log_file` VARCHAR(255) NOT NULL DEFAULT '', + PRIMARY KEY (`history_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;"); + + // Clean up detailed text logs older than 30 days in DIR_CACHE + if (is_dir(DIR_CACHE)) { + $files = glob(DIR_CACHE . '*'); + $now = time(); + foreach ($files as $file) { + if (is_file($file) && (strpos(basename($file), 'nat_') === 0 || strpos($file, '_processed.txt') !== false)) { + if ($now - filemtime($file) > 30 * 86400) { + @unlink($file); + } + } + } + } + } + + protected function validate() { + if (!$this->user->hasPermission('modify', 'extension/easy_import_nat/module/easy_import_nat')) { + $this->error['warning'] = $this->language->get('error_permission'); + } + + if (isset($this->request->post['module_easy_import_nat_cron_secret'])) { + $this->request->post['module_easy_import_nat_cron_secret'] = preg_replace('/[^a-zA-Z0-9_-]/', '', $this->request->post['module_easy_import_nat_cron_secret']); + } + if (isset($this->request->post['module_easy_import_nat_export_folder'])) { + $this->request->post['module_easy_import_nat_export_folder'] = preg_replace('/[^a-zA-Z0-9_-]/', '', basename($this->request->post['module_easy_import_nat_export_folder'])); + } + if (isset($this->request->post['module_easy_import_nat_export_path'])) { + $this->request->post['module_easy_import_nat_export_path'] = ($this->request->post['module_easy_import_nat_export_path'] === 'image') ? 'image' : 'root'; + } + if (isset($this->request->post['module_easy_import_nat_status'])) { + $this->request->post['module_easy_import_nat_status'] = (int)$this->request->post['module_easy_import_nat_status']; + } + if (isset($this->request->post['module_easy_import_nat_menu_position'])) { + $allowed_pos = array('module_only', 'header', 'sidebar', 'both'); + if (!in_array($this->request->post['module_easy_import_nat_menu_position'], $allowed_pos)) { + $this->request->post['module_easy_import_nat_menu_position'] = 'both'; + } + } + foreach (array('show_list', 'btn_catalog', 'btn_batch', 'btn_handy', 'inverse_special') as $opt) { + if (isset($this->request->post['module_easy_import_nat_' . $opt])) { + $this->request->post['module_easy_import_nat_' . $opt] = (int)$this->request->post['module_easy_import_nat_' . $opt]; + } + } + if (isset($this->request->post['module_easy_import_nat_export_format'])) { + $allowed_fmt = array('xlsx', 'xls', 'csv', 'xml', 'json'); + if (!in_array($this->request->post['module_easy_import_nat_export_format'], $allowed_fmt)) { + $this->request->post['module_easy_import_nat_export_format'] = 'csv'; + } + } + if (isset($this->request->post['module_easy_import_nat_export_identifier'])) { + $allowed_ident = array('model', 'sku', 'product_id'); + if (!in_array($this->request->post['module_easy_import_nat_export_identifier'], $allowed_ident)) { + $this->request->post['module_easy_import_nat_export_identifier'] = 'model'; + } + } + if (isset($this->request->post['module_easy_import_nat_price_mode'])) { + $allowed_pm = array('simple', 'special', 'special_group', 'discount', 'all_advanced'); + if (!in_array($this->request->post['module_easy_import_nat_price_mode'], $allowed_pm)) { + $this->request->post['module_easy_import_nat_price_mode'] = 'special'; + } + } + if (isset($this->request->post['module_easy_import_nat_batch_export'])) { + $this->request->post['module_easy_import_nat_batch_export'] = max(1, (int)$this->request->post['module_easy_import_nat_batch_export']); + } + if (isset($this->request->post['module_easy_import_nat_batch_import'])) { + $this->request->post['module_easy_import_nat_batch_import'] = max(1, (int)$this->request->post['module_easy_import_nat_batch_import']); + } + if (isset($this->request->post['module_easy_import_nat_log_mode'])) { + $allowed_log = array('full', 'changes', 'off'); + if (!in_array($this->request->post['module_easy_import_nat_log_mode'], $allowed_log)) { + $this->request->post['module_easy_import_nat_log_mode'] = 'changes'; + } + } + if (isset($this->request->post['module_easy_import_nat_log_lines'])) { + $this->request->post['module_easy_import_nat_log_lines'] = max(1, (int)$this->request->post['module_easy_import_nat_log_lines']); + } + + if (empty($this->request->post['module_easy_import_nat_cron_secret'])) { + $this->error['warning'] = $this->language->get('error_cron_secret'); + } + + if (!$this->error && !empty($this->request->post['module_easy_import_nat_export_folder'])) { + $folder = $this->request->post['module_easy_import_nat_export_folder']; + $path = $this->request->post['module_easy_import_nat_export_path'] == 'image' ? DIR_IMAGE . 'catalog/' . $folder . '/' : DIR_APPLICATION . '../' . $folder . '/'; + + if (!is_dir($path)) { + @mkdir($path, 0755, true); + } + if (is_dir($path) && !file_exists($path . '.htaccess')) { + file_put_contents($path . '.htaccess', "Options -Indexes\n\nOrder Allow,Deny\nDeny from all\n"); + file_put_contents($path . 'index.html', ''); + } + } + + return !$this->error; + } + + public function install(): void { + $this->load->model('user/user_group'); + $this->model_user_user_group->addPermission($this->user->getGroupId(), 'access', 'extension/easy_import_nat/module/easy_import_nat'); + $this->model_user_user_group->addPermission($this->user->getGroupId(), 'modify', 'extension/easy_import_nat/module/easy_import_nat'); + + $this->checkDb(); + + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('module_easy_import_nat'); + if (!isset($settings['module_easy_import_nat_cron_secret'])) { + $settings['module_easy_import_nat_cron_secret'] = substr(md5((string)mt_rand()), 0, 16); + $this->model_setting_setting->editSetting('module_easy_import_nat', $settings); + } + + // Register OC 4 Events + $sep = $this->getSeparator(); + $this->load->model('setting/event'); + $events = array( + array( + 'code' => 'easy_import_nat_column_left', + 'description' => 'Easy Import/Export [NAT] Menu', + 'trigger' => 'admin/view/common/column_left/before', + 'action' => 'extension/easy_import_nat/module/easy_import_nat' . $sep . 'eventColumnLeft', + 'status' => 1, + 'sort_order' => 1 + ), + array( + 'code' => 'easy_import_nat_header_after', + 'description' => 'Easy Import/Export [NAT] Header Icon', + 'trigger' => 'admin/view/common/header/after', + 'action' => 'extension/easy_import_nat/module/easy_import_nat' . $sep . 'eventHeaderAfter', + 'status' => 1, + 'sort_order' => 1 + ), + array( + 'code' => 'easy_import_nat_product_list', + 'description' => 'Easy Import/Export [NAT] Product List Fast Buttons', + 'trigger' => 'admin/view/catalog/product_list/after', + 'action' => 'extension/easy_import_nat/module/easy_import_nat' . $sep . 'eventProductListAfter', + 'status' => 1, + 'sort_order' => 1 + ) + ); + + $ref = new \ReflectionMethod($this->model_setting_event, 'addEvent'); + $is_array_sig = ($ref->getNumberOfParameters() === 1); + foreach ($events as $ev) { + $this->model_setting_event->deleteEventByCode($ev['code']); + if ($is_array_sig) { + $this->model_setting_event->addEvent($ev); + } else { + $this->model_setting_event->addEvent($ev['code'], $ev['description'], $ev['trigger'], $ev['action'], (bool)$ev['status'], (int)$ev['sort_order']); + } + } + } + + public function uninstall(): void { + $this->load->model('setting/setting'); + $this->model_setting_setting->deleteSetting('module_easy_import_nat'); + + $this->load->model('setting/event'); + $this->model_setting_event->deleteEventByCode('easy_import_nat_column_left'); + $this->model_setting_event->deleteEventByCode('easy_import_nat_header_after'); + $this->model_setting_event->deleteEventByCode('easy_import_nat_product_list'); + } + + public function eventColumnLeft(string &$route, array &$args): void { + if ($this->config->get('module_easy_import_nat_status')) { + $nat_pos = $this->config->get('module_easy_import_nat_menu_position'); + if ($nat_pos == 'sidebar' || $nat_pos == 'both') { + if ($this->user->hasPermission('access', 'extension/easy_import_nat/module/easy_import_nat')) { + $token = isset($this->session->data['user_token']) ? $this->session->data['user_token'] : ''; + $nat_item = array( + 'name' => 'Easy Import/Export', + 'href' => $this->url->link('extension/easy_import_nat/module/easy_import_nat', 'user_token=' . $token, true), + 'children' => array() + ); + + $nat_menu_index = -1; + if (isset($args['menus'])) { + foreach ($args['menus'] as $k => $menu) { + if (isset($menu['id']) && $menu['id'] == 'menu-nat') { + $nat_menu_index = $k; + break; + } + } + } + + if ($nat_menu_index > -1) { + $exists = false; + foreach ($args['menus'][$nat_menu_index]['children'] as $child) { + if ($child['href'] == $nat_item['href']) { + $exists = true; + break; + } + } + if (!$exists) { + $args['menus'][$nat_menu_index]['children'][] = $nat_item; + } + } else { + $args['menus'][] = array( + 'id' => 'menu-nat', + 'icon' => 'fa-solid fa-space-shuttle fa-rotate-270 fw', + 'name' => '[NAT] Modules', + 'href' => '', + 'children' => array($nat_item) + ); + } + } + } + } + } + + public function eventHeaderAfter(string &$route, array &$args, string &$output): void { + if ($this->config->get('module_easy_import_nat_status')) { + $nat_pos = $this->config->get('module_easy_import_nat_menu_position'); + if ($nat_pos == 'header' || $nat_pos == 'both') { + if ($this->user->hasPermission('access', 'extension/easy_import_nat/module/easy_import_nat')) { + $token = isset($this->session->data['user_token']) ? $this->session->data['user_token'] : ''; + $href = $this->url->link('extension/easy_import_nat/module/easy_import_nat', 'user_token=' . $token, true); + + $nat_menu_html = ' + '; + + if (strpos($output, 'id="nav-logout"') !== false) { + $output = str_replace('id="nav-logout"', 'id="nav-logout-old"', $output); + $output = str_replace('id="nav-logout-old"', 'id="nav-logout"', $output); + } + if (strpos($output, '