$this->get_label(),
'description' => __('Bring a supplier or marketplace catalogue into WooCommerce and keep it current: connect eFood, Wolt, Etsy or Amazon in a few fields, or paste any XML or CSV feed and let Rooster One work out its shape for you. Products and their category tree are created for you, matched by SKU so a re-run updates rather than duplicates.', 'ai-eshop-optimizer'),
'bullets' => array(
__('Paste a sample feed and the structure is inferred for you — record path, fields, separators — then mapped onto your product fields.', 'ai-eshop-optimizer'),
__('Vendor categories are matched to your own, and what you confirm once is remembered for every future feed from that supplier.', 'ai-eshop-optimizer'),
__('Per-feed rules derive the fields a supplier did not send: split a code into a parent, read a colour out of a spec line, set stock from the vendor’s own availability words.', 'ai-eshop-optimizer'),
__('Rows a supplier sends once per colour or size are assembled into one variable product instead of many near-identical ones.', 'ai-eshop-optimizer'),
__('Imports run on a schedule, and products you have corrected by hand can be pinned so a nightly run never overwrites them.', 'ai-eshop-optimizer'),
),
);
}
public function get_tabs() {
return array(
'import' => array('label' => __('Import', 'ai-eshop-optimizer'), 'icon' => 'zap'),
'sources' => array('label' => __('Feed sources', 'ai-eshop-optimizer'), 'icon' => 'folders'),
);
}
public function get_tab_arg() { return 'cati_section'; }
public function register_hooks() {
add_action('wp_ajax_aieo_catalog_import_save_conn', array($this, 'ajax_save_conn'));
add_action('wp_ajax_aieo_catalog_import_test', array($this, 'ajax_test'));
add_action('wp_ajax_aieo_catalog_import_start', array($this, 'ajax_import_start'));
add_action('wp_ajax_aieo_catalog_import_process', array($this, 'ajax_import_process'));
add_action('wp_ajax_aieo_catalog_feed_analyze', array($this, 'ajax_feed_analyze'));
add_action('wp_ajax_aieo_catalog_feed_dryrun', array($this, 'ajax_feed_dryrun'));
add_action('wp_ajax_aieo_catalog_feed_save', array($this, 'ajax_feed_save'));
add_action('wp_ajax_aieo_catalog_feed_delete', array($this, 'ajax_feed_delete'));
add_action('wp_ajax_aieo_catalog_feed_run_now', array($this, 'ajax_feed_run_now'));
add_action('wp_ajax_aieo_catalog_feed_load', array($this, 'ajax_feed_load'));
add_action('wp_ajax_aieo_catalog_feed_link_brands', array($this, 'ajax_feed_link_brands'));
add_action('wp_ajax_aieo_catalog_feed_search_terms', array($this, 'ajax_feed_search_terms'));
add_action('wp_ajax_aieo_catalog_feed_catmap_list', array($this, 'ajax_feed_catmap_list'));
add_action('wp_ajax_aieo_catalog_feed_catmap_suggest', array($this, 'ajax_feed_catmap_suggest'));
add_action('wp_ajax_aieo_catalog_feed_catmap_save', array($this, 'ajax_feed_catmap_save'));
add_action('wp_ajax_aieo_catalog_feed_catmap_accept', array($this, 'ajax_feed_catmap_accept'));
add_action('wp_ajax_aieo_catalog_feed_catmap_bulk', array($this, 'ajax_feed_catmap_bulk'));
add_action('wp_ajax_aieo_catalog_feed_catmap_health', array($this, 'ajax_feed_catmap_health'));
add_action('wp_ajax_aieo_catalog_feed_vocab_backfill', array($this, 'ajax_feed_vocab_backfill'));
add_action('wp_ajax_aieo_catalog_feed_vocab_flagged', array($this, 'ajax_feed_vocab_flagged'));
add_action('wp_ajax_aieo_catalog_feed_vocab_rule', array($this, 'ajax_feed_vocab_rule'));
if (class_exists('AIEO_Feed_Source_Store')) {
add_action('init', array('AIEO_Feed_Source_Store', 'register'));
add_filter('cron_schedules', array($this, 'add_weekly_schedule'));
add_action('admin_init', array($this, 'sync_schedules'));
add_action(self::CRON_HOOK, array($this, 'run_scheduled_import'), 10, 1);
}
if (class_exists('AIEO_Generic_Feed_Source')) {
add_filter('aieo_catalog_import_sources', array('AIEO_Generic_Feed_Source', 'register_all'));
}
if (class_exists('AIEO_Feed_Product_Admin')) {
AIEO_Feed_Product_Admin::register();
}
}
public function add_weekly_schedule($schedules) {
$later = did_action('init');
if (!isset($schedules['weekly'])) {
$schedules['weekly'] = array('interval' => WEEK_IN_SECONDS, 'display' => $later ? __('Once a week', 'ai-eshop-optimizer') : 'Once a week');
}
if (!isset($schedules['monthly'])) {
$schedules['monthly'] = array('interval' => MONTH_IN_SECONDS, 'display' => $later ? __('Once a month', 'ai-eshop-optimizer') : 'Once a month');
}
return $schedules;
}
public static function next_local_hour_ts($hour) {
return self::next_local_occurrence('daily', $hour, -1);
}
public static function next_local_occurrence($schedule, $hour, $day) {
$hour = ((int) $hour >= 0 && (int) $hour <= 23) ? (int) $hour : 6;
$day = (int) $day;
try {
$tz = wp_timezone();
$next = new \DateTime('today ' . sprintf('%02d', $hour) . ':00:00', $tz);
if ('weekly' === $schedule && $day >= 1 && $day <= 7) {
$guard = 0;
while (((int) $next->format('N') !== $day || $next->getTimestamp() <= time()) && $guard++ < 8) {
$next->modify('+1 day');
}
return (int) $next->getTimestamp();
}
if ('monthly' === $schedule && $day >= 1 && $day <= 31) {
for ($m = 0; $m < 3; $m++) {
$probe = new \DateTime('first day of this month', $tz);
if ($m > 0) { $probe->modify('+' . $m . ' month'); }
$dom = min($day, (int) $probe->format('t'));
$probe->setDate((int) $probe->format('Y'), (int) $probe->format('n'), $dom);
$probe->setTime($hour, 0, 0);
if ($probe->getTimestamp() > time()) { return (int) $probe->getTimestamp(); }
}
}
if ($next->getTimestamp() <= time()) { $next->modify('+1 day'); }
return (int) $next->getTimestamp();
} catch (\Throwable $e) {
return time() + DAY_IN_SECONDS;
}
}
public static function occurrence_aligned($schedule, $ts, $hour, $day) {
if ((int) $hour >= 0 && (int) wp_date('G', (int) $ts) !== (int) $hour) { return false; }
$day = (int) $day;
if ($day < 1) { return true; }
if ('weekly' === $schedule) { return (int) wp_date('N', (int) $ts) === $day; }
if ('monthly' === $schedule) {
$expected = min($day, (int) wp_date('t', (int) $ts));
return (int) wp_date('j', (int) $ts) === $expected;
}
return true;
}
public function sync_schedules() {
if (!class_exists('AIEO_Feed_Source_Store')) { return; }
foreach (AIEO_Feed_Source_Store::all() as $def) {
$this->arm_schedule((int) $def['id'], (string) $def['schedule']);
}
}
private static function next_recurring_occurrence($id) {
$crons = _get_cron_array();
if (!is_array($crons)) { return false; }
$key = md5(serialize(array((int) $id)));
$found = false;
foreach ($crons as $ts => $hooks) {
if (!isset($hooks[self::CRON_HOOK][$key])) { continue; }
$event = $hooks[self::CRON_HOOK][$key];
if (empty($event['schedule'])) { continue; }
if (false === $found || $ts < $found) { $found = (int) $ts; }
}
return $found;
}
private function arm_schedule($id, $schedule) {
$args = array((int) $id);
$next = self::next_recurring_occurrence($id);
if ('manual' === $schedule) {
if (wp_next_scheduled(self::CRON_HOOK, $args)) {
wp_clear_scheduled_hook(self::CRON_HOOK, $args);
}
return;
}
$hour = AIEO_Feed_Source_Store::get_schedule_hour((int) $id);
$day = AIEO_Feed_Source_Store::get_schedule_day((int) $id);
$align = (($hour >= 0 || $day >= 1) && in_array($schedule, array('daily', 'weekly', 'monthly'), true));
if ($next) {
$event = wp_get_scheduled_event(self::CRON_HOOK, $args, $next);
$rec_ok = $event && isset($event->schedule) && $event->schedule === $schedule;
$ok = !$align || self::occurrence_aligned($schedule, $next, $hour, $day);
if ($rec_ok && $ok) { return; }
wp_clear_scheduled_hook(self::CRON_HOOK, $args);
}
$first = $align ? self::next_local_occurrence($schedule, $hour, $day) : (time() + 600);
wp_schedule_event($first, $schedule, self::CRON_HOOK, $args);
}
public function run_scheduled_import($id, $mode_override = '') {
$id = (int) $id;
if (!class_exists('AIEO_Feed_Source_Store')) { return; }
$def = AIEO_Feed_Source_Store::get($id);
if (!$def) {
wp_clear_scheduled_hook(self::CRON_HOOK, array($id));
return;
}
if (!self::is_aieo_pro_user()) {
AIEO_Feed_Source_Store::set_last_run($id, array(
'when' => current_time('mysql', true),
'ok' => false,
'message' => __('Skipped: importing from a generated feed source requires the Pro version.', 'ai-eshop-optimizer'),
));
return;
}
$lock = 'aieo_feed_run_' . $id;
if (get_transient($lock)) { return; }
set_transient($lock, 1, HOUR_IN_SECONDS);
$source = new AIEO_Generic_Feed_Source($def);
$creds = array('feed_url' => (string) $def['url']);
$options = AIEO_Feed_Source_Store::get_options($id);
if ('' !== (string) $mode_override && 'update_only' === (string) ($options['mode'] ?? '')) {
$mode_override = 'update_only';
$options['refresh_depth'] = 1;
}
if ('' !== (string) $mode_override) {
$options['mode'] = (string) $mode_override;
}
$options['delta'] = ('' === (string) $mode_override);
$options['source_slug'] = $source->slug();
$options['source_label'] = $source->label();
$options['supplier_term_id'] = $source->supplier_term_id();
$options = $this->feed_intelligence_options($options, $def, true);
$result = array('when' => current_time('mysql', true), 'ok' => false, 'totals' => array(), 'message' => '');
$complete = false;
try {
$valid = $source->validate_credentials($creds);
if (is_wp_error($valid)) { throw new RuntimeException($valid->get_error_message()); }
$cats = $source->fetch_categories($creds);
if (is_wp_error($cats)) { throw new RuntimeException($cats->get_error_message()); }
$plan = $this->feed_plan_signature($def, $options);
$state = get_post_meta($id, '_aieo_feed_cursor', true);
if (is_array($state) && (string) ($state['plan'] ?? '') !== $plan) { $state = array(); }
$after = (is_array($state) && isset($state['after'])) ? (int) $state['after'] : 0;
$carry = (is_array($state) && !empty($state['carry']) && is_array($state['carry'])) ? $state['carry'] : array();
$totals = (is_array($state) && !empty($state['totals']) && is_array($state['totals'])) ? $state['totals'] : array();
$background = self::is_background_run();
$max_seconds = self::run_max_seconds($background);
$max_pages = self::run_max_pages($background);
$started = time();
$total_pages = 1;
$walked = 0;
$slowest = 0;
$prefiltered = 0;
$exhausted = false;
do {
$page_started = time();
$res = AIEO_Catalog_Import_Runner::run_batch($source, $creds, $options, $cats, $after, self::PAGE_SIZE, $carry);
if (is_wp_error($res)) { throw new RuntimeException($res->get_error_message()); }
foreach ((array) $res['tally'] as $k => $v) {
if (is_int($v)) { $totals[$k] = (int) ($totals[$k] ?? 0) + $v; }
}
if (!empty($res['tally']['error_samples']) && is_array($res['tally']['error_samples'])) {
$have = isset($totals['error_samples']) && is_array($totals['error_samples'])
? $totals['error_samples'] : array();
foreach ($res['tally']['error_samples'] as $sample) {
if (count($have) >= 50) { break; }
$have[] = $sample;
}
$totals['error_samples'] = $have;
}
if (!empty($res['tally']['group_notes']) && is_array($res['tally']['group_notes'])) {
$notes = isset($totals['group_notes']) && is_array($totals['group_notes'])
? $totals['group_notes'] : array();
foreach ($res['tally']['group_notes'] as $note) {
if (count($notes) >= 50) { break; }
$notes[] = $note;
}
$totals['group_notes'] = $notes;
}
foreach (array('created_samples', 'updated_samples') as $sk) {
if (empty($res['tally'][$sk]) || !is_array($res['tally'][$sk])) { continue; }
$have = isset($totals[$sk]) && is_array($totals[$sk]) ? $totals[$sk] : array();
foreach ($res['tally'][$sk] as $sample) {
if (count($have) >= 200) { break; }
$have[] = $sample;
}
$totals[$sk] = $have;
}
$carry = isset($res['carry']) && is_array($res['carry']) ? $res['carry'] : array();
$total_pages = max(1, (int) $res['total_pages']);
$prefiltered = max($prefiltered, (int) ($res['filtered_total'] ?? 0));
$slowest = max($slowest, time() - $page_started);
$exhausted = !empty($res['exhausted']);
$next = (int) ($res['next_after'] ?? $after);
if ($next <= $after) { $exhausted = true; }
$after = $next;
$walked++;
$projected = (time() - $started) + $slowest;
} while (!$exhausted
&& $walked < $max_pages
&& $projected < $max_seconds);
if ($prefiltered > 0) { $totals['filtered_out'] = $prefiltered; }
$complete = $exhausted;
if ($complete) {
delete_post_meta($id, '_aieo_feed_cursor');
} else {
update_post_meta($id, '_aieo_feed_cursor', wp_slash(array(
'after' => $after, 'carry' => $carry, 'totals' => $totals, 'plan' => $plan,
)));
$this->schedule_catch_up($id, $def);
}
$result['ok'] = true;
$result['totals'] = $totals;
$result['message'] = $complete
? sprintf(
__('Created %1$s, updated %2$s, skipped %3$s, %4$s errors.', 'ai-eshop-optimizer'),
number_format_i18n((int) ($totals['created'] ?? 0)),
number_format_i18n((int) ($totals['updated'] ?? 0)),
number_format_i18n((int) ($totals['skipped'] ?? 0)),
number_format_i18n((int) ($totals['errors'] ?? 0))
)
: sprintf(
__('Paused at page %1$s of %2$s; the next run carries on from there.', 'ai-eshop-optimizer'),
number_format_i18n($walked),
number_format_i18n($total_pages)
);
} catch (Exception $e) {
$result['ok'] = false;
$result['message'] = $e->getMessage();
}
delete_transient($lock);
AIEO_Feed_Source_Store::set_last_run($id, $result);
if (class_exists('AIEO_Feed_Run_Log') && ($complete || empty($result['ok']))) {
AIEO_Feed_Run_Log::record($id, $result, $complete);
}
}
private function schedule_catch_up($id, array $def) {
$schedule = (string) ($def['schedule'] ?? 'manual');
if ('' === $schedule || 'manual' === $schedule) { return; }
$delay = (int) apply_filters('aieo_catalog_feed_catch_up_delay', 60, (int) $id);
if ($delay <= 0) { return; }
$args = array((int) $id);
if (function_exists('as_schedule_single_action') && function_exists('as_has_scheduled_action')) {
if (!as_has_scheduled_action(self::CRON_HOOK, $args, self::AS_GROUP)) {
as_schedule_single_action(time() + $delay, self::CRON_HOOK, $args, self::AS_GROUP);
}
return;
}
wp_cache_delete('alloptions', 'options');
wp_cache_delete('cron', 'options');
wp_schedule_single_event(time() + $delay, self::CRON_HOOK, $args);
}
private static function is_background_run() {
if (defined('WP_CLI') && WP_CLI) { return true; }
return function_exists('wp_doing_cron') ? wp_doing_cron() : (defined('DOING_CRON') && DOING_CRON);
}
private static function run_max_seconds($background) {
$seconds = $background ? self::BACKGROUND_MAX_SECONDS : self::CRON_MAX_SECONDS;
$seconds = (int) apply_filters('aieo_catalog_feed_run_max_seconds', $seconds, $background);
return max(10, $seconds);
}
private static function run_max_pages($background) {
$pages = $background ? self::BACKGROUND_MAX_PAGES : self::CRON_MAX_PAGES;
$pages = (int) apply_filters('aieo_catalog_feed_run_max_pages', $pages, $background);
return max(1, $pages);
}
private function feed_plan_signature(array $def, array $options) {
return md5(serialize(array(
defined('AIEO_Generic_Feed_Source::PAGING_PLAN') ? AIEO_Generic_Feed_Source::PAGING_PLAN : '',
(int) self::PAGE_SIZE,
(int) ($def['version'] ?? 0),
(string) ($def['url'] ?? ''),
$def['filters'] ?? null,
$def['mapping'] ?? null,
$options['feed_cat_map'] ?? null,
$options['feed_rules'] ?? null,
(int) ($options['import_limit'] ?? 0),
(string) ($options['unmapped_policy'] ?? ''),
)));
}
private function feed_intelligence_options(array $options, array $def, $harvest) {
if (!class_exists('AIEO_Feed_Term_Stage') || !class_exists('AIEO_Feed_Cat_Map')) { return $options; }
if ($harvest) {
$harvested = AIEO_Feed_Term_Stage::harvest($def);
if (!is_wp_error($harvested) && class_exists('AIEO_Feed_Category_Correlator')) {
AIEO_Feed_Category_Correlator::refresh($def);
}
}
$prepared = AIEO_Feed_Term_Stage::prepare_filters((array) ($def['filters'] ?? array()));
if (null !== $prepared) { $options['feed_filters'] = $prepared; }
$map = AIEO_Feed_Cat_Map::map_for_feed($def);
if ($map) { $options['feed_cat_map'] = $map; }
if (!empty($def['rules']) && is_array($def['rules'])) {
$options['feed_rules'] = $def['rules'];
}
return $options;
}
private function posted_rules() {
if (!isset($_POST['rules']) || !class_exists('AIEO_Feed_Rules')) { return null; }
$decoded = json_decode((string) wp_unslash($_POST['rules']), true);
if (!is_array($decoded)) { return null; }
return AIEO_Feed_Rules::sanitize($decoded);
}
private function sources() {
$list = array();
foreach (array('AIEO_Efood_Catalog_Source', 'AIEO_Etsy_Catalog_Source', 'AIEO_Wolt_Catalog_Source', 'AIEO_Amazon_Catalog_Source') as $cls) {
if (class_exists($cls)) {
$s = new $cls();
$list[$s->slug()] = $s;
}
}
return apply_filters('aieo_catalog_import_sources', $list);
}
private function source($slug) {
$all = $this->sources();
return isset($all[$slug]) ? $all[$slug] : null;
}
private function creds_option($slug) { return 'aieo_catalog_import_' . sanitize_key($slug); }
private function get_creds($slug) {
$creds = get_option($this->creds_option($slug), array());
if (!is_array($creds)) { $creds = array(); }
$needed = array('chain_id', 'vendor_id', 'client_id', 'client_secret');
$missing = false;
foreach ($needed as $k) { if (empty($creds[$k])) { $missing = true; break; } }
if ($missing) {
$v = $this->moi_vendor_creds($slug);
foreach (array('chain_id', 'vendor_id', 'client_id', 'client_secret', 'base_url') as $k) {
if (empty($creds[$k]) && !empty($v[$k])) { $creds[$k] = $v[$k]; }
}
}
return $creds;
}
private function moi_vendor_creds($provider) {
global $wpdb;
$tbl = $wpdb->prefix . 'aieo_moi_vendors';
if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl)) !== $tbl) { return array(); }
$json = $wpdb->get_var($wpdb->prepare("SELECT credentials_json FROM {$tbl} WHERE provider = %s AND enabled = 1 ORDER BY id ASC LIMIT 1", $provider));
if (!$json) { return array(); }
$d = json_decode((string) $json, true);
return is_array($d) ? $d : array();
}
private function can() {
return current_user_can('manage_woocommerce') || current_user_can('manage_options');
}
private static function webp_default_quality() {
return class_exists('AIEO_Exchanger_Image_Resolver')
? (int) AIEO_Exchanger_Image_Resolver::WEBP_QUALITY_DEFAULT
: 82;
}
private static function empty_webp_totals() {
return array('converted' => 0, 'skipped' => 0, 'failed' => 0, 'bytes_saved' => 0, 'unsupported' => false);
}
private function engine_present() {
return class_exists(self::ENGINE_MARKER);
}
private function check($ok = true) {
if (!check_ajax_referer(self::NONCE, 'nonce', false)) { wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer'))); }
if (!$this->can()) { wp_send_json_error(array('message' => __('Not allowed.', 'ai-eshop-optimizer'))); }
if (!$this->engine_present()) {
wp_send_json_error(array('message' => __('Rooster One Pro is not installed. The catalogue import engine ships with the Pro plugin — install and activate it and this screen comes alive.', 'ai-eshop-optimizer')));
}
}
public function ajax_save_conn() {
$this->check();
$slug = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
$source = $this->source($slug);
if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); }
$existing = get_option($this->creds_option($slug), array());
if (!is_array($existing)) { $existing = array(); }
$new = $existing;
foreach ($source->credential_fields() as $f) {
$name = (string) $f['name'];
$key = 'cred_' . $name;
if (!isset($_POST[$key])) { continue; }
$val = sanitize_text_field(wp_unslash($_POST[$key]));
if (($f['type'] ?? 'text') === 'password' && $val === '') { continue; }
$new[$name] = $val;
}
update_option($this->creds_option($slug), $new, false);
wp_send_json_success(array('saved' => true));
}
private function drawn_table($id, array $cols, array $rows, array $opts = array()) {
if (!function_exists('rooster_admin_builders') || !rooster_admin_builders()) {
return array('html' => '', 'icons' => '');
}
$html = AIEO_Table::local($id, $cols, $rows, $opts + array('prefix' => $id . '_', 'sortable' => true));
return array('html' => $html, 'icons' => '' !== $html ? \Rooster\Admin\Ui::icons_of($html) : '');
}
private static function sample_chip($s) {
$s = is_scalar($s) ? (string) $s : '';
return '' . esc_html($s) . '';
}
private function structure_table(array $fields) {
$rows = array();
foreach (array_values($fields) as $i => $f) {
$path = (string) ($f['path'] ?? '');
$label = (string) ($f['label'] ?? '');
$name = ('' !== $label && $label !== $path) ? $label . ' [' . $path . ']' : $path;
$fill = (float) ($f['fill'] ?? 0);
$chips = '';
foreach ((array) ($f['samples'] ?? array()) as $sample) {
$chips .= self::sample_chip($sample);
}
$rows[] = array(
'field' => $name,
'fill' => array('title' => round($fill * 100) . '%', 'tone' => $fill < 0.5 ? 'warning' : ''),
'sample' => $chips,
'_id' => $i + 1,
'_s' => array('field' => $name, 'fill' => $fill, 'sample' => implode(' ', array_map('strval', array_filter((array) ($f['samples'] ?? array()), 'is_scalar')))),
);
}
return $this->drawn_table('aieo-cati-structure', array(
array('key' => 'field', 'label' => __('Field', 'ai-eshop-optimizer'), 'type' => 'code'),
array('key' => 'fill', 'label' => __('Filled in on', 'ai-eshop-optimizer'), 'sort' => 'number'),
array('key' => 'sample', 'label' => __('Example', 'ai-eshop-optimizer'), 'type' => 'html'),
), $rows, array('size' => 0));
}
private function dryrun_tables(array $variable, array $simple) {
$out = array('variable' => array(), 'simple' => '', 'icons' => '');
$icons = array();
foreach (array_values($variable) as $n => $v) {
$rows = array();
foreach (array_values((array) ($v['variations'] ?? array())) as $i => $x) {
$vals = array();
foreach ((array) ($x['values'] ?? array()) as $k => $val) {
$vals[] = $k . ': ' . (is_scalar($val) ? $val : '');
}
$meas = array_filter(array((string) ($x['weight'] ?? ''), (string) ($x['dims'] ?? '')), 'strlen');
$rows[] = array(
'sku' => (string) ($x['sku'] ?? ''),
'values' => implode(' · ', $vals),
'price' => (string) ($x['price'] ?? ''),
'stock' => (string) ($x['stock'] ?? ''),
'meas' => implode(' · ', $meas),
'_id' => $i + 1,
);
}
$t = $this->drawn_table('aieo-cati-dry-var-' . ($n + 1), array(
array('key' => 'sku', 'label' => __('SKU', 'ai-eshop-optimizer'), 'type' => 'code'),
array('key' => 'values', 'label' => __('Attributes', 'ai-eshop-optimizer')),
array('key' => 'price', 'label' => __('Price', 'ai-eshop-optimizer'), 'sort' => 'number'),
array('key' => 'stock', 'label' => __('Stock', 'ai-eshop-optimizer')),
array('key' => 'meas', 'label' => __('Weight and size', 'ai-eshop-optimizer')),
), $rows, array('size' => 0));
$out['variable'][] = $t['html'];
$icons[] = $t['icons'];
}
if ($simple) {
$rows = array();
foreach (array_values($simple) as $i => $p) {
$cats = implode(' › ', array_map(static function ($c) { return (string) ($c['name'] ?? ''); }, (array) ($p['category_terms'] ?? array())));
$attrs = implode(' · ', array_map(static function ($a) {
return (string) ($a['name'] ?? '') . ': ' . implode(', ', array_map(static function ($t) { return (string) ($t['name'] ?? ''); }, (array) ($a['terms'] ?? array())));
}, (array) ($p['attributes'] ?? array())));
$d = (array) ($p['dimensions'] ?? array());
$meas = array();
if (!empty($p['weight'])) { $meas[] = (string) $p['weight']; }
if (!empty($d['length']) || !empty($d['width']) || !empty($d['height'])) {
$meas[] = (!empty($d['length']) ? $d['length'] : '?') . ' × ' . (!empty($d['width']) ? $d['width'] : '?') . ' × ' . (!empty($d['height']) ? $d['height'] : '?');
}
$rows[] = array(
'title' => (string) ($p['title'] ?? ''),
'sku' => (string) ($p['match']['sku'] ?? ''),
'price' => (string) ($p['regular_price'] ?? ''),
'stock' => (string) ($p['stock']['status'] ?? ''),
'cats' => $cats,
'attrs' => $attrs,
'meas' => implode(' · ', $meas),
'_id' => $i + 1,
);
}
$t = $this->drawn_table('aieo-cati-dry-simple', array(
array('key' => 'title', 'label' => __('Title', 'ai-eshop-optimizer')),
array('key' => 'sku', 'label' => __('SKU', 'ai-eshop-optimizer'), 'type' => 'code'),
array('key' => 'price', 'label' => __('Price', 'ai-eshop-optimizer'), 'sort' => 'number'),
array('key' => 'stock', 'label' => __('Stock', 'ai-eshop-optimizer')),
array('key' => 'cats', 'label' => __('Category', 'ai-eshop-optimizer')),
array('key' => 'attrs', 'label' => __('Attributes', 'ai-eshop-optimizer')),
array('key' => 'meas', 'label' => __('Weight and size', 'ai-eshop-optimizer')),
), $rows, array('size' => 0));
$out['simple'] = $t['html'];
$icons[] = $t['icons'];
}
$out['icons'] = implode('', array_unique(array_filter($icons)));
return $out;
}
private static function catmap_status_label($st) {
$labels = array(
'auto' => __('applied automatically', 'ai-eshop-optimizer'),
'suggested' => __('suggestion — not applied', 'ai-eshop-optimizer'),
'confirmed' => __('confirmed', 'ai-eshop-optimizer'),
'manual' => __('picked by you', 'ai-eshop-optimizer'),
'rejected' => __('rejected', 'ai-eshop-optimizer'),
'learned' => __('from your earlier matches', 'ai-eshop-optimizer'),
);
return isset($labels[$st]) ? $labels[$st] : (string) $st;
}
private function catmap_table(array $rows, $threshold) {
if (!$rows || !function_exists('rooster_admin_builders') || !rooster_admin_builders()) {
return array('html' => '', 'icons' => '');
}
$prefix = 'catmap_';
$cols = array(
array('key' => 'vendor', 'label' => __('Feed category', 'ai-eshop-optimizer'), 'type' => 'code', 'sort' => 'none', 'sort_type' => 'text', 'sort_url' => '#'),
array('key' => 'ours', 'label' => __('Your category', 'ai-eshop-optimizer'), 'type' => 'html', 'sort' => 'none', 'sort_type' => 'text', 'sort_url' => '#'),
array('key' => 'score', 'label' => __('Match', 'ai-eshop-optimizer'), 'sort' => 'none', 'sort_type' => 'number', 'sort_url' => '#'),
array('key' => 'status', 'label' => __('Status', 'ai-eshop-optimizer'), 'type' => 'html', 'sort' => 'none', 'sort_type' => 'text', 'sort_url' => '#'),
array('key' => 'actions', 'label' => '', 'type' => 'actions'),
);
$list = array();
$statuses = array();
foreach ($rows as $r) {
$id = (int) $r['id'];
$term = (int) $r['term_id'];
$missing = !empty($r['term_missing']);
$st = (string) $r['status'];
$word = self::catmap_status_label($st);
$statuses[$st] = $word;
$chosen = $term > 0
? ''
: '';
$score = (float) $r['score'];
$list[] = array(
'vendor' => (string) $r['vendor_path'],
'ours' => '',
'score' => array('title' => round($score * 100) . '%', 'tone' => $score >= (float) $threshold ? 'success' : ''),
'status' => '' . esc_html($word) . '',
'actions' => \Rooster\Admin\Ui::button(__('Confirm', 'ai-eshop-optimizer'), array('size' => 'sm', 'class' => 'aieo-cati-catmap-ok'))
. ' ' . \Rooster\Admin\Ui::button(__('Reject', 'ai-eshop-optimizer'), array('size' => 'sm', 'variant' => 'ghost', 'class' => 'aieo-cati-catmap-no')),
'_id' => $id,
'_name' => (string) $r['vendor_path'],
'_attrs' => array(
'data-row-id' => $id,
'data-orig-term' => $term,
'data-ra-f' => array('status' => array($st)),
'data-ra-s' => array('vendor' => (string) $r['vendor_path'], 'ours' => (string) $r['term_label'], 'score' => $score, 'status' => $word, '_id' => $id),
'data-ra-text' => (string) $r['vendor_path'],
),
);
}
$button = static function ($label, $op, $variant = '') {
$opts = array('size' => 'sm', 'type' => 'submit', 'attrs' => array_merge(array('name' => 'aieo_catmap_op', 'value' => $op), \Rooster\Admin\States::confirm_attrs('aieo-cati-catmap-' . $op)));
if ('' !== $variant) { $opts['variant'] = $variant; }
return \Rooster\Admin\Ui::button($label, $opts);
};
$bulk = ' '
. $button(__('Confirm selected', 'ai-eshop-optimizer'), 'confirm')
. ' ' . $button(__('Reject selected', 'ai-eshop-optimizer'), 'reject', 'destructive')
. ' ' . $button(__('Set category on selected', 'ai-eshop-optimizer'), 'set');
asort($statuses);
$html = '
' . \Rooster\Admin\States::outcome(sprintf( __('Connected ✓ — %1$s categories, %2$s product page(s) of catalogue.', 'ai-eshop-optimizer'), number_format_i18n(count((array) $cats)), number_format_i18n((int) $page['total_pages']) ), 'success') . '
'; $table = $this->drawn_table('aieo-cati-sample', array( array('key' => 'title', 'label' => __('Title', 'ai-eshop-optimizer')), array('key' => 'sku', 'label' => __('SKU', 'ai-eshop-optimizer'), 'type' => 'code'), array('key' => 'price', 'label' => __('Price', 'ai-eshop-optimizer'), 'sort' => 'number'), array('key' => 'stock', 'label' => __('Stock', 'ai-eshop-optimizer')), array('key' => 'cats', 'label' => __('Cats', 'ai-eshop-optimizer'), 'type' => 'num'), ), $samples, array('size' => 0, 'empty' => esc_html__('No products returned.', 'ai-eshop-optimizer'))); $html .= $table['html']; wp_send_json_success(array('html' => $html, 'icons' => $table['icons'])); } public function ajax_import_start() { $this->check(); $slug = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : ''; $source = $this->source($slug); if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); } $creds = $this->get_creds($slug); $valid = $source->validate_credentials($creds); if (is_wp_error($valid)) { wp_send_json_error(array('message' => $valid->get_error_message())); } $options = array( 'status' => (isset($_POST['opt_status']) && $_POST['opt_status'] === 'publish') ? 'publish' : 'draft', 'mode' => isset($_POST['opt_mode']) ? sanitize_key(wp_unslash($_POST['opt_mode'])) : 'new_only', 'images' => !empty($_POST['opt_images']) ? 1 : 0, 'categories' => !empty($_POST['opt_categories']) ? 1 : 0, 'category_ancestors' => array_key_exists('opt_cat_ancestors', $_POST) ? (!empty($_POST['opt_cat_ancestors']) ? 1 : 0) : 1, 'option_groups' => !empty($_POST['opt_option_groups']) ? 1 : 0, 'variations' => !empty($_POST['opt_variations']) ? 1 : 0, 'webp' => !empty($_POST['opt_webp']) ? 1 : 0, 'webp_quality' => isset($_POST['opt_webp_quality']) ? max(1, min(100, (int) $_POST['opt_webp_quality'])) : self::webp_default_quality(), ); if (!in_array($options['mode'], array('price_stock', 'new_only', 'enrich', 'create_update', 'update_only'), true)) { $options['mode'] = 'new_only'; } $options['source_slug'] = $slug; $options['source_label'] = $source->label(); if ($source instanceof AIEO_Generic_Feed_Source) { $options['supplier_term_id'] = $source->supplier_term_id(); $feed_def = AIEO_Feed_Source_Store::get((int) substr($slug, strlen('feed_'))); if ($feed_def) { $options['unmapped_policy'] = (string) ($feed_def['options']['unmapped_policy'] ?? 'create'); $options = $this->feed_intelligence_options($options, $feed_def, false); } } $cats = $source->fetch_categories($creds); if (is_wp_error($cats)) { wp_send_json_error(array('message' => $cats->get_error_message())); } if ($source instanceof AIEO_Generic_Feed_Source && method_exists($source, 'set_run_options')) { $source->set_run_options($options); } $page1 = $source->fetch_page($creds, 1, self::PAGE_SIZE); if (is_wp_error($page1)) { wp_send_json_error(array('message' => $page1->get_error_message())); } $total_pages = max(1, (int) $page1['total_pages']); global $wpdb; $job_id = wp_generate_password(16, false, false); $wpdb->insert($wpdb->prefix . 'aieo_dmm_export_jobs', array( 'job_id' => $job_id, 'type' => 'catalog_import', 'status' => 'running', 'total' => $total_pages, 'processed' => 0, 'params' => wp_json_encode(array( 'slug' => $slug, 'options' => $options, 'category_map' => $cats, 'page_size' => self::PAGE_SIZE, 'carry' => array(), 'totals' => array('processed' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => 0, 'error_samples' => array(), 'webp' => self::empty_webp_totals(), 'variable_created' => 0, 'variable_refused' => 0, 'group_notes' => array(), 'filtered_out' => 0, 'brand_supplier_linked' => 0), )), 'user_id' => get_current_user_id(), ), array('%s', '%s', '%s', '%d', '%d', '%s', '%d')); wp_send_json_success(array('job_id' => $job_id, 'total_pages' => $total_pages)); } public function ajax_import_process() { $this->check(); $job_id = isset($_POST['job_id']) ? sanitize_text_field(wp_unslash($_POST['job_id'])) : ''; global $wpdb; $jobs = $wpdb->prefix . 'aieo_dmm_export_jobs'; $job = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$jobs} WHERE job_id = %s", $job_id), ARRAY_A); if (!$job || $job['type'] !== 'catalog_import') { wp_send_json_error(array('message' => __('Invalid job.', 'ai-eshop-optimizer'))); } $params = json_decode((string) $job['params'], true); if (!is_array($params)) { wp_send_json_error(array('message' => __('Corrupted job.', 'ai-eshop-optimizer'))); } $slug = (string) ($params['slug'] ?? ''); $source = $this->source($slug); if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); } $total_pages = max(1, (int) $job['total']); $page = (int) $job['processed'] + 1; $after = (int) ($params['after'] ?? 0); $cursor = ($source instanceof AIEO_Generic_Feed_Source) ? $after : $page; if ($page > $total_pages && !($source instanceof AIEO_Generic_Feed_Source)) { $wpdb->update($jobs, array('status' => 'done'), array('job_id' => $job_id)); wp_send_json_success($this->progress($params, $total_pages, $total_pages, true)); } $res = AIEO_Catalog_Import_Runner::run_batch( $source, $this->get_creds($slug), (array) $params['options'], (array) $params['category_map'], $cursor, (int) ($params['page_size'] ?? self::PAGE_SIZE), isset($params['carry']) && is_array($params['carry']) ? $params['carry'] : array() ); if (is_wp_error($res)) { $params['totals']['errors']++; if (count($params['totals']['error_samples']) < 50) { $params['totals']['error_samples'][] = array('sku' => 'page ' . $page, 'error' => $res->get_error_message()); } } else { $t = $res['tally']; foreach (array('processed', 'created', 'updated', 'skipped', 'errors', 'variable_created', 'variable_refused', 'filtered_out', 'brand_supplier_linked') as $k) { $params['totals'][$k] = (int) ($params['totals'][$k] ?? 0) + (int) ($t[$k] ?? 0); } $params['carry'] = isset($res['carry']) && is_array($res['carry']) ? $res['carry'] : array(); foreach ((array) ($t['group_notes'] ?? array()) as $note) { if (count($params['totals']['group_notes'] ?? array()) < 50) { $params['totals']['group_notes'][] = $note; } } foreach ((array) $t['error_samples'] as $e) { if (count($params['totals']['error_samples']) < 50) { $params['totals']['error_samples'][] = $e; } } if (!empty($t['webp']) && is_array($t['webp'])) { $carried = isset($params['totals']['webp']) && is_array($params['totals']['webp']) ? $params['totals']['webp'] : self::empty_webp_totals(); foreach (array('converted', 'skipped', 'failed', 'bytes_saved') as $k) { $carried[$k] = (int) ($carried[$k] ?? 0) + (int) ($t['webp'][$k] ?? 0); } if (!empty($t['webp']['unsupported'])) { $carried['unsupported'] = true; } $params['totals']['webp'] = $carried; } if ((int) $res['total_pages'] > $total_pages) { $total_pages = (int) $res['total_pages']; } if (isset($res['next_after'])) { $params['after'] = (int) $res['next_after']; } } $complete = ($source instanceof AIEO_Generic_Feed_Source) ? (!is_wp_error($res) && !empty($res['exhausted'])) : ($page >= $total_pages); $wpdb->update($jobs, array( 'processed' => $page, 'total' => $total_pages, 'status' => $complete ? 'done' : 'running', 'params' => wp_json_encode($params), ), array('job_id' => $job_id)); wp_send_json_success($this->progress($params, $page, $total_pages, $complete)); } private function progress($params, $page, $total_pages, $complete) { $pct = $total_pages > 0 ? (int) round(100 * min($page, $total_pages) / $total_pages) : 100; return array( 'page' => (int) $page, 'total_pages' => (int) $total_pages, 'percentage' => $pct, 'complete' => (bool) $complete, 'totals' => $params['totals'], ); } private function require_pro() { if (!self::is_aieo_pro_user()) { wp_send_json_error(array('message' => __('Generating a source from a feed requires the Pro version.', 'ai-eshop-optimizer'))); } } private function draft_key() { return 'aieo_feed_draft_' . get_current_user_id(); } private function save_draft($xml) { $xml = (string) $xml; set_transient( $this->draft_key(), class_exists('AIEO_Feed_Structure_Inference') ? AIEO_Feed_Structure_Inference::pack($xml) : $xml, HOUR_IN_SECONDS ); } private function max_browser_feed_bytes() { $ceiling = class_exists('AIEO_Feed_Structure_Inference') ? (int) AIEO_Feed_Structure_Inference::MAX_BYTES : 16777216; $post_max = (int) wp_convert_hr_to_bytes((string) ini_get('post_max_size')); if ($post_max <= 0) { return $ceiling; } return max(262144, min($ceiling, (int) floor($post_max / 3))); } private function read_draft() { $stored = get_transient($this->draft_key()); if (class_exists('AIEO_Feed_Structure_Inference')) { $stored = AIEO_Feed_Structure_Inference::unpack($stored); } return is_string($stored) ? $stored : ''; } public function ajax_feed_analyze() { $this->check(); $this->require_pro(); $xml = isset($_POST['xml']) ? (string) wp_unslash($_POST['xml']) : ''; $url = isset($_POST['url']) ? esc_url_raw(trim((string) wp_unslash($_POST['url']))) : ''; if (trim($xml) === '' && $url !== '') { if (!wp_http_validate_url($url)) { wp_send_json_error(array('message' => __('That feed address is not one this server will fetch.', 'ai-eshop-optimizer'))); } $res = wp_safe_remote_get($url, array('timeout' => 60, 'user-agent' => 'Rooster One Feed Importer')); if (is_wp_error($res)) { wp_send_json_error(array('message' => $res->get_error_message())); } $code = (int) wp_remote_retrieve_response_code($res); if ($code < 200 || $code >= 300) { wp_send_json_error(array('message' => sprintf( __('The feed address answered with %s.', 'ai-eshop-optimizer'), (string) $code ))); } $xml = (string) wp_remote_retrieve_body($res); } if (trim($xml) === '') { $xml = $this->read_draft(); } if (trim($xml) === '') { wp_send_json_error(array('message' => __('Paste a feed, or give an address to fetch one from.', 'ai-eshop-optimizer'))); } $record_path = isset($_POST['record_path']) ? sanitize_text_field(wp_unslash($_POST['record_path'])) : ''; $analysis = AIEO_Feed_Structure_Inference::analyze($xml, $record_path); if (is_wp_error($analysis)) { wp_send_json_error(array('message' => $analysis->get_error_message())); } $this->save_draft($xml); wp_send_json_success(array( 'analysis' => $analysis, 'proposal' => AIEO_Feed_Mapping::propose($analysis['fields']), 'targets' => $this->target_shapes(), 'structure' => $this->structure_table((array) $analysis['fields']), )); } private function affix_target_shapes() { $out = array(); if (class_exists('AIEO_Feed_Rules')) { foreach (AIEO_Feed_Rules::affix_targets() as $key => $label) { $out[] = array('key' => $key, 'label' => (string) $label); } } return $out; } private function target_shapes() { $out = array(); foreach (AIEO_Feed_Mapping::targets() as $key => $spec) { $out[] = array( 'key' => $key, 'label' => (string) $spec['label'], 'help' => (string) ($spec['help'] ?? ''), 'required' => !empty($spec['required']), 'repeatable' => !empty($spec['repeatable']), 'multi' => !empty($spec['multi']), ); } return $out; } public function ajax_feed_dryrun() { $this->check(); $this->require_pro(); $xml = $this->read_draft(); if (trim($xml) === '') { wp_send_json_error(array('message' => __('The feed sample has expired. Read the feed again.', 'ai-eshop-optimizer'))); } $mapping = $this->posted_mapping(); $valid = AIEO_Feed_Mapping::validate($mapping); if (is_wp_error($valid)) { wp_send_json_error(array('message' => $valid->get_error_message())); } $records = AIEO_Feed_Structure_Inference::extract($xml, (string) $mapping['record_path'], 60); if (is_wp_error($records)) { wp_send_json_error(array('message' => $records->get_error_message())); } if (!$records) { wp_send_json_error(array('message' => __('That product row matched nothing in the feed.', 'ai-eshop-optimizer'))); } $apply_options = array('status' => 'draft'); $prepared = null; $dry_def = null; $dry_id = isset($_POST['id']) ? (int) $_POST['id'] : 0; if ($dry_id > 0 && class_exists('AIEO_Feed_Term_Stage') && class_exists('AIEO_Feed_Cat_Map')) { $dry_def = AIEO_Feed_Source_Store::get($dry_id); if ($dry_def) { $prepared = AIEO_Feed_Term_Stage::prepare_filters((array) ($dry_def['filters'] ?? array())); $dry_map = AIEO_Feed_Cat_Map::map_for_feed($dry_def); if ($dry_map) { $apply_options['feed_cat_map'] = $dry_map; $apply_options['unmapped_policy'] = (string) ($dry_def['options']['unmapped_policy'] ?? 'create'); } } } $dry_rules = $this->posted_rules(); if (null === $dry_rules && $dry_def) { $dry_rules = (array) ($dry_def['rules'] ?? array()); } if ($dry_rules) { $apply_options['feed_rules'] = $dry_rules; } $flat = array(); $groups = array(); $filtered = 0; foreach ($records as $record) { $mapped = AIEO_Feed_Mapping::apply($record, $mapping, $apply_options); $payload = $mapped['payload']; if (empty($payload['match']['sku'])) { continue; } if (null !== $prepared && !AIEO_Feed_Term_Stage::row_passes($payload, $prepared)) { $filtered++; continue; } if (!empty($payload['category_unmapped'])) { $filtered++; continue; } unset($payload['vendor_category_values'], $payload['category_unmapped']); $key = isset($mapped['group']['key']) ? trim((string) $mapped['group']['key']) : ''; if ($key !== '') { $groups[$key][] = array('payload' => $payload, 'axes' => (array) ($mapped['group']['axes'] ?? array())); } else { $flat[] = $payload; } } $built = array(); $refused = array(); foreach ($groups as $key => $rows) { if (count($rows) < 2) { $flat[] = $rows[0]['payload']; continue; } $preview = AIEO_Catalog_Variation_Builder::preview($key, $rows); if (is_wp_error($preview)) { $refused[] = array('key' => (string) $key, 'reason' => $preview->get_error_message()); foreach ($rows as $row) { $flat[] = $row['payload']; } continue; } $built[] = $preview; } $simple_rows = array_slice($flat, 0, 10); $variable_rows = array_slice($built, 0, 5); wp_send_json_success(array( 'simple' => $simple_rows, 'variable' => $variable_rows, 'tables' => $this->dryrun_tables($variable_rows, $simple_rows), 'refused' => $refused, 'counts' => array( 'records' => count($records), 'simple' => count($flat), 'variable' => count($built), 'refused' => count($refused), 'filtered' => $filtered, ), )); } public function ajax_feed_save() { $this->check(); $this->require_pro(); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : ''; $url = isset($_POST['url']) ? esc_url_raw(trim((string) wp_unslash($_POST['url']))) : ''; $schedule = isset($_POST['schedule']) ? sanitize_key(wp_unslash($_POST['schedule'])) : 'manual'; $mapping = $this->posted_mapping(); $supplier_term_id = isset($_POST['supplier_term_id']) ? (int) $_POST['supplier_term_id'] : 0; $supplier_new = isset($_POST['supplier_new']) ? sanitize_text_field(wp_unslash($_POST['supplier_new'])) : ''; if ($supplier_new !== '' && taxonomy_exists('supplier')) { $existing_term = term_exists($supplier_new, 'supplier'); if (is_array($existing_term) && !empty($existing_term['term_id'])) { $supplier_term_id = (int) $existing_term['term_id']; } elseif (is_numeric($existing_term) && (int) $existing_term > 0) { $supplier_term_id = (int) $existing_term; } else { $created_term = wp_insert_term($supplier_new, 'supplier'); if (is_wp_error($created_term)) { wp_send_json_error(array('message' => $created_term->get_error_message())); } $supplier_term_id = (int) $created_term['term_id']; } } $options = array( 'status' => isset($_POST['opt_status']) ? sanitize_key(wp_unslash($_POST['opt_status'])) : 'draft', 'mode' => isset($_POST['opt_mode']) ? sanitize_key(wp_unslash($_POST['opt_mode'])) : 'new_only', 'images' => !empty($_POST['opt_images']) ? 1 : 0, 'categories' => !empty($_POST['opt_categories']) ? 1 : 0, 'category_ancestors' => array_key_exists('opt_cat_ancestors', $_POST) ? (!empty($_POST['opt_cat_ancestors']) ? 1 : 0) : 1, 'variations' => !empty($_POST['opt_variations']) ? 1 : 0, 'webp' => !empty($_POST['opt_webp']) ? 1 : 0, 'webp_quality' => isset($_POST['opt_webp_quality']) ? (int) $_POST['opt_webp_quality'] : self::webp_default_quality(), 'unmapped_policy' => isset($_POST['opt_unmapped_policy']) ? sanitize_key(wp_unslash($_POST['opt_unmapped_policy'])) : 'create', 'import_limit' => isset($_POST['opt_import_limit']) ? (int) $_POST['opt_import_limit'] : 0, ); $schedule_hour = isset($_POST['schedule_hour']) ? (int) $_POST['schedule_hour'] : -1; $schedule_day = isset($_POST['schedule_day']) ? (int) $_POST['schedule_day'] : -1; $saved = AIEO_Feed_Source_Store::save($id, $name, $mapping, $url, $schedule, $options, $supplier_term_id, $schedule_hour, $schedule_day); if (is_wp_error($saved)) { wp_send_json_error(array('message' => $saved->get_error_message())); } $this->arm_schedule((int) $saved, AIEO_Feed_Source_Store::get_schedule((int) $saved)); $armed = AIEO_Feed_Source_Store::get_schedule((int) $saved); $xml = $this->read_draft(); if (trim($xml) !== '') { AIEO_Feed_Source_Store::save_sample((int) $saved, $xml); } if (isset($_POST['filters'])) { $posted_filters = json_decode((string) wp_unslash($_POST['filters']), true); AIEO_Feed_Source_Store::save_filters((int) $saved, is_array($posted_filters) ? $posted_filters : array()); } $posted_rules = $this->posted_rules(); if (null !== $posted_rules) { AIEO_Feed_Source_Store::save_rules((int) $saved, $posted_rules); } $saved_def = AIEO_Feed_Source_Store::get((int) $saved); if ($saved_def && class_exists('AIEO_Feed_Term_Stage')) { $harvested = AIEO_Feed_Term_Stage::harvest($saved_def); if (!is_wp_error($harvested) && class_exists('AIEO_Feed_Category_Correlator')) { AIEO_Feed_Category_Correlator::refresh($saved_def); } } $message = ('manual' === $armed) ? __('Saved. It is now one of the sources on the Import tab.', 'ai-eshop-optimizer') : sprintf( __('Saved and scheduled: %s. It is also one of the sources on the Import tab.', 'ai-eshop-optimizer'), (string) AIEO_Feed_Source_Store::schedules()[$armed] ); if ('manual' === $armed && isset($_POST['schedule']) && 'manual' !== sanitize_key(wp_unslash($_POST['schedule'])) && '' === $url) { $message = __('Saved, but not scheduled: a scheduled import needs a feed address to fetch from. A pasted sample never changes, so re-importing it on a timer would rewrite the same products for ever.', 'ai-eshop-optimizer'); } wp_send_json_success(array( 'id' => (int) $saved, 'schedule' => $armed, 'message' => $message, )); } public function ajax_feed_load() { $this->check(); $this->require_pro(); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $def = AIEO_Feed_Source_Store::get($id); if (!$def) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } $xml = AIEO_Feed_Source_Store::get_sample($id); if (trim($xml) === '' && $def['url'] !== '') { $res = wp_safe_remote_get($def['url'], array('timeout' => 60, 'user-agent' => 'Rooster One Feed Importer')); if (!is_wp_error($res)) { $code = (int) wp_remote_retrieve_response_code($res); if ($code >= 200 && $code < 300) { $xml = (string) wp_remote_retrieve_body($res); } } } if (trim($xml) === '') { wp_send_json_error(array('message' => __('This source has no stored sample and nothing could be fetched from its address. Paste a fresh sample, analyze it, and save: with the same source open, Save updates it.', 'ai-eshop-optimizer'))); } $analysis = AIEO_Feed_Structure_Inference::analyze($xml, (string) ($def['mapping']['record_path'] ?? '')); if (is_wp_error($analysis)) { wp_send_json_error(array('message' => $analysis->get_error_message())); } $this->save_draft($xml); if (class_exists('AIEO_Feed_Term_Stage')) { $harvested = AIEO_Feed_Term_Stage::harvest($def); if (!is_wp_error($harvested) && class_exists('AIEO_Feed_Category_Correlator')) { AIEO_Feed_Category_Correlator::refresh($def); } } $filter_options = array(); if (class_exists('AIEO_Feed_Term_Stage')) { $all_ids = array(); foreach (array('include', 'exclude') as $side) { foreach (AIEO_Feed_Term_Stage::kinds() as $kind) { foreach ((array) ($def['filters'][$side][$kind] ?? array()) as $fid) { $all_ids[] = (int) $fid; } } } foreach (AIEO_Feed_Term_Stage::rows_by_ids($all_ids) as $fid => $row) { $filter_options[$fid] = (string) $row['value']; } } $shown = array(); foreach ((array) ($analysis['fields'] ?? array()) as $f) { if (empty($f['virtual'])) { $shown[] = $f; } } foreach ((array) ($def['rules'] ?? array()) as $r2) { if ('derive' === ($r2['type'] ?? '') && '' !== (string) ($r2['name'] ?? '')) { $shown[] = array('path' => 'rule:' . $r2['name'], 'label' => 'rule:' . $r2['name'], 'fill' => 1, 'samples' => array()); } } unset($def['history'], $def['sample']); wp_send_json_success(array( 'definition' => $def, 'analysis' => $analysis, 'structure' => $this->structure_table($shown), 'targets' => $this->target_shapes(), 'filter_options' => $filter_options, )); } public function ajax_feed_run_now() { $this->check(); $this->require_pro(); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; if (!AIEO_Feed_Source_Store::get($id)) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } $override = !empty($_POST['refresh_all']) ? 'create_update' : ''; $this->run_scheduled_import($id, $override); $last = AIEO_Feed_Source_Store::get_last_run($id); wp_send_json_success(array( 'ok' => !empty($last['ok']), 'message' => (string) ($last['message'] ?? ''), )); } public function ajax_feed_link_brands() { $this->check(); $this->require_pro(); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $dry = !empty($_POST['dry']); $def = AIEO_Feed_Source_Store::get($id); if (!$def) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } $supplier = (int) ($def['supplier_term_id'] ?? 0); if ($supplier <= 0) { wp_send_json_error(array('message' => __('This source has no supplier, so there is nothing to link its brands to. Set one above and save first.', 'ai-eshop-optimizer'))); } if (!taxonomy_exists('product_brand')) { wp_send_json_error(array('message' => __('Product brands are not available on this shop.', 'ai-eshop-optimizer'))); } if (!class_exists('AIEO_DMM_Brand_Extras_Data')) { $data_file = AIEO_DIR . 'includes/dmm/class-aieo-dmm-brand-extras-data.php'; if (file_exists($data_file)) { require_once $data_file; } } if (!class_exists('AIEO_DMM_Brand_Extras_Data')) { wp_send_json_error(array('message' => __('The brand records are not available.', 'ai-eshop-optimizer'))); } $values = AIEO_Feed_Term_Stage::all_values($def, 'brand'); if (!$values) { wp_send_json_error(array('message' => __('This feed has no brands staged yet. Save the source once so its vocabulary is read, then try again.', 'ai-eshop-optimizer'))); } $to_link = array(); $already = array(); $unknown = array(); foreach ($values as $value) { $term = get_term_by('name', $value, 'product_brand'); if (!$term || is_wp_error($term)) { $term = get_term_by('slug', sanitize_title($value), 'product_brand'); } if (!$term || is_wp_error($term)) { $unknown[] = $value; continue; } $extras = AIEO_DMM_Brand_Extras_Data::get('product_brand', (int) $term->term_id); $owner = (int) ($extras['supplier_term_id'] ?? 0); if ($owner > 0) { $already[] = array('brand' => (string) $term->name, 'mine' => ($owner === $supplier)); continue; } $to_link[] = array('id' => (int) $term->term_id, 'brand' => (string) $term->name, 'products' => (int) $term->count); } $linked = 0; if (!$dry) { foreach ($to_link as $row) { AIEO_DMM_Brand_Extras_Data::save('product_brand', (int) $row['id'], array('supplier_term_id' => $supplier)); $linked++; } } $products = 0; foreach ($to_link as $row) { $products += (int) $row['products']; } $supplier_term = get_term($supplier, 'supplier'); wp_send_json_success(array( 'dry' => $dry ? 1 : 0, 'supplier' => ($supplier_term && !is_wp_error($supplier_term)) ? (string) $supplier_term->name : ('#' . $supplier), 'staged' => count($values), 'to_link' => count($to_link), 'linked' => $linked, 'already' => count($already), 'already_others' => count(array_filter($already, function ($a) { return empty($a['mine']); })), 'unknown' => count($unknown), 'products' => $products, 'samples' => array_slice(array_map(function ($r) { return $r['brand']; }, $to_link), 0, 12), 'unknown_samples' => array_slice($unknown, 0, 8), )); } public function ajax_feed_delete() { $this->check(); $this->require_pro(); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; if (!AIEO_Feed_Source_Store::delete($id)) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } wp_send_json_success(array('deleted' => true)); } public function ajax_feed_search_terms() { if (!class_exists('AIEO_DMM')) { wp_send_json(array('results' => array())); } AIEO_DMM::verify_ajax_request(); if (!$this->engine_present()) { wp_send_json(array('results' => array())); } $ctx = isset($_GET['ctx']) ? sanitize_text_field(wp_unslash($_GET['ctx'])) : ''; $parts = explode('|', $ctx); $def = AIEO_Feed_Source_Store::get((int) ($parts[0] ?? 0)); $kind = sanitize_key((string) ($parts[1] ?? '')); if (!$def || !class_exists('AIEO_Feed_Term_Stage')) { wp_send_json(array('results' => array())); } $q = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : ''; wp_send_json(array('results' => AIEO_Feed_Term_Stage::search($def, $kind, $q))); } private function catmap_def() { $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $def = AIEO_Feed_Source_Store::get($id); if (!$def || !class_exists('AIEO_Feed_Cat_Map')) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } return $def; } private function catmap_rows(array $def) { $rows = array(); foreach (AIEO_Feed_Cat_Map::rows_for_def($def) as $row) { $term_id = (int) $row['term_id']; $label = ''; if ($term_id > 0) { $term = get_term($term_id, 'product_cat'); if ($term && !is_wp_error($term)) { $label = $term->name; } } $rows[] = array( 'id' => (int) $row['id'], 'vendor_path' => (string) $row['vendor_path'], 'term_id' => $term_id, 'term_label' => $label, 'term_missing' => ($term_id > 0 && '' === $label), 'score' => (float) $row['score'], 'status' => (string) $row['status'], ); } return $rows; } public function ajax_feed_catmap_health() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); $suggested = 0; $missing = 0; $applied = 0; $applied_statuses = AIEO_Feed_Cat_Map::applied_statuses(); foreach ($this->catmap_rows($def) as $row) { if (!empty($row['term_missing'])) { $missing++; continue; } if ('suggested' === $row['status'] && (int) $row['term_id'] > 0) { $suggested++; continue; } if (in_array($row['status'], $applied_statuses, true) && (int) $row['term_id'] > 0) { $applied++; } } wp_send_json_success(array( 'suggested' => $suggested, 'missing' => $missing, 'applied' => $applied, )); } public function ajax_feed_catmap_list() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); $rows = $this->catmap_rows($def); wp_send_json_success(array( 'rows' => $rows, 'threshold' => AIEO_Feed_Category_Correlator::threshold(), 'scope' => AIEO_Feed_Cat_Map::owner($def), 'table' => $this->catmap_table($rows, AIEO_Feed_Category_Correlator::threshold()), )); } public function ajax_feed_catmap_suggest() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); if (class_exists('AIEO_Feed_Term_Stage')) { $harvested = AIEO_Feed_Term_Stage::harvest($def); if (is_wp_error($harvested)) { wp_send_json_error(array('message' => $harvested->get_error_message())); } } $result = AIEO_Feed_Category_Correlator::refresh($def); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message())); } $rows = $this->catmap_rows($def); wp_send_json_success(array( 'rows' => $rows, 'threshold' => AIEO_Feed_Category_Correlator::threshold(), 'result' => $result, 'table' => $this->catmap_table($rows, AIEO_Feed_Category_Correlator::threshold()), )); } public function ajax_feed_catmap_save() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); $row_id = isset($_POST['row_id']) ? (int) $_POST['row_id'] : 0; $term_id = isset($_POST['term_id']) ? (int) $_POST['term_id'] : 0; $status = isset($_POST['status']) ? sanitize_key(wp_unslash($_POST['status'])) : ''; if ('rejected' !== $status) { if ($term_id <= 0 || !term_exists($term_id, 'product_cat')) { wp_send_json_error(array('message' => __('Pick one of your categories first.', 'ai-eshop-optimizer'))); } } if (!AIEO_Feed_Cat_Map::set_status($def, $row_id, $term_id, $status)) { wp_send_json_error(array('message' => __('That mapping row could not be updated.', 'ai-eshop-optimizer'))); } wp_send_json_success(array('saved' => true)); } public function ajax_feed_catmap_bulk() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); $ids = isset($_POST['row_ids']) ? array_values(array_unique(array_filter(array_map('intval', (array) wp_unslash($_POST['row_ids']))))) : array(); $op = isset($_POST['op']) ? sanitize_key(wp_unslash($_POST['op'])) : ''; if (!$ids) { wp_send_json_error(array('message' => __('Select at least one row first.', 'ai-eshop-optimizer'))); } if (count($ids) > 500) { wp_send_json_error(array('message' => __('Too many rows in one request; work in batches of up to 500.', 'ai-eshop-optimizer'))); } $done = 0; $skipped = 0; if ('set' === $op) { $term_id = isset($_POST['term_id']) ? (int) $_POST['term_id'] : 0; if ($term_id <= 0 || !term_exists($term_id, 'product_cat')) { wp_send_json_error(array('message' => __('Pick one of your categories first.', 'ai-eshop-optimizer'))); } foreach ($ids as $rid) { if (AIEO_Feed_Cat_Map::set_status($def, $rid, $term_id, 'manual')) { $done++; } else { $skipped++; } } } elseif ('reject' === $op) { foreach ($ids as $rid) { if (AIEO_Feed_Cat_Map::set_status($def, $rid, 0, 'rejected')) { $done++; } else { $skipped++; } } } elseif ('confirm' === $op) { $terms = array(); foreach ($this->catmap_rows($def) as $r) { $terms[(int) $r['id']] = (int) $r['term_id']; } foreach ($ids as $rid) { $t = isset($terms[$rid]) ? (int) $terms[$rid] : 0; if ($t > 0 && AIEO_Feed_Cat_Map::set_status($def, $rid, $t, 'confirmed')) { $done++; } else { $skipped++; } } } else { wp_send_json_error(array('message' => __('Unknown bulk operation.', 'ai-eshop-optimizer'))); } $rows = $this->catmap_rows($def); wp_send_json_success(array( 'done' => $done, 'skipped' => $skipped, 'rows' => $rows, 'table' => $this->catmap_table($rows, AIEO_Feed_Category_Correlator::threshold()), )); } public function ajax_feed_catmap_accept() { $this->check(); $this->require_pro(); $def = $this->catmap_def(); $floor = isset($_POST['min_score']) ? (float) $_POST['min_score'] : AIEO_Feed_Category_Correlator::threshold(); $done = AIEO_Feed_Cat_Map::accept_at_least($def, $floor); $rows = $this->catmap_rows($def); wp_send_json_success(array('accepted' => (int) $done, 'rows' => $rows, 'table' => $this->catmap_table($rows, AIEO_Feed_Category_Correlator::threshold()))); } private function vocab_def() { if (!class_exists('AIEO_Docscan_Vocab') || !class_exists('AIEO_Match_Text')) { wp_send_json_error(array('message' => __('The document scanner engine is not installed.', 'ai-eshop-optimizer'))); } $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $def = AIEO_Feed_Source_Store::get($id); if (!$def) { wp_send_json_error(array('message' => __('That source no longer exists.', 'ai-eshop-optimizer'))); } if (empty($def['supplier_term_id'])) { wp_send_json_error(array('message' => __('Assign a supplier to this feed first — the vocabulary is stored per supplier.', 'ai-eshop-optimizer'))); } return $def; } public function ajax_feed_vocab_backfill() { $this->check(); $this->require_pro(); $def = $this->vocab_def(); $supplier = (int) $def['supplier_term_id']; $offset = isset($_POST['offset']) ? max(0, (int) $_POST['offset']) : 0; $chunk = 1000; $source = new AIEO_Generic_Feed_Source($def); $rows = $source->harvest_rows(array('feed_url' => (string) ($def['url'] ?? ''))); if (is_wp_error($rows)) { wp_send_json_error(array('message' => $rows->get_error_message())); } $total = count($rows); $slice = array_slice($rows, $offset, $chunk); $apply_options = array('status' => 'draft'); if (!empty($def['rules'])) { $apply_options['feed_rules'] = (array) $def['rules']; } if (class_exists('AIEO_Feed_Cat_Map')) { $map = AIEO_Feed_Cat_Map::map_for_feed($def); if ($map) { $apply_options['feed_cat_map'] = $map; $apply_options['unmapped_policy'] = (string) ($def['options']['unmapped_policy'] ?? 'create'); } } $vocab_options = array( 'supplier_term_id' => $supplier, 'source_slug' => 'feed_' . (int) $def['id'], ); $learned = 0; $unresolved = 0; foreach ($slice as $raw) { if (!is_array($raw)) { continue; } $mapped = AIEO_Feed_Mapping::apply($raw, $def['mapping'], $apply_options); $payload = isset($mapped['payload']) && is_array($mapped['payload']) ? $mapped['payload'] : null; if (!$payload) { continue; } $entries = array($payload); foreach ((array) ($payload['variations'] ?? array()) as $vp) { if (!empty($vp['match']['sku'])) { $entries[] = array('title' => $payload['title'] ?? '', 'match' => (array) ($vp['match'] ?? array())); } } foreach ($entries as $entry) { $sku = (string) ($entry['match']['sku'] ?? ''); $title = (string) ($entry['title'] ?? ''); if ('' === $sku && '' === trim($title)) { continue; } $match = AIEO_Exchanger_Product_Importer::resolve_match($entry, 'sku'); $product_id = 0; $variation_id = 0; if ((int) $match['id'] > 0 && '' !== (string) $match['post_type']) { if ('product_variation' === $match['post_type']) { $product_id = (int) $match['parent_id']; $variation_id = (int) $match['id']; } else { $product_id = (int) $match['id']; } } AIEO_Docscan_Vocab::stamp_from_import($entry, $product_id, $variation_id, $vocab_options); if ($product_id > 0) { $learned++; } else { $unresolved++; } } } $next = $offset + count($slice); $complete = ($next >= $total || empty($slice)); if ($complete && class_exists('AIEO_Docscan_Vocab_Uplink')) { AIEO_Docscan_Vocab_Uplink::mark_dirty(); } wp_send_json_success(array( 'total' => $total, 'offset' => $next, 'learned' => $learned, 'unresolved' => $unresolved, 'complete' => $complete, 'counts' => AIEO_Docscan_Vocab::counts_for_supplier($supplier), )); } public function ajax_feed_vocab_flagged() { $this->check(); $this->require_pro(); $def = $this->vocab_def(); $supplier = (int) $def['supplier_term_id']; $rows = AIEO_Docscan_Vocab::flagged_rows($supplier); wp_send_json_success(array( 'rows' => $rows, 'counts' => AIEO_Docscan_Vocab::counts_for_supplier($supplier), 'table' => $this->vocab_table((array) $rows), )); } public function ajax_feed_vocab_rule() { $this->check(); $this->require_pro(); $def = $this->vocab_def(); $row_id = isset($_POST['row_id']) ? (int) $_POST['row_id'] : 0; $rule = isset($_POST['rule']) ? sanitize_key(wp_unslash($_POST['rule'])) : ''; if ($row_id <= 0) { wp_send_json_error(array('message' => __('Unknown vocabulary row.', 'ai-eshop-optimizer'))); } switch ($rule) { case 'suppress': AIEO_Docscan_Vocab::suppress($row_id, true); break; case 'restore': AIEO_Docscan_Vocab::suppress($row_id, false); break; case 'unflag': AIEO_Docscan_Vocab::clear_flag($row_id); break; default: wp_send_json_error(array('message' => __('Unknown ruling.', 'ai-eshop-optimizer'))); } $supplier = (int) $def['supplier_term_id']; $rows = AIEO_Docscan_Vocab::flagged_rows($supplier); wp_send_json_success(array( 'rows' => $rows, 'counts' => AIEO_Docscan_Vocab::counts_for_supplier($supplier), 'table' => $this->vocab_table((array) $rows), )); } private function posted_mapping() { $raw = isset($_POST['mapping']) ? wp_unslash($_POST['mapping']) : ''; $decoded = json_decode((string) $raw, true); if (!is_array($decoded)) { return array(); } $known = array(); $xml = $this->read_draft(); if (trim($xml) !== '' && !empty($decoded['record_path'])) { $analysis = AIEO_Feed_Structure_Inference::analyze($xml, (string) $decoded['record_path']); if (!is_wp_error($analysis)) { $known = wp_list_pluck($analysis['fields'], 'path'); } } if ($known && class_exists('AIEO_Feed_Rules')) { $rules = $this->posted_rules(); if (null === $rules) { $rid = isset($_POST['id']) ? (int) $_POST['id'] : 0; $rules = ($rid > 0) ? AIEO_Feed_Source_Store::get_rules($rid) : array(); } foreach (AIEO_Feed_Rules::virtual_fields($rules) as $vpath) { $known[] = $vpath; } } return AIEO_Feed_Mapping::sanitize($decoded, $known); } public function enqueue_admin_assets() { wp_enqueue_style('aieo-catalog-importer', AIEO_URI . 'assets/css/aieo-catalog-importer.min.css', array(), AIEO_VERSION); if (!$this->engine_present()) { return; } if (function_exists('rooster_admin_table_assets')) { rooster_admin_table_assets(array('local')); } $cfg = 'window.aieoCati=' . wp_json_encode(array( 'nonce' => wp_create_nonce(self::NONCE), 'ajaxurl' => admin_url('admin-ajax.php'), 'affixTargets' => $this->affix_target_shapes(), 'maxFeedBytes' => $this->max_browser_feed_bytes(), 'attrIndex' => class_exists('AIEO_Feed_Mapping') ? AIEO_Feed_Mapping::attribute_index() : array('attributes' => array(), 'canonical' => array(), 'hints' => array()), 'i18n' => array( 'webpConverted' => __('%s images converted to WebP', 'ai-eshop-optimizer'), 'webpSaved' => __('%s saved', 'ai-eshop-optimizer'), 'webpLeft' => __('%s left in their original format', 'ai-eshop-optimizer'), 'webpFailed' => __('%s could not be converted', 'ai-eshop-optimizer'), 'webpUnsupported' => __('This server cannot write WebP, so images were imported in the format the source served.', 'ai-eshop-optimizer'), 'varCreated' => __('%s variable products built from grouped rows', 'ai-eshop-optimizer'), 'varRefused' => __('%s groups could not be named and were imported as separate products:', 'ai-eshop-optimizer'), 'testing' => __('Testing…', 'ai-eshop-optimizer'), 'error' => __('Error', 'ai-eshop-optimizer'), 'requestFailed' => __('Request failed', 'ai-eshop-optimizer'), 'starting' => __('Starting…', 'ai-eshop-optimizer'), 'couldNotStart' => __('Could not start', 'ai-eshop-optimizer'), 'progress' => __('%1$s%% · page %2$s of %3$s · %4$s', 'ai-eshop-optimizer'), 'counts' => __('created %1$s · updated %2$s · skipped %3$s · errors %4$s', 'ai-eshop-optimizer'), 'progressDone' => __('%s — done.', 'ai-eshop-optimizer'), 'issuesHead' => __('Issues (first %s):', 'ai-eshop-optimizer'), 'feedReading' => __('Reading…', 'ai-eshop-optimizer'), 'feedRecordNode' => __('One product is', 'ai-eshop-optimizer'), 'feedRecordCount' => __('%s products found', 'ai-eshop-optimizer'), 'feedColField' => __('Field', 'ai-eshop-optimizer'), 'feedColFill' => __('Filled in on', 'ai-eshop-optimizer'), 'feedColSample' => __('Example', 'ai-eshop-optimizer'), 'feedUnmapped' => __('— not imported —', 'ai-eshop-optimizer'), 'feedAxes' => __('Product attributes', 'ai-eshop-optimizer'), 'feedAxesHelp' => __('Choose which of your existing attributes each field is written to, for example your own Colour or Size. Pick from the list whenever the attribute already exists: naming a new one creates a second attribute beside it. When rows are grouped into one product these are what its variations differ by; on every other row they are written onto the product itself.', 'ai-eshop-optimizer'), 'feedAddAxis' => __('Add another', 'ai-eshop-optimizer'), 'feedAddField' => __('Add field', 'ai-eshop-optimizer'), 'feedUpdate' => __('Update source', 'ai-eshop-optimizer'), 'feedEditing' => __('Editing "%1$s". Save updates this source in place; reload the page to start a fresh one.', 'ai-eshop-optimizer'), 'feedAxisName' => __('Attribute name', 'ai-eshop-optimizer'), 'feedAxisNewAttr' => __('— create a new attribute —', 'ai-eshop-optimizer'), 'feedAxisSearch' => __('Search your attributes…', 'ai-eshop-optimizer'), 'feedAxisSuggested' => __('Best match:', 'ai-eshop-optimizer'), 'feedAxisNoMatch' => __('No attribute matches that.', 'ai-eshop-optimizer'), 'feedRemove' => __('Remove', 'ai-eshop-optimizer'), 'feedDryRunning' => __('Working it out…', 'ai-eshop-optimizer'), 'feedWouldCreate' => __('%1$s rows read: %2$s products, %3$s of them with variations.', 'ai-eshop-optimizer'), 'feedVariableOf' => __('%s, with variations:', 'ai-eshop-optimizer'), 'feedAxisFrom' => __('read from the feed', 'ai-eshop-optimizer'), 'feedAxisTitles' => __('read from the product names', 'ai-eshop-optimizer'), 'feedRefusedHead' => __('These groups could not be built and would be imported as separate products:', 'ai-eshop-optimizer'), 'feedSaving' => __('Saving…', 'ai-eshop-optimizer'), 'feedConfirmDel' => __('Delete this source? Products it already imported are not affected.', 'ai-eshop-optimizer'), 'feedConfirmRefresh' => __('Rewrite every product this feed covers with what the feed says now? This fills in fields your products were imported without, such as weight and dimensions, and it also replaces names, descriptions, images and categories with the supplier\'s. Anything you pinned is left alone, and this feed\'s schedule is not changed.', 'ai-eshop-optimizer'), 'feedError' => __('Something went wrong.', 'ai-eshop-optimizer'), 'feedSimpleHead' => __('Ordinary products', 'ai-eshop-optimizer'), 'feedRunning' => __('Importing…', 'ai-eshop-optimizer'), 'feedFileLoaded' => __('Read "%s". Press "Read the feed" to look at its structure.', 'ai-eshop-optimizer'), 'feedFileTooBig' => __('"%s" is larger than this server accepts through the browser. Put the feed\'s address in the field above instead: the server fetches it directly and reads far larger files that way.', 'ai-eshop-optimizer'), 'feedFileUnreadable' => __('That file could not be read.', 'ai-eshop-optimizer'), 'feedFiltered' => __('%s rows are kept out by the saved filters.', 'ai-eshop-optimizer'), 'catmapVendor' => __('Feed category', 'ai-eshop-optimizer'), 'catmapOurs' => __('Your category', 'ai-eshop-optimizer'), 'catmapScore' => __('Match', 'ai-eshop-optimizer'), 'catmapStatus' => __('Status', 'ai-eshop-optimizer'), 'catmapConfirm' => __('Confirm', 'ai-eshop-optimizer'), 'catmapReject' => __('Reject', 'ai-eshop-optimizer'), 'catmapSelAll' => __('Select or deselect every row', 'ai-eshop-optimizer'), 'catmapBulkConfirm' => __('Confirm selected', 'ai-eshop-optimizer'), 'catmapBulkReject' => __('Reject selected', 'ai-eshop-optimizer'), 'catmapBulkSet' => __('Set category on selected', 'ai-eshop-optimizer'), 'catmapBulkConfirmQ' => __('Confirm the suggested category on %1$s selected rows? Rows without a suggestion are skipped.', 'ai-eshop-optimizer'), 'catmapBulkRejectQ' => __('Reject the mapping on %1$s selected rows?', 'ai-eshop-optimizer'), 'catmapBulkSetQ' => __('Set %2$s on %1$s selected rows?', 'ai-eshop-optimizer'), 'catmapBulkDone' => __('%1$s rows updated, %2$s skipped.', 'ai-eshop-optimizer'), 'catmapTermGone' => __('— category deleted (was #%s) — pick again', 'ai-eshop-optimizer'), 'catmapUnconfirmed' => __('%s category matches are still suggestions you have not confirmed. They will NOT be applied, and the feed may create its own categories instead.', 'ai-eshop-optimizer'), 'catmapMissing' => __('%s category matches point at a category that no longer exists. They will NOT be applied.', 'ai-eshop-optimizer'), 'catmapRunAnyway' => __('Run anyway?', 'ai-eshop-optimizer'), 'catmapEmpty' => __('Nothing here yet. Press "Suggest matches" to read the feed\'s categories and score them against yours.', 'ai-eshop-optimizer'), 'catmapAccepted' => __('%s accepted.', 'ai-eshop-optimizer'), 'catmapSaved' => __('Saved.', 'ai-eshop-optimizer'), 'catmapPick' => __('Pick one of your categories first.', 'ai-eshop-optimizer'), 'catmapStAuto' => __('applied automatically', 'ai-eshop-optimizer'), 'catmapStSuggested' => __('suggestion — not applied', 'ai-eshop-optimizer'), 'catmapStConfirmed' => __('confirmed', 'ai-eshop-optimizer'), 'catmapStManual' => __('picked by you', 'ai-eshop-optimizer'), 'catmapStRejected' => __('rejected', 'ai-eshop-optimizer'), 'catmapStLearned' => __('from your earlier matches', 'ai-eshop-optimizer'), 'vocabLearning' => __('Learning %1$s of %2$s…', 'ai-eshop-optimizer'), 'vocabDone' => __('Vocabulary: %1$s matched to products, %2$s not in the catalogue.', 'ai-eshop-optimizer'), 'vocabVendorSku' => __('Supplier code', 'ai-eshop-optimizer'), 'vocabVendorTitle' => __('Supplier wording', 'ai-eshop-optimizer'), 'vocabProduct' => __('Feed maps it to', 'ai-eshop-optimizer'), 'vocabSuppress' => __('Suppress', 'ai-eshop-optimizer'), 'vocabRestore' => __('Restore', 'ai-eshop-optimizer'), 'vocabUnflag' => __('Keep the mapping', 'ai-eshop-optimizer'), 'vocabEmpty' => __('No contradictions. Rows appear here when a confirmed invoice line names a DIFFERENT product than this feed\'s vocabulary — a sign the feed mapping may be wrong.', 'ai-eshop-optimizer'), 'vocabSuppressed' => __('suppressed', 'ai-eshop-optimizer'), 'ruleVirtual' => __('(rule)', 'ai-eshop-optimizer'), 'ruleMakeField' => __('Make a field named', 'ai-eshop-optimizer'), 'ruleFrom' => __('from', 'ai-eshop-optimizer'), 'ruleBySplit' => __('by cutting at', 'ai-eshop-optimizer'), 'ruleByRegex' => __('by pattern (regex)', 'ai-eshop-optimizer'), 'ruleByMultiply' => __('by multiplying with', 'ai-eshop-optimizer'), 'ruleFactor' => __('e.g. 1.5 (1 = exact copy)', 'ai-eshop-optimizer'), 'ruleBySum' => __('by summing its values', 'ai-eshop-optimizer'), 'ruleByPick' => __('by taking it where', 'ai-eshop-optimizer'), 'rulePickEquals' => __('equals', 'ai-eshop-optimizer'), 'ruleUseAs' => __('and use it as', 'ai-eshop-optimizer'), 'linkBrandsBusy' => __('Checking…', 'ai-eshop-optimizer'), 'linkBrandsNone' => __('Every brand in this feed already names a supplier. Nothing to do.', 'ai-eshop-optimizer'), 'linkBrandsPrev' => __('%1$s brands would be linked to %2$s, covering %3$s products. %4$s already name a supplier and stay as they are. %5$s are not brands in this shop yet.', 'ai-eshop-optimizer'), 'linkBrandsDone' => __('Linked %1$s brands to %2$s. Their existing products now resolve to that supplier.', 'ai-eshop-optimizer'), 'linkBrandsApply' => __('Link them', 'ai-eshop-optimizer'), 'ruleAffixAdd' => __('Add a prefix or suffix', 'ai-eshop-optimizer'), 'ruleAffixPut' => __('Put', 'ai-eshop-optimizer'), 'ruleAffixBefore'=> __('in front of and', 'ai-eshop-optimizer'), 'ruleAffixAfter' => __('after the', 'ai-eshop-optimizer'), 'ruleAffixOf' => __('of every product', 'ai-eshop-optimizer'), 'ruleUseAsNone' => __('— nothing yet (set it in the mapping) —', 'ai-eshop-optimizer'), 'ruleSaysPattern' => __('pattern', 'ai-eshop-optimizer'), 'ruleSaysSum' => __('sum', 'ai-eshop-optimizer'), 'ruleSaysPick' => __('pick', 'ai-eshop-optimizer'), 'ruleSaysSplit' => __('split', 'ai-eshop-optimizer'), 'ruleKeepBefore' => __('keep what is before', 'ai-eshop-optimizer'), 'ruleKeepAfter' => __('keep what is after', 'ai-eshop-optimizer'), 'ruleFirstHit' => __('the first occurrence', 'ai-eshop-optimizer'), 'ruleLastHit' => __('the last occurrence', 'ai-eshop-optimizer'), 'ruleWhen' => __('When', 'ai-eshop-optimizer'), 'ruleThen' => __('then', 'ai-eshop-optimizer'), 'ruleAddCond' => __('+ condition', 'ai-eshop-optimizer'), 'ruleAddAction' => __('+ action', 'ai-eshop-optimizer'), 'ruleSetTo' => __('set', 'ai-eshop-optimizer'), 'ruleToValue' => __('to', 'ai-eshop-optimizer'), 'ruleIfUnset' => __('only when the mapping left it unassigned', 'ai-eshop-optimizer'), 'ruleName' => __('field name, e.g. parent-code', 'ai-eshop-optimizer'), 'ruleDelimiter' => __('delimiter, e.g. -', 'ai-eshop-optimizer'), 'rulePattern' => __('e.g. ΧΡΩΜΑ:\s*([^|\]]+)', 'ai-eshop-optimizer'), 'ruleValue' => __('value', 'ai-eshop-optimizer'), ), 'ruleOps' => array_map('strval', AIEO_Feed_Rules::condition_ops()), 'ruleTargets' => array_map('strval', AIEO_Feed_Rules::action_targets()), )) . ';'; wp_register_script('aieo-cati-admin', false, array('jquery'), defined('AIEO_VERSION') ? AIEO_VERSION : '1', true); wp_enqueue_script('aieo-cati-admin'); $js = <<<'JS' jQuery(function($){ var n=window.aieoCati.nonce, u=window.aieoCati.ajaxurl; // A table a route drew (the library's, CONTRACT §8.2 "A table drawn later"): inserted, then wired by the library. function enhanceIn(el, icons){ if(el&&window.roosterAdminTable&&window.roosterAdminTable.enhance){ window.roosterAdminTable.enhance(el, icons||''); } } function source(){ return $('#aieo-cati-source').val(); } function panel(slug){ return $('.aieo-cati-panel[data-slug="'+slug+'"]'); } // The four connection panels are parts of one card: the chosen one shows and names the card (its library title, // or the h2 of Rooster One's own box without the chrome). // UI wave 2: Save connection and Test connection stand in the card's footer and act on the panel shown: the Save // submits that panel's own form (the library's Save, answered by dmm.js with this module's nonce). $('#aieo-cati-source').on('change', function(){ // The panels themselves follow the select through the library (States::depends_attrs). var s=$(this).val(), t=panel(s).data('title'); $('.aieo-cati-savewrap').prop('hidden', true).find('.rooster-admin-button').removeClass('rooster-admin-button--primary'); $('.aieo-cati-savewrap[data-slug="'+s+'"]').prop('hidden', false).find('.rooster-admin-button').addClass('rooster-admin-button--primary'); $('#aieo-cati-conn-test').attr('data-slug', s).data('slug', s); if(t){ $('#aieo-card-catalog-importer-connect-to-s-title, #aieo-card-catalog-importer-connect-to-s > h2').first().text(t); } }); $(document).on('click','.aieo-cati-test', function(){ var slug=$(this).data('slug'), b=$(this), p=panel(slug); b.prop('disabled',true); p.find('.aieo-cati-test-out').html(outcome(i18n.testing, '')); $.post(u, {action:'aieo_catalog_import_test', nonce:n, slug:slug}, function(r){ b.prop('disabled',false); if(r&&r.success){ var o=p.find('.aieo-cati-test-out').html(r.data.html); enhanceIn(o[0], r.data.icons); } else { p.find('.aieo-cati-test-out').html(outcome((r&&r.data&&r.data.message)||i18n.error, 'destructive')); } }).fail(function(){ b.prop('disabled',false); p.find('.aieo-cati-test-out').html(outcome(i18n.requestFailed, 'destructive')); }); }); var importing=false; var i18n=window.aieoCati.i18n||{}; // sprintf-style: %1$s… by position, a lone %s, %% a percent sign. function sp(s){ var a=arguments; return String(s||'').replace(/%(\d)\$s/g,function(m,i){return a[Number(i)];}).replace('%s',a[1]).replace(/%%/g,'%'); } function bytes(n){ n=Number(n)||0; if(n<1024) return n+' B'; if(n<1048576) return (n/1024).toFixed(0)+' KB'; return (n/1048576).toFixed(1)+' MB'; } // Without this the conversion is invisible and nobody trusts it. function webpLine(w){ if(!w) { return ''; } var parts=[]; if(w.converted>0){ var c=sp(i18n.webpConverted,w.converted); if(w.bytes_saved>0){ c+=' ('+sp(i18n.webpSaved,bytes(w.bytes_saved))+')'; } parts.push(c); } if(w.skipped>0){ parts.push(sp(i18n.webpLeft,w.skipped)); } if(w.failed>0){ parts.push(sp(i18n.webpFailed,w.failed)); } var h=parts.length?outcome(parts.join(' · '), w.failed>0?'warning':'success'):''; if(w.unsupported){ h=(h?h+''+esc(g.key)+': '+esc(g.reason)+''+outcome(sp(i18n.issuesHead, s.length), 'destructive')+'
'+esc(e.sku||'')+': '+esc(e.error||'')+''+esc(sp(L.feedRecordCount,A.record_count))+'
'; // The fields, their fill rates and samples: the library's table, drawn by the route with the analysis. var box=$('#aieo-cati-feed-structure').html(h); if(S&&S.html){ box.append(S.html); enhanceIn(box[0], S.icons); } } // One ordered source-field row of a multi target (description built from // intro + body + specs; featured image and gallery from separate fields). // A target's field id: its row's label and help hang on it (the library's field rows, 7 Nov 2026). function mapId(key){ return 'aieo-cati-map-'+String(key).replace(/[^a-z0-9_-]/gi,'-'); } function mapRow(key, sel){ return '' +' ' +''; } function renderMapping(){ // The library's field rows, as Ui::field_row() prints them (the cleanup of 7 Nov 2026: no form table): a single // field's select is labelled by its target, a list of fields is a group its selects name themselves by. var h=''+esc(t.help)+'
':''; var tied=t.help?' aria-describedby="'+id+'-help"':''; if(t.multi){ // Rows merge in DOM order, so dragging a field up literally reorders // the description parts and picks which picture leads. var paths=Array.isArray(chosen)?chosen:(chosen?[chosen]:['']); h+=''+esc(L.feedAxesHelp)+'
'; h+=''; h+=''; $('#aieo-cati-feed-mapping').html(h); addAxisRow(); } // WHICH ATTRIBUTE, chosen rather than derived. A shop's size attribute is // pa_size or pa_megethos or pa_noumero or pa_bigness, and its colour one // pa_color or pa_chroma or pa_apoxrosi. No rule reading a name can know // which, and guessing wrong does not fail loudly: it creates a SECOND // attribute meaning the same thing, which somebody then merges by hand. // Picking from what the shop HAS is the only reliable answer, so the // dropdown leads and naming a new one is the deliberate second choice. // A SEARCHABLE picker, not a 400-row dropdown. The chosen taxonomy lives in // a hidden input; the visible box is a filter. `data-tax` empty means "create // a new attribute", which stays available as the deliberate second choice. var AXBOX='aieo-cati-axbox'; function attrShortLabel(tax){ var a=ABY[tax]; if(!a){ return tax; } var lbl=String(a.label), cut=lbl.lastIndexOf(' ('); return cut>0?lbl.slice(0,cut):lbl.replace(/^pa_/,''); } function axisRowText($r){ var typed=$.trim($r.find('.aieo-cati-axis-label').val()||''); if(typed){ return typed; } // Fall back to the FEED FIELD's own leaf name: on a fresh row that is the // only thing that says what this axis is about. var p=String($r.find('.aieo-cati-axis-path').val()||''); return p.split('/').pop().replace(/^@/,''); } function renderAxOptions($r, q){ var $list=$r.find('.'+AXBOX+'-list').empty(), qq=fold(q||''), shown=0; var sugg=suggestFor(axisRowText($r)); function row(tax, why){ var a=ABY[tax]; return ''+esc(L.feedDryRunning)+'
'); $.post(u,{action:'aieo_catalog_feed_dryrun', nonce:n, id:editingId, mapping:JSON.stringify(mapping()), rules:JSON.stringify(rulesDoc())},function(r){ if(!r||!r.success){ out.html(''+outcome((r&&r.data&&r.data.message)||L.feedError, 'destructive')+'
'); return; } var d=r.data, h=''+esc(sp(L.feedWouldCreate,d.counts.records,d.counts.simple+d.counts.variable,d.counts.variable))+'
'; if(d.counts.filtered>0){ h+=''+outcome(sp(L.feedFiltered,d.counts.filtered), 'warning')+'
'; } var dt=d.tables||{}; (d.variable||[]).forEach(function(v, vi){ h+=''+esc(sp(L.feedVariableOf,v.title))+' '+esc(v.sku)+' '
+'('+esc(v.axes.join(', '))+' · '+esc(v.source==='feed'?L.feedAxisFrom:L.feedAxisTitles)+')'
// Mapped attributes that are the same on every row: not what the
// variations differ by, still true of the product, so they go on it.
+((v.fixed&&v.fixed.length)?' · '+esc(v.fixed.join(' · '))+'':'')+'
'+outcome(L.feedRefusedHead, 'warning')+'
'+esc(g.key)+': '+esc(g.reason)+''+outcome(L.feedError, 'destructive')+'
'); }); }); $('#aieo-cati-feed-save').on('click', function(){ var s=$('#aieo-cati-feed-save-status').text(L.feedSaving).removeAttr('data-tone'); $.post(u,{action:'aieo_catalog_feed_save', nonce:n, id:editingId, name:$('#aieo-cati-feed-name').val(), url:$('#aieo-cati-feed-url').val(), mapping:JSON.stringify(mapping()), schedule:$('#aieo-cati-feed-schedule').val(), schedule_hour:$('#aieo-cati-feed-schedule-hour').val()||-1, schedule_day:($('#aieo-cati-feed-schedule').val()==='weekly'?$('#aieo-cati-feed-schedule-dow').val():($('#aieo-cati-feed-schedule').val()==='monthly'?$('#aieo-cati-feed-schedule-dom').val():-1))||-1, supplier_term_id:$('#aieo-cati-feed-supplier').val()||0, supplier_new:$.trim($('#aieo-cati-feed-supplier-new').val()||''), opt_status:$('#aieo-cati-feed-opt-status').val(), opt_mode:$('#aieo-cati-feed-opt-mode').val(), opt_images:$('#aieo-cati-feed-opt-images').is(':checked')?1:0, opt_categories:$('#aieo-cati-feed-opt-categories').is(':checked')?1:0, opt_cat_ancestors:$('#aieo-cati-feed-opt-cat-ancestors').is(':checked')?1:0, opt_variations:$('#aieo-cati-feed-opt-variations').is(':checked')?1:0, opt_webp:$('#aieo-cati-feed-opt-webp').is(':checked')?1:0, opt_unmapped_policy:$('#aieo-cati-feed-opt-unmapped').val()||'create', opt_import_limit:$('#aieo-cati-feed-opt-limit').val()||0, filters:JSON.stringify(filtersDoc()), rules:JSON.stringify(rulesDoc()) },function(r){ if(!r||!r.success){ s.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } s.text(r.data.message).attr('data-tone','success'); setTimeout(function(){ window.location.reload(); }, 900); }).fail(function(){ s.text(L.feedError).attr('data-tone','destructive'); }); }); // Runs the template immediately, through the same path cron uses, so what // you see here is what the schedule will do. // PRE-FLIGHT: an unconfirmed or dangling category mapping is not applied, // and the run then creates vendor categories beside the ones the operator // picked. Nothing said so before pressing Run. Count first, warn, let them // decide — the run is never blocked. // Asked through the library's dialog (its click caught first, the handler run once confirmed): true when it is here. function asked(el){ var id=el&&el.getAttribute('data-ra-confirm'); return !!(id && window.roosterAdminStates && document.getElementById(id)); } function catmapPreflight(id, go, trigger){ $.post(u,{action:'aieo_catalog_feed_catmap_health', nonce:n, id:id}, function(r){ if(!r||!r.success){ go(true); return; } // health unknown: do not stand in the way var d=r.data, bits=[]; if(d.suggested>0){ bits.push(sp(L.catmapUnconfirmed, d.suggested)); } if(d.missing>0){ bits.push(sp(L.catmapMissing, d.missing)); } if(!bits.length){ go(true); return; } // The library's dialog, its words this run's (say); confirm() only where the library is absent. var dlg=document.getElementById('aieo-cati-feed-catmap-confirm'), st=window.roosterAdminStates; if(dlg && st && st.ask && trigger){ trigger.setAttribute('data-ra-confirm-say', bits.join(' ')); st.ask(dlg, trigger).then(function(ok){ trigger.removeAttribute('data-ra-confirm-say'); go(!!ok); }); return; } go(window.confirm(bits.join('\n') + '\n\n' + L.catmapRunAnyway)); }).fail(function(){ go(true); }); } $(document).on('click','.aieo-cati-feed-run', function(){ // The Last-run cell is addressed by its content's own hook (.aieo-cati-last-run): the positional td.eq(6) broke // whenever a column moved, and the library table's cells carry no column key (td[data-key] matched nothing, so // the result never showed; 7 Nov 2026). var b=$(this), cell=b.closest('tr').find('.aieo-cati-last-run'); catmapPreflight(b.data('id'), function(ok){ if(!ok){ return; } b.prop('disabled',true); cell.html(outcome(L.feedRunning, '')); $.post(u,{action:'aieo_catalog_feed_run_now', nonce:n, id:b.data('id')},function(r){ b.prop('disabled',false); if(!r||!r.success){ cell.html(outcome((r&&r.data&&r.data.message)||L.feedError, 'destructive')); return; } cell.html(outcome(r.data.message, r.data.ok?'success':'destructive')); }).fail(function(){ b.prop('disabled',false); cell.html(outcome(L.feedError, 'destructive')); }); }, b[0]); }); // Same path, same endpoint, one flag: rewrite everything the feed carries // onto products that already exist. Confirmed first, because unlike "Run // now" it CAN overwrite a name or description the shop edited by hand. $(document).on('click','.aieo-cati-feed-refresh', function(){ if(!asked(this) && !window.confirm(L.feedConfirmRefresh)){ return; } var b=$(this), cell=b.closest('tr').find('.aieo-cati-last-run'); b.prop('disabled',true); cell.html(outcome(L.feedRunning, '')); $.post(u,{action:'aieo_catalog_feed_run_now', nonce:n, id:b.data('id'), refresh_all:1},function(r){ b.prop('disabled',false); if(!r||!r.success){ cell.html(outcome((r&&r.data&&r.data.message)||L.feedError, 'destructive')); return; } cell.html(outcome(r.data.message, r.data.ok?'success':'destructive')); }).fail(function(){ b.prop('disabled',false); cell.html(outcome(L.feedError, 'destructive')); }); }); $(document).on('click','.aieo-cati-feed-delete', function(){ if(!asked(this) && !window.confirm(L.feedConfirmDel)){ return; } var b=$(this); b.prop('disabled',true); $.post(u,{action:'aieo_catalog_feed_delete', nonce:n, id:b.data('id')},function(r){ if(r&&r.success){ if(Number(b.data('id'))===editingId){ editingId=0; } b.closest('tr').remove(); } else { b.prop('disabled',false); } }).fail(function(){ b.prop('disabled',false); }); }); // Edit: load the saved source back into the generator. The STORED mapping // is the truth for this source — rows hydrate from it alone, so a target // the operator left unmapped stays unmapped rather than being re-proposed // behind their back. Analyzing a fresh paste while editing keeps the id: // that is the replace-the-sample flow, and Save still updates in place. $(document).on('click','.aieo-cati-feed-edit', function(){ var b=$(this), s=$('#aieo-cati-feed-save-status').text(L.feedReading).removeAttr('data-tone'); b.prop('disabled',true); $.post(u,{action:'aieo_catalog_feed_load', nonce:n, id:b.data('id')},function(r){ b.prop('disabled',false); if(!r||!r.success){ s.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } var d=r.data, def=d.definition||{}, m=def.mapping||{}; editingId=Number(def.id)||0; A=d.analysis; T=d.targets; P={}; S=d.structure||null; // Stored rules hydrate FIRST: their derived fields must be in the // path vocabulary before the mapping selects draw, or a mapping that // points at rule:parent-code would render as unmapped. A.fields=(A.fields||[]).filter(function(f){ return !f.virtual; }); (def.rules||[]).forEach(function(r2){ if(r2.type==='derive'&&r2.name){ A.fields.push({path:'rule:'+r2.name, label:'rule:'+r2.name, fill:1, samples:[], virtual:true, recipe:ruleRecipe(r2)}); } }); $('#aieo-cati-rules-list').empty(); (def.rules||[]).forEach(function(r2){ if(r2.type==='derive'){ addDeriveRow(r2); } else if(r2.type==='affix'){ addAffixRow(r2); } else if(r2.type==='set'){ addSetRow(r2); } }); Object.keys(m.fields||{}).forEach(function(k){ P[k]={path:m.fields[k]}; }); // Reopening a saved source: show each rule's destination by reading it // BACK off the mapping. The rule document never stores it — the mapping // is the single source of truth for where a field lands. $('#aieo-cati-rules-list .aieo-cati-rule[data-type=derive]').each(function(){ var $r=$(this), name=$.trim($r.find('.aieo-cati-rule-name').val()||''), found=''; if(!name){ return; } Object.keys(m.fields||{}).forEach(function(k){ if(!found && m.fields[k]==='rule:'+name){ found=k; } }); $r.find('.aieo-cati-rule-dest').val(found); }); $('#aieo-cati-feed-name').val(def.name||''); $('#aieo-cati-feed-url').val(def.url||''); $('#aieo-cati-feed-xml').val(''); $('#aieo-cati-feed-sep').val(m.separator||'>'); $('#aieo-cati-feed-schedule').val(def.schedule||'manual'); $('#aieo-cati-feed-schedule-hour').val(String(def.schedule_hour!=null?def.schedule_hour:-1)); var sd=String(def.schedule_day!=null?def.schedule_day:-1); $('#aieo-cati-feed-schedule-dow').val(def.schedule==='weekly'?sd:'-1'); $('#aieo-cati-feed-schedule-dom').val(def.schedule==='monthly'?sd:'-1'); hourToggle(); $('#aieo-cati-feed-supplier').val(String(def.supplier_term_id||0)); $('#aieo-cati-feed-supplier-new').val(''); var o=def.options||{}; $('#aieo-cati-feed-opt-status').val(o.status||'draft'); $('#aieo-cati-feed-opt-mode').val(o.mode||'new_only'); $('#aieo-cati-feed-opt-images').prop('checked', !!Number(o.images)); $('#aieo-cati-feed-opt-categories').prop('checked', !!Number(o.categories)); $('#aieo-cati-feed-opt-cat-ancestors').prop('checked', (typeof o.category_ancestors === 'undefined') ? true : !!Number(o.category_ancestors)); $('#aieo-cati-feed-opt-variations').prop('checked', !!Number(o.variations)); uoNoteFeed(); $('#aieo-cati-feed-opt-webp').prop('checked', !!Number(o.webp)); $('#aieo-cati-feed-opt-unmapped').val(o.unmapped_policy||'create'); $('#aieo-cati-feed-opt-limit').val(Number(o.import_limit)||0); showEditCards(def, d.filter_options||{}); renderStructure(); renderMapping(); $('#aieo-cati-feed-axes').empty(); var ax=m.axes||[]; if(ax.length){ ax.forEach(function(a){ addAxisRow(a.path,a.label,a.taxonomy); }); } else { addAxisRow(); } step(2,true); step(3,true); step(4,true); step(5,true); $('#aieo-cati-feed-preview').html(''); $('#aieo-cati-feed-save').text(L.feedUpdate); s.text(sp(L.feedEditing, def.name||'')).removeAttr('data-tone'); var t=$('#aieo-cati-feed-structure'); if(t.length&&t[0].scrollIntoView){ t[0].scrollIntoView({behavior:'smooth'}); } }).fail(function(){ b.prop('disabled',false); s.text(L.feedError).attr('data-tone','destructive'); }); }); // ---- Rules: derived fields + conditional value-setting. Drafted rules // work in the dry run BEFORE saving; the derive names join the mapping // dropdowns live, so "cut the parent code out of the SKU" and "map it to // grouping" is one uninterrupted motion. ---- var OPS=window.aieoCati.ruleOps||{}, TARGETS=window.aieoCati.ruleTargets||{}; function selOf(map, sel, cls){ var h=''; } function condRow(c){ c=c||{}; return '' +' ' +selOf(OPS, c.op||'equals', 'aieo-cati-rule-cond-op')+' ' +' ' +''; } function actRow(a){ a=a||{}; return '' +esc(L.ruleSetTo)+' '+selOf(TARGETS, a.target||'stock_quantity', 'aieo-cati-rule-act-target')+' ' // Wide, because one of the targets is a whole category path // ("Θάλασσα > Ψάρεμα > Παραγάδια") and not a figure. +esc(L.ruleToValue)+' ' +' ' +''; } function addDeriveRow(r){ r=r||{}; var mode=(['regex','multiply','sum','pick'].indexOf(r.mode)!==-1)?r.mode:'split'; var h=''+esc(d.samples.join(', '))+(d.to_link>d.samples.length?' …':'')+'
'; } if(d.unknown_samples&&d.unknown_samples.length){ h+=''+esc(d.unknown_samples.join(', '))+(d.unknown>d.unknown_samples.length?' …':'')+'
'; } $d.html(h); $('#aieo-cati-linkbrands-apply').prop('hidden', false); } else { $s.text(sp(L.linkBrandsDone, d.linked, d.supplier)).attr('data-tone','success'); $d.empty(); $('#aieo-cati-linkbrands-apply').prop('hidden', true); } }).fail(function(){ $s.text(L.feedError).attr('data-tone','destructive'); }); } $(document).on('click','#aieo-cati-linkbrands-check', function(){ linkBrands(true); }); $(document).on('click','#aieo-cati-linkbrands-apply', function(){ linkBrands(false); }); // The category mapping: the library's form grid, drawn by the route (its rows are the page's own, so a row's // picker keeps what was picked while the search, the status filter or the page changes). The selection and the // bulk bar are the library's; the bar's three buttons submit the grid's form, answered below with this screen's own // endpoint. Per-row Confirm/Reject and the Suggest/Accept buttons above are UNCHANGED. function renderCatmap(table, rows){ var box=$('#aieo-cati-catmap-table'); if(!rows||!rows.length||!table||!table.html){ box.html(''+esc(L.catmapEmpty)+'
'); return; } box.html(table.html); enhanceIn(box[0], table.icons); if(window.AieoDmm&&window.AieoDmm.initSelect2){ window.AieoDmm.initSelect2(box[0]); } } // Every ticked row is in the form (a form grid hides rows, never drops them): the count goes in the confirmation, // and the write is this screen's own endpoint (a T0 table has no report id to post to generically). $(document).on('submit','.aieo-cati-catmap-form', function(e){ e.preventDefault(); var by=e.originalEvent&&e.originalEvent.submitter, op=by?by.value:''; if(!op){ return; } var ids=[], seen={}; new FormData(this).getAll('ids[]').forEach(function(v){ if(v!==''&&!seen[v]){ seen[v]=1; ids.push(Number(v)); } }); if(!ids.length){ return; } // The library's confirmation has asked already (with the count); it clicked the button again to get here. var term='set'===op?Number($(this).find('.aieo-cati-catmap-bulk-term').val()||0):0; if('set'===op&&!term){ window.alert(L.catmapPick); return; } catmapBulk(op, term, ids); }); // Set category needs a category first, before its confirmation opens (on the window, ahead of the library's own // capture on the document), and names it there. window.addEventListener('click', function(e){ var b=e.target&&e.target.closest?e.target.closest('.aieo-cati-catmap-form button[value="set"]'):null; if(!b){ return; } var pick=$(b.form).find('.aieo-cati-catmap-bulk-term'); if(!Number(pick.val()||0)){ e.preventDefault(); e.stopImmediatePropagation(); window.alert(L.catmapPick); return; } $('.aieo-cati-catmap-set-name').text($.trim(pick.find('option:selected').text())); }, true); function catmapBulk(op, term, ids){ var st=$('#aieo-cati-catmap-status').removeAttr('data-tone'); st.text(L.feedReading); $.post(u,{action:'aieo_catalog_feed_catmap_bulk', nonce:n, id:editingId, op:op, term_id:term||0, row_ids:ids},function(r){ if(!r||!r.success){ st.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } st.text(sp(L.catmapBulkDone, r.data.done, r.data.skipped)).attr('data-tone','success'); renderCatmap(r.data.table, r.data.rows); }).fail(function(){ st.text(L.feedError).attr('data-tone','destructive'); }); } function loadCatmap(){ if(!editingId){ return; } var st=$('#aieo-cati-catmap-status').text(L.feedReading).removeAttr('data-tone'); $.post(u,{action:'aieo_catalog_feed_catmap_list', nonce:n, id:editingId},function(r){ st.text(''); if(r&&r.success){ catmapThreshold=Number(r.data.threshold)||catmapThreshold; renderCatmap(r.data.table, r.data.rows); } }).fail(function(){ st.text(L.feedError).attr('data-tone','destructive'); }); } $('#aieo-cati-catmap-suggest').on('click', function(){ if(!editingId){ return; } var b=$(this).prop('disabled',true), st=$('#aieo-cati-catmap-status').text(L.feedReading).removeAttr('data-tone'); $.post(u,{action:'aieo_catalog_feed_catmap_suggest', nonce:n, id:editingId},function(r){ b.prop('disabled',false); if(!r||!r.success){ st.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } st.text(''); catmapThreshold=Number(r.data.threshold)||catmapThreshold; renderCatmap(r.data.table, r.data.rows); }).fail(function(){ b.prop('disabled',false); st.text(L.feedError).attr('data-tone','destructive'); }); }); $('#aieo-cati-catmap-accept').on('click', function(){ if(!editingId){ return; } var b=$(this).prop('disabled',true), st=$('#aieo-cati-catmap-status').removeAttr('data-tone'); $.post(u,{action:'aieo_catalog_feed_catmap_accept', nonce:n, id:editingId},function(r){ b.prop('disabled',false); if(!r||!r.success){ st.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } st.text(sp(L.catmapAccepted, r.data.accepted)).attr('data-tone','success'); renderCatmap(r.data.table, r.data.rows); }).fail(function(){ b.prop('disabled',false); st.text(L.feedError).attr('data-tone','destructive'); }); }); function catmapRule(tr, term, status){ var st=$('#aieo-cati-catmap-status').removeAttr('data-tone'); $.post(u,{action:'aieo_catalog_feed_catmap_save', nonce:n, id:editingId, row_id:tr.data('row-id'), term_id:term, status:status},function(r){ if(!r||!r.success){ st.text((r&&r.data&&r.data.message)||L.feedError).attr('data-tone','destructive'); return; } st.text(L.catmapSaved).attr('data-tone','success'); tr.find('.aieo-cati-catmap-st').attr('data-st',status).data('st',status).text(stLabel(status)); tr.attr('data-ra-f', JSON.stringify({status:[status]})); // the grid's status filter reads the row's new status }).fail(function(){ st.text(L.feedError).attr('data-tone','destructive'); }); } $(document).on('click','.aieo-cati-catmap-ok', function(){ var tr=$(this).closest('tr'), term=Number(tr.find('.aieo-cati-catmap-term').val()||0); if(!term){ window.alert(L.catmapPick); return; } // Confirming the correlator's own pick is 'confirmed'; picking a // different category is the operator's own 'manual' ruling. catmapRule(tr, term, term===Number(tr.data('orig-term'))?'confirmed':'manual'); }); $(document).on('click','.aieo-cati-catmap-no', function(){ catmapRule($(this).closest('tr'), 0, 'rejected'); }); // ── Feed vocabulary (the invoice-scanner bridge) ───────────────────────── // "Learn vocabulary": re-reads the live feed and stores the supplier's own // SKUs and titles WITHOUT importing anything. Chunked; progress rides the // Last-run cell exactly like Run now. $(document).on('click','.aieo-cati-feed-vocab', function(){ var b=$(this), cell=b.closest('tr').find('.aieo-cati-last-run'), id=b.data('id'); var learned=0, unresolved=0; b.prop('disabled',true); function step(offset){ $.post(u,{action:'aieo_catalog_feed_vocab_backfill', nonce:n, id:id, offset:offset},function(r){ if(!r||!r.success){ b.prop('disabled',false); cell.html(outcome((r&&r.data&&r.data.message)||L.feedError, 'destructive')); return; } learned+=Number(r.data.learned)||0; unresolved+=Number(r.data.unresolved)||0; if(!r.data.complete){ cell.html(outcome(sp(L.vocabLearning, r.data.offset, r.data.total), '')); step(r.data.offset); return; } b.prop('disabled',false); cell.html(outcome(sp(L.vocabDone, learned, unresolved), 'success')); }).fail(function(){ b.prop('disabled',false); cell.html(outcome(L.feedError, 'destructive')); }); } step(0); }); // The contradiction-flag review (§6.4): rows a confirmed invoice line has // contradicted. Suppress = the operator tombstone; nothing here ever // auto-edits a feed mapping. function renderVocabFlagged(table, rows){ var box=$('#aieo-cati-vocab-table'); if(!box.length){ return; } if(!rows||!rows.length||!table||!table.html){ box.html(''+esc(L.vocabEmpty)+'
'); return; } // The library's table, drawn by the route (searchable, paged); the rulings below read each row's id. box.html(table.html); enhanceIn(box[0], table.icons); } function loadVocabFlagged(){ if(!editingId||!$('#aieo-cati-vocab-table').length){ return; } $.post(u,{action:'aieo_catalog_feed_vocab_flagged', nonce:n, id:editingId},function(r){ if(r&&r.success){ renderVocabFlagged(r.data.table, r.data.rows); } else{ $('#aieo-cati-vocab-table').html(''); } }); } function vocabRule(tr, rule){ $.post(u,{action:'aieo_catalog_feed_vocab_rule', nonce:n, id:editingId, row_id:tr.data('row-id'), rule:rule},function(r){ if(r&&r.success){ renderVocabFlagged(r.data.table, r.data.rows); } }); } $(document).on('click','.aieo-cati-vocab-suppress', function(){ vocabRule($(this).closest('tr'),'suppress'); }); $(document).on('click','.aieo-cati-vocab-restore', function(){ vocabRule($(this).closest('tr'),'restore'); }); $(document).on('click','.aieo-cati-vocab-unflag', function(){ vocabRule($(this).closest('tr'),'unflag'); }); $(document).on('aieo:feed-editcards', loadVocabFlagged); }); JS; wp_add_inline_script('aieo-cati-admin', $cfg . "\n" . $js . "\n" . $feed_js); } public function render_subtab() { if (!$this->engine_present()) { $this->render_engine_missing_notice(); return; } $section = isset($_GET[$this->get_tab_arg()]) ? sanitize_key(wp_unslash($_GET[$this->get_tab_arg()])) : 'import'; if (!array_key_exists($section, $this->get_tabs())) { $section = 'import'; } AIEO_DMM_UI::tab_strip($this->get_id(), $this->get_tabs(), $section, array( 'arg' => $this->get_tab_arg(), )); $band = function_exists('rooster_admin_band_open'); if ($band) { rooster_admin_band_open(array('cols' => 1)); } if ('sources' === $section) { $this->render_sources_tab(); } else { $this->render_import_tab(); } if ($band) { rooster_admin_band_close(); } } private static function field($label, $control, array $helps = array(), array $opts = array()) { $extra = ''; foreach (array_slice($helps, 1) as $help) { $extra .= '' . esc_html((string) $help) . '
'; } return AIEO_Kit::row((string) $label, $control . $extra . (string) ($opts['more'] ?? ''), (string) ($helps[0] ?? ''), $opts); } private static function with_attrs(array $card, array $attrs) { list($open, $close) = $card; $extra = ''; foreach ($attrs as $name => $value) { $extra .= ' ' . sanitize_key($name) . '="' . esc_attr((string) $value) . '"'; } $open = (string) preg_replace_callback('/^\s*<(?:section|div)\b/', static function ($m) use ($extra) { return $m[0] . $extra; }, $open, 1); return array($open, $close); } private function render_engine_missing_notice() { echo '' . esc_html__('Rooster One Pro is not installed.', 'ai-eshop-optimizer') . ' ' . esc_html__('The catalogue import engine — the marketplace connectors, the feed reader, the mapping and rules pipeline and the scheduler — ships with the Rooster One Pro plugin. Install and activate it and this screen comes alive without further setup.', 'ai-eshop-optimizer') . '
' . esc_html__('No catalogue sources are available.', 'ai-eshop-optimizer') . '
'; echo $aieo_cati_close; return; } $slugs = array_keys($sources); $current = $slugs[0]; echo ''; $aieo_cati_why = __('Pick the marketplace to import from, fill in its credentials below, then run the import.', 'ai-eshop-optimizer'); echo class_exists('\Rooster\Admin\Guidance') ? \Rooster\Admin\Guidance::text($aieo_cati_why) : '' . esc_html($aieo_cati_why) . '
'; echo $aieo_cati_close; $aieo_cati_nonce = wp_create_nonce(self::NONCE); $aieo_cati_widths = array('region' => 'xs', 'chain_id' => 'medium', 'vendor_id' => 'medium', 'shop_id' => 'medium', 'venue_id' => 'medium', 'seller_id' => 'medium', 'marketplace_id' => 'medium'); $aieo_cati_panels = ''; $aieo_cati_foot = ''; $aieo_cati_test = ''; foreach ($sources as $slug => $src) { $creds = $this->get_creds($slug); $key = sanitize_html_class((string) $slug); $form_id = 'aieo-cati-conn-' . $key . '-form'; list($aieo_cati_sub_open, $aieo_cati_sub_close) = AIEO_DMM_UI::card(array('anchor' => 'catalog-importer-connect-' . $key . '-credentials', 'title' => sprintf( __('%s credentials', 'ai-eshop-optimizer'), $src->label()), 'description' => __('The account details and keys this source asks for, as the marketplace issued them.', 'ai-eshop-optimizer'), 'level' => 3)); $fields = '' . $aieo_cati_sub_open . '' . esc_html__('"Price and stock only" leaves the name, description, images, categories and attributes exactly as they are, and never adds, removes or re-creates a variation. It is the one to use on a feed that runs again and again.', 'ai-eshop-optimizer') . '
', array(__('Matched by SKU, so a product is never created twice however often you re-import.', 'ai-eshop-optimizer')), array('id' => 'aieo-cati-mode')); echo self::field(__('Images', 'ai-eshop-optimizer'), '', array(), array('id' => 'aieo-cati-images-row', 'group' => true)); echo self::field(__('Categories', 'ai-eshop-optimizer'), '', array(), array('id' => 'aieo-cati-categories-row', 'group' => true)); $aieo_cati_uo = esc_html__('With "Only update existing", grouped rows only update the variable products and variations that already exist — missing ones are skipped and reported, never created.', 'ai-eshop-optimizer'); $aieo_cati_uo = class_exists('\Rooster\Admin\Ui') ? \Rooster\Admin\Ui::notice($aieo_cati_uo, 'warning', array('inline' => true, 'id' => 'aieo-cati-update-only-note', 'attrs' => array('hidden' => ''))) : '' . $aieo_cati_uo . '
'; echo self::field(__('Variations', 'ai-eshop-optimizer'), '' . '' . esc_html__('Only rows a source says belong together are grouped. What they vary by is read from the feed where it names the field, and from the product titles otherwise. A group whose difference cannot be named is imported as separate products rather than guessed at, and the reason is reported below.', 'ai-eshop-optimizer') . '
', array(), array('id' => 'aieo-cati-variations-row', 'group' => true, 'more' => $aieo_cati_uo)); echo self::field(__('Image format', 'ai-eshop-optimizer'), '' . ' ' . ' ' . '' . esc_html__('Converted before the image is stored, so every thumbnail is made from the WebP and no JPEG is kept alongside it. Camera and location data is removed at the same time. Images that are already WebP or AVIF are left alone, and a server that cannot write WebP imports the original format instead.', 'ai-eshop-optimizer') . '
' . '' . esc_html__('Above 85 the saving disappears; below 75 gradients band, which shows on product photography.', 'ai-eshop-optimizer') . '
', array(), array('id' => 'aieo-cati-webp-row', 'group' => true)); echo '' . \Rooster\Admin\States::outcome('', '', array('id' => 'aieo-cati-prog-msg')) . '
'; echo ''; echo ''; echo ''; echo '' . esc_html($aieo_cati_why) . '
') . $aieo_cati_close; return; } $existing = class_exists('AIEO_Feed_Source_Store') ? AIEO_Feed_Source_Store::all() : array(); if (!$existing) { list($aieo_cati_open, $aieo_cati_close) = AIEO_DMM_UI::card(array( 'anchor' => 'catalog-importer-your-feed-sources', 'icon' => 'folders', 'title' => __('Your feed sources', 'ai-eshop-optimizer'), 'description' => __('The feeds you turned into reusable sources, with their schedule and last run; run, refresh, edit or delete each one.', 'ai-eshop-optimizer'), )); $aieo_cati_none = __('None yet. Read a feed below and the source you build from it appears here, and on the Import tab beside the marketplaces.', 'ai-eshop-optimizer'); echo $aieo_cati_open . (class_exists('\Rooster\Admin\States') ? \Rooster\Admin\States::state('first-use', array('title' => __('No feed sources yet.', 'ai-eshop-optimizer'), 'text' => $aieo_cati_none)) : '' . esc_html($aieo_cati_none) . '
') . $aieo_cati_close; } else { $schedules = AIEO_Feed_Source_Store::schedules(); $src_rows = array(); foreach ($existing as $def) { $next = wp_next_scheduled(self::CRON_HOOK, array((int) $def['id'])); $runs = isset($schedules[$def['schedule']]) ? (string) $schedules[$def['schedule']] : (string) $def['schedule']; if ('manual' !== $def['schedule'] && $next) { $runs .= '' . esc_html__('A day past the month\'s end runs on its last day.', 'ai-eshop-optimizer') . '
' . '' . esc_html(sprintf( __('Hours are the site\'s time (%s).', 'ai-eshop-optimizer'), wp_timezone_string() )) . '
'; echo self::field(__('Run automatically', 'ai-eshop-optimizer'), $aieo_cati_when, array( __('A scheduled import re-fetches the feed address above and applies this same template, with nobody watching. It needs a feed address: a pasted sample never changes, so putting one on a timer would rewrite the same products for ever.', 'ai-eshop-optimizer'), __('A catalogue too large for one run is not abandoned. The run records where it stopped and the next one carries on from there.', 'ai-eshop-optimizer'), ), array('id' => 'aieo-cati-feed-schedule-row', 'group' => true)); ob_start(); echo ''; echo ''; echo '' . esc_html__('A repeating feed is authoritative about two things: what a product costs and how many are left. "Price and stock only" moves exactly those and nothing else, so a supplier cannot overwrite a name you rewrote or a description you paid for. New products in the feed are still created in full.', 'ai-eshop-optimizer') . '
'; echo '' . esc_html__('Any product can be pinned against feed updates individually, and a pinned product is skipped by every mode here. Products created by a feed record which feed they came from, so a shop taking several supplier feeds can always tell them apart.', 'ai-eshop-optimizer') . '
'; echo '' . $aieo_cati_uo . '
'; echo ''; echo '' . ' ' . '' . esc_html__('products (0 = the whole feed)', 'ai-eshop-optimizer') . '
'; echo '' . esc_html__('Set it to 1 to watch how a single product of this feed actually lands before letting the whole catalogue through. Counted from the top of the feed, before the filters below; every import path of this source obeys it, and the filter pickers and category matches still read the whole feed.', 'ai-eshop-optimizer') . '
'; echo ''; echo '' . esc_html__('Only matters once the source is saved and its feed categories are matched to yours in the panel below. Until a category is matched, it counts as having no match.', 'ai-eshop-optimizer') . '
'; echo '' . esc_html__('Drafts and "only add new products" are the defaults on purpose: nobody is watching a scheduled run, so the recoverable choice is the one that is made for you.', 'ai-eshop-optimizer') . '
'; echo self::field(__('What a scheduled run does', 'ai-eshop-optimizer'), (string) ob_get_clean(), array(), array('id' => 'aieo-cati-feed-opts', 'group' => true)); echo '' . esc_html($text) . '
'; }; echo $aieo_cati_text(__('Conditions on fields inside a repeating group (a per-warehouse availability) are matched within ONE entry of the group, so "address equals X AND availability equals in stock" is true only when that one warehouse says both.', 'ai-eshop-optimizer'), __('How are group conditions matched?', 'ai-eshop-optimizer')); echo ''; echo '' . ' ' . '
'; echo $aieo_cati_text(__('The preview below respects the rules exactly as drafted here; Save stores them with the source, and every import path applies them.', 'ai-eshop-optimizer'), __('When do the rules apply?', 'ai-eshop-optimizer')); echo $aieo_cati_close; } private function render_feed_filters_card() { $picker = function ($id, $kind, $placeholder) { return ''; }; list($aieo_cati_open, $aieo_cati_close) = self::with_attrs(AIEO_DMM_UI::card(array( 'anchor' => 'catalog-importer-filter-what-is-imported', 'icon' => 'funnel', 'title' => __('Filter what is imported', 'ai-eshop-optimizer'), 'description' => __('These filters speak the feed\'s own language: its categories, its brands, its tags, read out of the feed itself. A row the filters refuse is never imported and never counted against a variation group. Leave everything empty to import the whole feed.', 'ai-eshop-optimizer'), )), array('hidden' => 'hidden', 'data-aieo-feed-editcard' => '1')); echo $aieo_cati_open; echo '' . esc_html__('A row matching ANY of these is kept out, whatever the filters above say.', 'ai-eshop-optimizer') . '
'; echo '' . esc_html($aieo_cati_why) . '
'; echo $aieo_cati_close; } private function render_feed_link_brands_card() { list($aieo_cati_open, $aieo_cati_close) = self::with_attrs(AIEO_DMM_UI::card(array( 'anchor' => 'catalog-importer-suppliers-for-existing-products', 'icon' => 'building', 'title' => __('Suppliers for products you already had', 'ai-eshop-optimizer'), 'description' => __('An import records the supplier on every product it touches, and on the brands of that product. Products that were already in the shop before this feed existed have no supplier at all, so they show as unresolved on the re-order boards. This links the brands this feed carries to the supplier of this source, which repairs those older products too: a product looks up its supplier through its brand when it has none of its own. Brands that already name a supplier are never changed, and no product is modified.', 'ai-eshop-optimizer'), )), array('hidden' => 'hidden', 'data-aieo-feed-editcard' => '1')); echo $aieo_cati_open; echo '' . ' ' . \Rooster\Admin\States::outcome('', '', array('id' => 'aieo-cati-linkbrands-status')) . '
'; echo ''; echo $aieo_cati_close; } private function render_feed_run_history_card() { if (!class_exists('AIEO_Feed_Run_Log') || !class_exists('AIEO_Table')) { return; } $runs = AIEO_Feed_Run_Log::recent(0, 30); $names = array(); $link = static function ($s) { $sku = esc_html((string) ($s['sku'] ?? '')); if (!empty($s['id'])) { return '' . $sku . '';
}
return '' . $sku . '';
};
AIEO_Table::card(array(
'anchor' => 'catalog-importer-import-run-history',
'heading' => 'h2',
'title' => __('Import run history', 'ai-eshop-optimizer'),
'description' => __('One row per finished run of every feed source, kept for 30 days. Open a row to see WHICH products were created or updated, which rows errored and why, and the feed-quality notes.', 'ai-eshop-optimizer'),
'id' => 'aieo-cati-runlog',
'page_id' => 'catalog_importer',
'row_key' => 'run_id',
'empty' => __('No finished runs yet. Runs land here as they complete, whether scheduled or started with Run now.', 'ai-eshop-optimizer'),
'per_page' => 10,
'rows' => array_map(function ($r) use (&$names) {
$fid = (int) $r['feed_id'];
if (!isset($names[$fid])) { $names[$fid] = (string) get_the_title($fid); }
return array(
'run_id' => (int) $r['id'],
'when' => get_date_from_gmt((string) $r['started_at'], get_option('date_format') . ' H:i'),
'when_gmt' => (string) $r['started_at'],
'feed' => '' !== $names[$fid] ? $names[$fid] : ('#' . $fid),
'outcome' => !empty($r['ok'])
? (!empty($r['complete']) ? __('finished', 'ai-eshop-optimizer') : __('paused', 'ai-eshop-optimizer'))
: __('failed', 'ai-eshop-optimizer'),
'ok' => (int) $r['ok'],
'created' => (int) $r['created'],
'updated' => (int) $r['updated'],
'skipped' => (int) $r['skipped'],
'filtered' => (int) $r['filtered_out'],
'errors' => (int) $r['errors_count'],
'message' => (string) $r['message'],
'details' => is_array($r['details']) ? $r['details'] : array(),
);
}, (array) $runs),
'columns' => array(
array('key' => 'when', 'label' => __('When', 'ai-eshop-optimizer'), 'type' => 'control', 'sort_key' => 'when_gmt', 'format' => array(
'render' => static function ($r) { return esc_html((string) $r['when']); },
)),
array('key' => 'feed', 'label' => __('Feed source', 'ai-eshop-optimizer'), 'type' => 'text'),
array('key' => 'outcome', 'label' => __('Outcome', 'ai-eshop-optimizer'), 'type' => 'text'),
array('key' => 'created', 'label' => __('Created', 'ai-eshop-optimizer'), 'type' => 'integer', 'tone' => 'success'),
array('key' => 'updated', 'label' => __('Updated', 'ai-eshop-optimizer'), 'type' => 'integer'),
array('key' => 'skipped', 'label' => __('Skipped', 'ai-eshop-optimizer'), 'type' => 'integer'),
array('key' => 'filtered', 'label' => __('Filtered out', 'ai-eshop-optimizer'), 'type' => 'integer'),
array('key' => 'errors', 'label' => __('Errors', 'ai-eshop-optimizer'), 'type' => 'integer', 'bands' => array(array('min' => 1, 'tone' => 'danger'))),
array('key' => 'message', 'label' => __('Result', 'ai-eshop-optimizer'), 'type' => 'text', 'truncate' => 56, 'tooltip' => true),
),
'detail_row' => static function ($row) use ($link) {
$d = (array) $row['details'];
if (!$d) { return ''; }
$out = '';
$sections = array(
'created_samples' => __('Created', 'ai-eshop-optimizer'),
'updated_samples' => __('Updated', 'ai-eshop-optimizer'),
);
foreach ($sections as $k => $label) {
if (empty($d[$k]) || !is_array($d[$k])) { continue; }
$bits = array_map($link, array_slice($d[$k], 0, 200));
$more = (int) $row[('created_samples' === $k) ? 'created' : 'updated'] - count($bits);
$out .= '' . esc_html($label) . ' (' . count($bits) . ($more > 0 ? '+' : '') . '): ' . implode(' ', $bits) . ($more > 0 ? ' ' . esc_html(sprintf( __('and %s more — the list keeps the first 200', 'ai-eshop-optimizer'), number_format_i18n($more) )) . '' : '') . '
'; } if (!empty($d['error_samples']) && is_array($d['error_samples'])) { $out .= '' . esc_html__('Errors', 'ai-eshop-optimizer') . ':
' . esc_html((string) ($e['sku'] ?? '')) . ' — ' . esc_html((string) ($e['error'] ?? '')) . '' . esc_html__('Feed-quality notes', 'ai-eshop-optimizer') . ':
' . esc_html((string) ($n['key'] ?? '')) . ' — ' . esc_html((string) ($n['reason'] ?? '')) . '' . ' ' . \Rooster\Admin\States::outcome('', '', array('id' => 'aieo-cati-catmap-status')) . '
'; echo ''; if (class_exists('\Rooster\Admin\States')) { \Rooster\Admin\States::enqueue(); } echo $aieo_cati_close; } private function render_feed_vocab_card() { if (!class_exists('AIEO_Docscan_Vocab')) { return; } list($aieo_cati_open, $aieo_cati_close) = self::with_attrs(AIEO_DMM_UI::card(array( 'anchor' => 'catalog-importer-supplier-vocabulary', 'icon' => 'book-open', 'title' => __('Supplier vocabulary — contradictions', 'ai-eshop-optimizer'), 'description' => __('The invoice scanner matches supplier documents against the wording this feed carries. When you confirm an invoice line onto a DIFFERENT product than the feed\'s vocabulary predicted, the row is flagged here: either keep the feed\'s mapping, or suppress the entry so it stops matching.', 'ai-eshop-optimizer'), )), array('hidden' => 'hidden', 'data-aieo-feed-editcard' => '1')); echo $aieo_cati_open . '' . $aieo_cati_close; } }