'daily', 'time' => '03:30', ); } public static function settings() { $stored = get_option(self::SETTINGS_OPTION, array()); return array_merge(self::defaults(), is_array($stored) ? $stored : array()); } public function maybe_schedule() { $cfg = self::settings(); $next = (int) wp_next_scheduled(self::CRON_HOOK); $sched = wp_get_schedule(self::CRON_HOOK); if ($cfg['frequency'] === 'off') { if ($next > 0) { wp_clear_scheduled_hook(self::CRON_HOOK); } return; } $desired_recurrence = $cfg['frequency'] === 'hourly' ? 'hourly' : 'daily'; if ($sched === $desired_recurrence && $next > 0) { return; } wp_clear_scheduled_hook(self::CRON_HOOK); $first_ts = $cfg['frequency'] === 'hourly' ? (time() + MINUTE_IN_SECONDS) : $this->next_athens_at($cfg['time']); wp_schedule_event($first_ts, $desired_recurrence, self::CRON_HOOK); } private function next_athens_at($hhmm) { try { $tz = new \DateTimeZone('Europe/Athens'); $next = new \DateTime('today ' . $hhmm . ':00', $tz); if ($next->getTimestamp() <= time()) { $next->modify('+1 day'); } return (int) $next->getTimestamp(); } catch (\Throwable $e) { return time() + DAY_IN_SECONDS; } } public function cron_run_pipeline() { $this->run_pipeline('cron'); } public function run_pipeline($source = 'manual') { $lock_key = 'aieo_dmm_data_prep_running'; if (get_transient($lock_key)) { return array( 'source' => $source, 'started_at' => current_time('mysql', true), 'stages' => array(), 'ok' => false, 'error' => __('Data prep pipeline already running in another process — skipped concurrent invocation.', 'ai-eshop-optimizer'), 'skipped' => true, ); } set_transient($lock_key, time(), 90 * MINUTE_IN_SECONDS); register_shutdown_function(function () use ($lock_key) { $err = error_get_last(); $fatal_types = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR); if ($err && in_array($err['type'], $fatal_types, true)) { delete_transient($lock_key); } }); global $wpdb; @set_time_limit(0); if (false !== stripos((string) $wpdb->db_server_info(), 'mariadb')) { $wpdb->query("SET SESSION tmp_disk_table_size = 4294967296"); $wpdb->query("SET SESSION max_statement_time = 180"); } $started = microtime(true); $log = array( 'source' => $source, 'started_at' => current_time('mysql', true), 'stages' => array(), 'ok' => true, 'error' => '', ); $prefix = $wpdb->prefix; $stages = array( 'category_hierarchy' => array( 'sproc' => $prefix . 'AIEO_InsertProductCategoryHierarchy', 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_category_hierarchy", 'notes_sql' => "SELECT CONCAT( COUNT(DISTINCT top_category_id), ' menu / ', COUNT(DISTINCT second_level_category_id), ' head / ', COUNT(DISTINCT third_level_category_id), ' leaf categories' ) FROM {$wpdb->prefix}aieo_core_product_category_hierarchy", ), 'product_attributes' => array( 'callback' => array($this, 'run_stage_product_attributes'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_attributes WHERE brand_id > 0", 'notes_sql' => "SELECT CONCAT( SUM(brand_id > 0), ' / ', COUNT(*), ' with brand · ', COUNT(DISTINCT CASE WHEN brand_id > 0 THEN brand_id END), ' distinct brands' ) FROM {$wpdb->prefix}aieo_core_product_attributes", ), 'analyze_dims' => array( 'callback' => array($this, 'run_stage_analyze_dims'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_attributes", ), 'product_vitals' => array( 'sproc' => $prefix . 'AIEO_InsertProductVitals', 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE parent_id = product_id", 'notes_sql' => "SELECT CONCAT( SUM(variation_count = 0 OR variation_count IS NULL), ' simple + ', SUM(variation_count > 0), ' variable parents' ) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE parent_id = product_id", ), 'variation_vitals' => array( 'sproc' => $prefix . 'AIEO_InsertVariationVitals', 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_variation_vitals", 'notes_sql' => "SELECT CONCAT( COUNT(*), ' variations · avg ', ROUND(COUNT(*) / NULLIF(COUNT(DISTINCT parent_id), 0), 1), ' per parent' ) FROM {$wpdb->prefix}aieo_core_variation_vitals", ), 'combine_variations' => array( 'sproc' => $prefix . 'AIEO_CombineVariationVitalsInProductVitals', 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals", 'notes_sql' => "SELECT CONCAT( SUM(parent_id = product_id), ' parent + ', SUM(parent_id <> product_id), ' variation rows' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'analyze_vitals' => array( 'callback' => array($this, 'run_stage_analyze_vitals'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'propagate_brand' => array( 'callback' => array($this, 'run_stage_propagate_brand'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE product_id <> parent_id AND brand IS NOT NULL AND brand <> '' AND brand <> 'No Brand'", 'notes_sql' => "SELECT CONCAT( SUM(product_id <> parent_id AND brand IS NOT NULL AND brand <> '' AND brand <> 'No Brand'), ' / ', SUM(product_id <> parent_id), ' variations now branded' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'needs_population' => array( 'callback' => array($this, 'run_stage_needs_population'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE primary_need_id IS NOT NULL", 'notes_sql' => "SELECT CONCAT( SUM(primary_need_id IS NOT NULL), ' / ', COUNT(*), ' with primary need · ', COUNT(DISTINCT primary_need_id), ' distinct needs' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'content_text' => array( 'callback' => array($this, 'run_stage_content_text'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_content_text", 'notes_sql' => "SELECT CONCAT( COUNT(*), ' texts · ', SUM(word_count), ' words · newest ', COALESCE(MAX(updated_at), '—') ) FROM {$wpdb->prefix}aieo_content_text", ), 'semantic_index' => array( 'callback' => array($this, 'run_stage_semantic_index'), 'count_sql' => 'SELECT 0', ), 'semantic_terms_gc' => array( 'callback' => array($this, 'run_stage_semantic_terms_gc'), 'count_sql' => 'SELECT 0', ), 'semantic_related_local' => array( 'callback' => array($this, 'run_stage_semantic_related_local'), 'count_sql' => 'SELECT 0', ), 'semantic_demand_enrich' => array( 'callback' => array($this, 'run_stage_semantic_demand_enrich'), 'count_sql' => 'SELECT 0', ), 'variation_swatches' => array( 'callback' => array($this, 'run_stage_variation_swatches'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE variation_swatch IS NOT NULL AND variation_swatch <> ''", 'notes_sql' => "SELECT CONCAT( SUM(variation_swatch IS NOT NULL AND variation_swatch <> ''), ' / ', SUM(product_id <> parent_id), ' variations have a swatch image' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'sellable_status_flag' => array( 'callback' => array($this, 'run_stage_sellable_status_flag'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE status = 1", 'notes_sql' => "SELECT CONCAT( SUM(status = 1), ' sellable · ', SUM(status = 0 AND variation_count > 0), ' variable parents hidden' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'storefront_facets' => array( 'callback' => array($this, 'run_stage_storefront_facets'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals WHERE stock_status IS NOT NULL", 'notes_sql' => "SELECT CONCAT( SUM(stock_status = 'instock'), ' in stock · ', SUM(stock_status = 'outofstock'), ' out of stock · ', SUM(stock_status = 'onbackorder'), ' on backorder' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'vitals_swap' => array( 'callback' => array($this, 'run_stage_vitals_swap'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_product_vitals", 'notes_sql' => "SELECT CONCAT( SUM(parent_id = product_id), ' products + ', SUM(parent_id <> product_id), ' variations live' ) FROM {$wpdb->prefix}aieo_core_product_vitals", ), 'brand_vitals' => array( 'callback' => array($this, 'run_stage_brand_vitals'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_core_brand_vitals", 'notes_sql' => "SELECT CONCAT( SUM(product_count > 0), ' brands w/ products · top: ', COALESCE((SELECT CONCAT(brand_name, ' (', product_count, ')') FROM {$wpdb->prefix}aieo_core_brand_vitals WHERE product_count > 0 ORDER BY product_count DESC LIMIT 1), '—') ) FROM {$wpdb->prefix}aieo_core_brand_vitals", ), 'effective_prices' => array( 'callback' => array($this, 'run_stage_effective_prices'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_effective_prices", 'notes_sql' => "SELECT CONCAT( SUM(was_on_sale = 1), ' on sale · ', SUM(role_price_applied = 1), ' role-priced · ', SUM(monthly_offer_active = 1), ' monthly offer' ) FROM {$wpdb->prefix}aieo_effective_prices", ), 'effective_eligibility' => array( 'callback' => array($this, 'run_stage_effective_eligibility'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_effective_eligibility", 'notes_sql' => "SELECT CONCAT( SUM(eligible = 1), ' eligible across ', COUNT(DISTINCT surface), ' surfaces' ) FROM {$wpdb->prefix}aieo_effective_eligibility", ), 'seo_head_cache' => array( 'callback' => array($this, 'run_stage_seo_head_cache'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_seo_head_cache", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' cached heads') FROM {$wpdb->prefix}aieo_seo_head_cache", ), 'seo_sitemap' => array( 'callback' => array($this, 'run_stage_seo_sitemap'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_seo_posts WHERE canonical_url <> '' AND (robots_noindex = 0 OR robots_noindex IS NULL)", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' sitemap URLs') FROM {$wpdb->prefix}aieo_seo_posts WHERE canonical_url <> '' AND (robots_noindex = 0 OR robots_noindex IS NULL)", ), 'seo_scores' => array( 'callback' => array($this, 'run_stage_seo_scores'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_seo_scores", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' scored · avg ', COALESCE(ROUND(AVG(score)),0), '/100 · ', COALESCE(SUM(fix_count),0), ' fixes') FROM {$wpdb->prefix}aieo_seo_scores", ), 'seo_pillars' => array( 'callback' => array($this, 'run_stage_seo_pillars'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_seo_scores WHERE is_pillar = 1", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' pillar products') FROM {$wpdb->prefix}aieo_seo_scores WHERE is_pillar = 1", ), 'seo_image_alt' => array( 'callback' => array($this, 'run_stage_seo_image_alt'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_image_alt' AND meta_value <> ''", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' image alts set') FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_image_alt' AND meta_value <> ''", ), 'seo_redirect_map' => array( 'callback' => array($this, 'run_stage_seo_redirect_map'), 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->prefix}aieo_seo_redirects WHERE enabled = 1", 'notes_sql' => "SELECT CONCAT(COUNT(*), ' edge redirects') FROM {$wpdb->prefix}aieo_seo_redirects WHERE enabled = 1", ), ); foreach ($stages as $name => $stage) { if ('product_vitals' === $name) { $this->vitals_busy = false; $log['stages']['vitals_window'] = $this->open_vitals_window(); if ($this->vitals_busy) { $log['ok'] = false; $log['error'] = 'vitals_window: ' . $log['stages']['vitals_window']['notes']; break; } } $t0 = microtime(true); $hr0 = $this->handler_reads(); if (isset($stage['callback']) && is_callable($stage['callback'])) { $mark = function_exists('aieo_sql_error_mark') ? aieo_sql_error_mark() : 0; try { call_user_func($stage['callback']); } catch (\Throwable $e) { $log['ok'] = false; $log['error'] = $name . ': ' . $e->getMessage(); $log['stages'][$name] = array('error' => $e->getMessage(), 'duration' => round(microtime(true) - $t0, 2)); break; } $sql_errors = function_exists('aieo_sql_errors_since') ? aieo_sql_errors_since($mark) : array(); if ($sql_errors) { $log['ok'] = false; $log['error'] = $log['error'] !== '' ? $log['error'] : $name . ': ' . $sql_errors[0]; $log['stages'][$name] = array('error' => $sql_errors[0], 'errors' => count($sql_errors), 'duration' => round(microtime(true) - $t0, 2)); continue; } $count = (int) $wpdb->get_var($stage['count_sql']); $notes = !empty($stage['notes_sql']) ? (string) $wpdb->get_var($stage['notes_sql']) : ''; $log['stages'][$name] = array( 'rows' => $count, 'duration' => round(microtime(true) - $t0, 2), 'notes' => $notes, 'handler_reads' => $this->stage_handler_delta($name, $hr0), ); continue; } $exists = (string) $wpdb->get_var($wpdb->prepare( "SELECT routine_name FROM information_schema.routines WHERE routine_schema = DATABASE() AND routine_type='PROCEDURE' AND routine_name=%s", $stage['sproc'] )) === $stage['sproc']; if (!$exists) { $log['stages'][$name] = array('skipped' => 'sproc_missing', 'duration' => 0); continue; } try { aieo_call_sproc("CALL `{$stage['sproc']}`()", null); } catch (\Throwable $e) { $wpdb->last_error = $e->getMessage(); } if ($wpdb->last_error) { $log['ok'] = false; $log['error'] = $name . ': ' . $wpdb->last_error; $log['stages'][$name] = array('error' => $wpdb->last_error, 'duration' => round(microtime(true) - $t0, 2)); break; } $count = (int) $wpdb->get_var($stage['count_sql']); $notes = !empty($stage['notes_sql']) ? (string) $wpdb->get_var($stage['notes_sql']) : ''; $log['stages'][$name] = array( 'rows' => $count, 'duration' => round(microtime(true) - $t0, 2), 'notes' => $notes, 'handler_reads' => $this->stage_handler_delta($name, $hr0), ); } if (class_exists('AIEO_Vitals_Build') && AIEO_Vitals_Build::is_open()) { $aieo_swap = AIEO_Vitals_Build::close(false); $log['stages']['vitals_swap'] = array('skipped' => (string) $aieo_swap['why'], 'duration' => 0); } $log['total_duration'] = round(microtime(true) - $started, 2); $log['finished_at'] = current_time('mysql', true); update_option(self::LAST_RUN_OPTION, $log, false); if (function_exists('aieo_debug_log')) { aieo_debug_log('AIEO_DMM_Data_Prep_Scheduler ' . $source . ' run: ' . wp_json_encode($log)); } delete_transient($lock_key); return $log; } private function open_vitals_window() { if (!class_exists('AIEO_Vitals_Build')) { return array('rows' => 0, 'duration' => 0, 'notes' => 'building in place: AIEO_Vitals_Build is not there'); } $t0 = microtime(true); if (class_exists('AIEO_Vitals_Facets')) { AIEO_Vitals_Facets::maybe_install(); } $window = AIEO_Vitals_Build::open(); if ('busy' === $window['mode']) { $this->vitals_busy = true; return array('rows' => 0, 'duration' => round(microtime(true) - $t0, 2), 'notes' => 'not built: ' . $window['why']); } return array( 'rows' => 0, 'duration' => round(microtime(true) - $t0, 2), 'notes' => 'beside' === $window['mode'] ? 'building beside the live table' : 'building in place: ' . $window['why'], ); } private $vitals_busy = false; public function run_stage_storefront_facets() { if (!class_exists('AIEO_Vitals_Facets') || !AIEO_Vitals_Facets::ready()) { return; } $filled = AIEO_Vitals_Facets::fill(); AIEO_Vitals_Facets::mark_filled(empty($filled['errors'])); } public function run_stage_vitals_swap() { if (!class_exists('AIEO_Vitals_Build') || !AIEO_Vitals_Build::is_open()) { return; } $swap = AIEO_Vitals_Build::close(true); if (empty($swap['swapped'])) { throw new \RuntimeException((string) $swap['why']); } } public function run_stage_analyze_vitals() { global $wpdb; $wpdb->query("ANALYZE TABLE {$wpdb->prefix}aieo_core_product_vitals"); } public function run_stage_analyze_dims() { global $wpdb; $wpdb->query("ANALYZE TABLE {$wpdb->prefix}aieo_core_product_attributes"); $wpdb->query("ANALYZE TABLE {$wpdb->prefix}aieo_core_product_category_hierarchy"); } private function handler_reads() { global $wpdb; $rows = $wpdb->get_results( "SHOW SESSION STATUS WHERE Variable_name IN ('Handler_read_rnd_next','Handler_read_next')", ARRAY_A ); $sum = 0.0; foreach ((array) $rows as $r) { $sum += (float) $r['Value']; } return $sum; } private function stage_handler_delta($name, $baseline) { $delta = (int) max(0, $this->handler_reads() - $baseline); if ($delta > 20000000 && function_exists('aieo_debug_log')) { aieo_debug_log(sprintf( 'AIEO data-prep FLIP WARNING: stage "%s" examined ~%s rows (> 20M) — likely a stale-stats plan flip; check the seam ANALYZE / index hints for this stage.', $name, number_format($delta) )); } return $delta; } public function run_stage_brand_vitals() { if (!class_exists('AIEO_Core_Brand_Vitals')) { return; } $bv = AIEO_Core_Brand_Vitals::instance(); $bv->drain_dirty(); $bv->refresh(); } public function run_stage_seo_head_cache() { if (!class_exists('AIEO_SEO_Head_Builder') || !class_exists('AIEO_SEO_Store') || !AIEO_SEO_Store::is_active_provider()) { return; } AIEO_SEO_Head_Builder::drain_dirty(1000); AIEO_SEO_Head_Builder::run_backfill(2000); } public function run_stage_seo_sitemap() { if (!class_exists('AIEO_SEO_Sitemap')) { return; } if (AIEO_SEO_Sitemap::is_active()) { if (class_exists('AIEO_SEO_Sitemap_Rules') && AIEO_SEO_Sitemap_Rules::column_ok()) { $rules = AIEO_SEO_Sitemap_Rules::settings(); foreach (array('category' => 'default_category', 'product_cat' => 'default_product_cat') as $tax => $opt) { if (taxonomy_exists($tax) && (int) get_option($opt, 0) > 0) { AIEO_SEO_Sitemap_Rules::refresh($tax, (int) get_option($opt), 'term'); } } if ($rules['rules'] || $rules['only'] || has_filter('aieo_seo_sitemap_include')) { $last = 0; do { $batch = AIEO_SEO_Sitemap_Rules::apply_batch($last, 1000); $last = $batch['last_id']; if (function_exists('wp_cache_supports') && wp_cache_supports('flush_runtime')) { wp_cache_flush_runtime(); } } while (!$batch['done']); } } if (class_exists('AIEO_SEO_Sitemap_Priority')) { AIEO_SEO_Sitemap_Priority::run_all(); } } AIEO_SEO_Sitemap::build(); } public function run_stage_seo_scores() { if (!class_exists('AIEO_SEO_Score')) { return; } AIEO_SEO_Score::run_backfill(1500); } public function run_stage_seo_pillars() { if (!class_exists('AIEO_SEO_Pillars')) { return; } AIEO_SEO_Pillars::maybe_rebuild(); } public function run_stage_seo_redirect_map() { if (!class_exists('AIEO_SEO_Redirects')) { return; } AIEO_SEO_Redirects::export_edge_map(); } public function run_stage_seo_image_alt() { if (class_exists('AIEO_DMM_Settings') && ! AIEO_DMM_Settings::get('seo.image_alt_enabled', true)) { return; } if (class_exists('AIEO_SEO_Image')) { AIEO_SEO_Image::backfill_alt(300); } } public function run_stage_product_attributes() { global $wpdb; $sp = $wpdb->prefix . 'AIEO_InsertCoreProductAttributes'; $exists = (string) $wpdb->get_var($wpdb->prepare( "SELECT ROUTINE_NAME FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_NAME = %s AND ROUTINE_TYPE = 'PROCEDURE'", $sp )) === $sp; if (!$exists) { return; } $vendor = (string) get_option('aieo_core_attribute_vendor', ''); $brands = (string) get_option('aieo_core_attribute_brands', 'product_brand'); $sizes = (string) get_option('aieo_core_attribute_size', ''); $colors = (string) get_option('aieo_core_attribute_color', ''); if ($brands === '') { $brands = 'product_brand'; } $wpdb->query($wpdb->prepare( "CALL `{$sp}` (%s, %s, %s, %s)", $vendor, $brands, $sizes, $colors )); } public function run_stage_propagate_brand() { global $wpdb; $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; $wpdb->query("ANALYZE TABLE {$vitals}"); $wpdb->query( "UPDATE {$vitals} v INNER JOIN {$vitals} p FORCE INDEX (aieo_idx_vitals_product_id) ON p.product_id = v.parent_id AND p.product_id <> v.product_id SET v.brand = p.brand, v.brand_id = p.brand_id, v.brand_slug = p.brand_slug, v.brand_bias = p.brand_bias WHERE v.product_id <> v.parent_id AND p.brand IS NOT NULL AND p.brand <> '' AND p.brand <> 'No Brand'" ); } public function run_stage_propagate_marketplace_categories() { global $wpdb; $ce = $wpdb->prefix . 'aieo_dmm_category_extras'; $pv = $wpdb->prefix . 'aieo_core_product_vitals'; if ($wpdb->get_var("SHOW TABLES LIKE '{$ce}'") !== $ce) { return; } $wpdb->query( "UPDATE {$pv} v LEFT JOIN {$ce} ce_sub ON ce_sub.taxonomy = 'product_cat' AND ce_sub.term_id = v.subcat_id LEFT JOIN {$ce} ce_head ON ce_head.taxonomy = 'product_cat' AND ce_head.term_id = v.head_id LEFT JOIN {$ce} ce_menu ON ce_menu.taxonomy = 'product_cat' AND ce_menu.term_id = v.menu_id SET v.google_product_category = COALESCE( NULLIF(ce_sub.google_category_path, ''), NULLIF(ce_head.google_category_path, ''), NULLIF(ce_menu.google_category_path, '') ), v.facebook_product_category = COALESCE( NULLIF(ce_sub.facebook_category_path, ''), NULLIF(ce_head.facebook_category_path, ''), NULLIF(ce_menu.facebook_category_path, '') )" ); } public function run_stage_needs_population() { $needs_file = plugin_dir_path(dirname(dirname(__FILE__))) . 'class-product-needs.php'; if (!class_exists('AI_eShop_Product_Needs') && file_exists($needs_file)) { require_once $needs_file; } if (class_exists('AI_eShop_Product_Needs')) { AI_eShop_Product_Needs::get_instance()->populate_product_needs(); } } public function run_stage_content_text() { if (!class_exists('AIEO_Content_Text')) { $file = plugin_dir_path(dirname(dirname(__FILE__))) . 'class-aieo-content-text.php'; if (file_exists($file)) { require_once $file; } } if (!class_exists('AIEO_Content_Text')) { return; } for ($i = 0; $i < 10; $i++) { $result = AIEO_Content_Text::refresh(300); if (!empty($result['done'])) { break; } } } public function run_stage_semantic_index() { if (!class_exists('AIEO_Semantic_Index')) { return; } if (!method_exists('AIEO_Semantic_Index', 'process_batch')) { return; } AIEO_Semantic_Index::process_batch(200); } public function run_stage_semantic_terms_gc() { if (!class_exists('AIEO_Semantic_Index_Store')) { return; } if (!method_exists('AIEO_Semantic_Index_Store', 'terms_gc')) { return; } AIEO_Semantic_Index_Store::terms_gc(); } public function run_stage_semantic_related_local() { if (!class_exists('AIEO_Semantic_Similarity')) { return; } if (!method_exists('AIEO_Semantic_Similarity', 'materialize_batch')) { return; } AIEO_Semantic_Similarity::materialize_batch(); } public function run_stage_semantic_demand_enrich() { if (!class_exists('AIEO_Semantic_Content_Gaps')) { return; } AIEO_Semantic_Content_Gaps::enrich(500); } public function run_stage_variation_swatches() { global $wpdb; $uploads = wp_upload_dir(); if (empty($uploads['baseurl'])) { return; } $base = esc_sql(trailingslashit(wp_make_link_relative($uploads['baseurl']))); $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; $wpdb->query("ANALYZE TABLE {$vitals}"); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) INNER JOIN {$wpdb->postmeta} pm_attr ON pm_attr.post_id = v.product_id AND pm_attr.meta_key LIKE 'attribute_pa_%' INNER JOIN {$wpdb->terms} t ON t.slug = pm_attr.meta_value INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id AND tt.taxonomy = REPLACE(pm_attr.meta_key, 'attribute_', '') INNER JOIN {$wpdb->termmeta} tm ON tm.term_id = t.term_id AND tm.meta_key = '_aieo_swatch_image_id' AND tm.meta_value <> '' AND tm.meta_value <> '0' INNER JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(tm.meta_value AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' SET v.variation_swatch = CONCAT('{$base}', pm_file.meta_value) WHERE v.product_id <> v.parent_id" ); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) INNER JOIN {$wpdb->postmeta} pm_attr ON pm_attr.post_id = v.product_id AND pm_attr.meta_key LIKE 'attribute_pa_%' INNER JOIN {$wpdb->terms} t ON t.slug = pm_attr.meta_value INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id AND tt.taxonomy = REPLACE(pm_attr.meta_key, 'attribute_', '') INNER JOIN {$wpdb->termmeta} tm ON tm.term_id = t.term_id AND tm.meta_key = 'product_attribute_image' AND tm.meta_value <> '' AND tm.meta_value <> '0' INNER JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(tm.meta_value AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' SET v.variation_swatch = CONCAT('{$base}', pm_file.meta_value) WHERE v.product_id <> v.parent_id AND (v.variation_swatch IS NULL OR v.variation_swatch = '')" ); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) INNER JOIN {$wpdb->posts} p ON p.ID = v.product_id AND p.post_type = 'product_variation' INNER JOIN {$wpdb->postmeta} pm_gal ON pm_gal.post_id = v.product_id AND pm_gal.meta_key = '_product_image_gallery' AND pm_gal.meta_value <> '' INNER JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(SUBSTRING_INDEX(pm_gal.meta_value, ',', 1) AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' SET v.image_url = CONCAT('{$base}', pm_file.meta_value)" ); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) INNER JOIN {$wpdb->posts} p ON p.ID = v.product_id AND p.post_type = 'product_variation' INNER JOIN {$wpdb->postmeta} pm_gal ON pm_gal.post_id = v.product_id AND pm_gal.meta_key = 'botiga_variation_gallery' AND pm_gal.meta_value <> '' AND pm_gal.meta_value <> 'a:0:{}' INNER JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(pm_gal.meta_value, ':\"', -1), '\";', 1) AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' SET v.image_url = CONCAT('{$base}', pm_file.meta_value) WHERE v.image_url IS NULL OR v.image_url = ''" ); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) JOIN ( SELECT pm.post_id, GROUP_CONCAT(CONCAT('{$base}', pm_file.meta_value) ORDER BY n.n SEPARATOR ',') AS urls FROM {$wpdb->postmeta} pm JOIN ( SELECT 1 AS n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19 UNION SELECT 20 ) n ON CHAR_LENGTH(pm.meta_value) - CHAR_LENGTH(REPLACE(pm.meta_value, ',', '')) >= n.n - 1 JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(pm.meta_value, ',', n.n), ',', -1) AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' WHERE pm.meta_key = '_product_image_gallery' AND pm.meta_value <> '' GROUP BY pm.post_id ) gal ON gal.post_id = v.product_id SET v.image_gallery_urls = gal.urls" ); $wpdb->query( "UPDATE {$vitals} v FORCE INDEX (aieo_idx_vitals_product_id) INNER JOIN {$wpdb->posts} p ON p.ID = v.product_id AND p.post_type = 'product_variation' INNER JOIN {$wpdb->postmeta} pm_gal ON pm_gal.post_id = v.product_id AND pm_gal.meta_key = 'botiga_variation_gallery' AND pm_gal.meta_value <> '' AND pm_gal.meta_value <> 'a:0:{}' INNER JOIN {$wpdb->postmeta} pm_file ON pm_file.post_id = CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(pm_gal.meta_value, ':\"', -1), '\";', 1) AS UNSIGNED) AND pm_file.meta_key = '_wp_attached_file' SET v.image_gallery_urls = CONCAT('{$base}', pm_file.meta_value) WHERE v.image_gallery_urls IS NULL OR v.image_gallery_urls = ''" ); if (class_exists('AIEO_DMM_Variations_Gallery') && has_filter('aieo_variation_gallery_image_ids')) { $variation_ids = $wpdb->get_col( "SELECT v.ID FROM {$wpdb->posts} v WHERE v.post_type = 'product_variation' AND v.post_status IN ('publish','private')" ); foreach ($variation_ids as $vid) { $ids = AIEO_DMM_Variations_Gallery::resolve_image_ids((int) $vid, 'data_prep'); if (empty($ids)) { continue; } $canonical = (string) get_post_meta((int) $vid, '_product_image_gallery', true); $canonical_ids = $canonical !== '' ? array_values(array_filter(array_map('intval', explode(',', $canonical)))) : array(); if ($canonical_ids === $ids) { continue; } $urls = array(); foreach ($ids as $aid) { $url = wp_get_attachment_image_url($aid, 'full'); if ($url) { $urls[] = wp_make_link_relative($url); } } if (!empty($urls)) { $wpdb->update( $wpdb->prefix . 'aieo_core_product_vitals', array('image_gallery_urls' => implode(',', $urls)), array('product_id' => (int) $vid) ); } } } } public function run_stage_sellable_status_flag() { global $wpdb; $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; $wpdb->query("ANALYZE TABLE {$vitals}"); $wpdb->query( "UPDATE {$vitals} v JOIN ( SELECT DISTINCT c.parent_id FROM {$vitals} c WHERE c.product_id <> c.parent_id ) kids ON kids.parent_id = v.product_id SET v.status = 0 WHERE v.product_id = v.parent_id" ); $wpdb->query( "UPDATE {$vitals} v INNER JOIN {$wpdb->posts} p ON p.ID = v.product_id INNER JOIN {$wpdb->posts} pp ON pp.ID = v.parent_id SET v.status = 1 WHERE v.product_id <> v.parent_id AND p.post_status = 'publish' AND pp.post_status = 'publish'" ); } public function run_stage_effective_prices() { $this->drain_substrate_queue('effective_prices', 'AIEO_Effective_Prices'); } public function run_stage_effective_eligibility() { $this->drain_substrate_queue('effective_eligibility', 'AIEO_Effective_Eligibility'); } private function drain_substrate_queue($surface, $worker_class) { if (!class_exists($worker_class) || !class_exists('AIEO_Recompute_Queue')) { return; } if (!AIEO_Recompute_Queue::table_exists()) { return; } global $wpdb; $tbl = AIEO_Recompute_Queue::table_name(); $batch = 200; $max_rounds = 25; while ($max_rounds-- > 0) { $rows = $wpdb->get_results($wpdb->prepare( "SELECT id, entity_id, audience_key, attempts FROM {$tbl} WHERE surface = %s AND attempts < 3 ORDER BY id ASC LIMIT %d", $surface, $batch ), ARRAY_A); if (empty($rows)) { break; } foreach ($rows as $r) { $err = null; try { if (!empty($r['audience_key'])) { $worker_class::recompute((int) $r['entity_id'], (string) $r['audience_key']); } else { $worker_class::recompute_all_audiences((int) $r['entity_id']); } } catch (\Throwable $e) { $err = $e->getMessage(); } if ($err === null) { $wpdb->delete($tbl, array('id' => (int) $r['id']), array('%d')); } else { $wpdb->update( $tbl, array('attempts' => ((int) $r['attempts']) + 1, 'last_error' => substr($err, 0, 250)), array('id' => (int) $r['id']), array('%d', '%s'), array('%d') ); } } } } public function ajax_full_substrate() { AIEO_DMM::verify_ajax_request(); @set_time_limit(0); global $wpdb; $started = microtime(true); if (!class_exists('AIEO_Recompute_Queue') || !AIEO_Recompute_Queue::table_exists()) { wp_send_json_error(array('message' => __('Recompute queue not installed.', 'ai-eshop-optimizer'))); } do_action('aieo_dmm_cache_version_bumped', 'gifts'); $tbl = AIEO_Recompute_Queue::table_name(); $depth_after_enqueue = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tbl}"); $this->run_stage_effective_prices(); $this->run_stage_effective_eligibility(); $depth_remaining = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tbl}"); $duration = round(microtime(true) - $started, 2); wp_send_json_success(array( 'message' => sprintf( __('Enqueued %1$s, drained %2$s, %3$s left in queue (will be processed on next ticks). Took %4$ss.', 'ai-eshop-optimizer'), number_format_i18n($depth_after_enqueue), number_format_i18n($depth_after_enqueue - $depth_remaining), number_format_i18n($depth_remaining), $duration ), 'enqueued' => $depth_after_enqueue, 'remaining' => $depth_remaining, 'duration' => $duration, )); } public function ajax_save() { AIEO_DMM::verify_ajax_request(); $freq = isset($_POST['frequency']) ? sanitize_key((string) wp_unslash($_POST['frequency'])) : ''; $time = isset($_POST['time']) ? sanitize_text_field((string) wp_unslash($_POST['time'])) : '03:30'; if (!in_array($freq, array('off', 'hourly', 'daily'), true)) { $freq = 'off'; } if (!preg_match('/^\d{2}:\d{2}$/', $time)) { $time = '03:30'; } update_option(self::SETTINGS_OPTION, array('frequency' => $freq, 'time' => $time), false); $this->maybe_schedule(); wp_send_json_success(array( 'message' => __('Schedule saved.', 'ai-eshop-optimizer'), 'next_at' => (int) wp_next_scheduled(self::CRON_HOOK), )); } public function ajax_run_now() { AIEO_DMM::verify_ajax_request(); $log = $this->run_pipeline('manual'); wp_send_json_success(array( 'log' => $log, 'message' => $log['ok'] ? sprintf(__('Pipeline completed in %ss.', 'ai-eshop-optimizer'), $log['total_duration']) : sprintf(__('Failed: %s', 'ai-eshop-optimizer'), $log['error']), )); } public function render_subtab() { $cfg = self::settings(); $last = (array) get_option(self::LAST_RUN_OPTION, array()); $next_ts = (int) wp_next_scheduled(self::CRON_HOOK); $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION); $ajax = admin_url('admin-ajax.php'); rooster_admin_band_open(array('cols' => 1)); $form_id = 'aieo-card-data-prep-scheduler-substrate-schedule-form'; $aieo_dp_confirm = ''; $aieo_dp_dialog = ''; if (class_exists('\Rooster\Admin\States')) { foreach (\Rooster\Admin\States::confirm_attrs('aieo-dp-substrate-dialog') as $k => $v) { $aieo_dp_confirm .= ' ' . $k . '="' . esc_attr($v) . '"'; } $aieo_dp_products = function_exists('wp_count_posts') ? (int) wp_count_posts('product')->publish : 0; $aieo_dp_dialog = \Rooster\Admin\States::confirm( 'aieo-dp-substrate-dialog', 'apply', __('Rebuild the substrate for every product?', 'ai-eshop-optimizer'), '

' . esc_html(sprintf( __('Published products queued for their prices and offer eligibility: %s. Then the queue drains; a large catalogue takes 1 to 3 minutes.', 'ai-eshop-optimizer'), number_format_i18n($aieo_dp_products) )) . '

', array('confirm' => __('Rebuild', 'ai-eshop-optimizer')) ); } $footer = (class_exists('\Rooster\Admin\States') ? \Rooster\Admin\States::save_button($form_id) : '') . ' ' . ' ' . ' ' . (class_exists('\Rooster\Admin\States') ? \Rooster\Admin\States::outcome('', '', array('id' => 'aieo-dp-status')) : ''); list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => 'data-prep-scheduler-substrate-schedule', 'icon' => 'calendar-days', 'title' => __('Substrate schedule', 'ai-eshop-optimizer'), 'description' => __('Everything on this site that rebuilds a table on a clock. Two pipelines, each on its own schedule: the SUBSTRATE the storefront reads from, and the ANALYTICS JOBS the report pages read from. To see what the whole install measures — including what is dormant or unread — use Signals.', 'ai-eshop-optimizer'), 'footer' => $footer, )); echo $open; echo $aieo_dp_dialog; $aieo_dp_why = __('Refreshes the Rooster One flat tables that marketplace feeds, recommendations, and the storefront read from — wp_aieo_core_product_vitals, brand vitals, plus the substrate tables that drive badge eligibility (wp_aieo_effective_prices) and per-product offer eligibility (wp_aieo_effective_eligibility). The substrate stages drain queued recomputes in steady state; use "Full substrate rebuild" after a sweeping rule change.', 'ai-eshop-optimizer'); echo class_exists('\Rooster\Admin\Guidance') ? \Rooster\Admin\Guidance::text($aieo_dp_why) : '

' . esc_html($aieo_dp_why) . '

'; ob_start(); echo '
'; foreach (array( 'off' => __('Off (manual only)', 'ai-eshop-optimizer'), 'hourly' => __('Every hour', 'ai-eshop-optimizer'), 'daily' => __('Daily at', 'ai-eshop-optimizer'), ) as $aieo_dp_value => $aieo_dp_label) { echo ''; } echo '
' . '' . esc_html__('(Europe/Athens)', 'ai-eshop-optimizer') . ''; echo '
'; echo AIEO_DMM_UI::card_form('aieo_dmm_data_prep_save', $this->get_id(), $form_id, (string) ob_get_clean()); echo '

'; echo '' . esc_html__('Next scheduled run:', 'ai-eshop-optimizer') . ' '; if ($next_ts > 0) { echo esc_html(human_time_diff($next_ts) . ' (' . wp_date('Y-m-d H:i', $next_ts) . ')'); } else { echo esc_html__('not scheduled', 'ai-eshop-optimizer'); } echo '

'; echo $close; list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => 'data-prep-scheduler-last-run', 'icon' => 'clock', 'title' => __('Last run', 'ai-eshop-optimizer'), 'description' => __('Check when the tables your storefront reads from were last rebuilt, how long each stage took and whether any stage failed.', 'ai-eshop-optimizer'), )); echo $open; if (empty($last)) { $none = \Rooster\Admin\States::from( array('ran' => false), array('text' => __('No runs yet — click "Run now" or wait for the first scheduled tick.', 'ai-eshop-optimizer')) ); echo $none; } else { $result = \Rooster\Admin\Ui::badge( ($last['ok'] ?? true) ? 'OK' : 'FAILED', ($last['ok'] ?? true) ? 'success' : 'destructive' ); echo '

'; echo '' . esc_html__('When:', 'ai-eshop-optimizer') . ' ' . esc_html((string) ($last['finished_at'] ?? '')); echo ' · ' . esc_html__('Source:', 'ai-eshop-optimizer') . ' ' . esc_html((string) ($last['source'] ?? '')); echo ' · ' . esc_html__('Total:', 'ai-eshop-optimizer') . ' ' . esc_html((string) ($last['total_duration'] ?? '?')) . 's'; echo ' · ' . $result; echo '

'; if (!empty($last['error'])) { $failure = \Rooster\Admin\Ui::notice(esc_html((string) $last['error']), 'destructive', array('inline' => true)); echo $failure; } if (!empty($last['stages']) && is_array($last['stages'])) { $aieo_dp_stage_rows = array(); foreach ($last['stages'] as $aieo_dp_name => $aieo_dp_info) { $aieo_dp_note = ''; if (!empty($aieo_dp_info['error'])) { $aieo_dp_note = (string) $aieo_dp_info['error']; } elseif (!empty($aieo_dp_info['skipped'])) { $aieo_dp_note = (string) $aieo_dp_info['skipped']; } elseif (!empty($aieo_dp_info['notes'])) { $aieo_dp_note = (string) $aieo_dp_info['notes']; } $aieo_dp_stage_rows[] = array( 'stage' => (string) $aieo_dp_name, 'rows' => isset($aieo_dp_info['rows']) ? (int) $aieo_dp_info['rows'] : null, 'duration' => isset($aieo_dp_info['duration']) ? (float) $aieo_dp_info['duration'] : null, 'notes' => $aieo_dp_note, 'failed' => !empty($aieo_dp_info['error']), ); } AIEO_Table::render(array( 'page_id' => $this->get_id(), 'row_key' => 'stage', 'rows' => $aieo_dp_stage_rows, 'caps' => array('search' => true), 'density' => 'compact', 'row_class' => static function ($r) { return !empty($r['failed']) ? 'aieo-t-row--danger' : ''; }, 'columns' => array( array('key' => 'stage', 'label' => __('Stage', 'ai-eshop-optimizer'), 'type' => 'code'), array('key' => 'rows', 'label' => __('Rows', 'ai-eshop-optimizer'), 'type' => 'integer'), array('key' => 'duration', 'label' => __('Duration', 'ai-eshop-optimizer'), 'type' => 'decimal', 'format' => array('precision' => 1), 'suffix' => 's'), array('key' => 'notes', 'label' => __('Notes', 'ai-eshop-optimizer'), 'tone' => 'secondary'), ), )); } } echo $close; $analytics = $this->analytics_module(); if ($analytics && method_exists($analytics, 'render_jobs_card')) { $analytics->render_jobs_card(); } echo ''; rooster_admin_band_close(); rooster_admin_band_open(array('cols' => 2)); $this->render_identity_card(); $this->render_feed_imports_card(); rooster_admin_band_close(); } private static function load_subject_resolver() { if (!class_exists('AIEO_Subject_Resolver') && defined('AIEO_DIR')) { $f = AIEO_DIR . 'includes/class-aieo-subject-resolver.php'; if (is_readable($f)) { require_once $f; } } return class_exists('AIEO_Subject_Resolver'); } public function ajax_identity_backfill() { AIEO_DMM::verify_ajax_request(); if (!self::load_subject_resolver()) { wp_send_json_error(array('message' => __('Identity resolver unavailable.', 'ai-eshop-optimizer'))); } $res = AIEO_Subject_Resolver::backfill_from_orders(AIEO_Subject_Resolver::BACKFILL_BATCH); $upgraded = AIEO_Subject_Resolver::reresolve_known_emails(500); $pending = AIEO_Subject_Resolver::backfill_pending_count(); wp_send_json_success(array( 'scanned' => (int) $res['scanned'], 'resolved' => (int) $res['resolved'], 'skipped' => (int) $res['skipped'], 'upgraded' => (int) $upgraded, 'pending' => $pending, 'more' => ($pending > 0 && ((int) $res['resolved'] > 0 || $upgraded > 0)) ? 1 : 0, 'stats' => self::identity_stats(), )); } private static function identity_stats() { global $wpdb; $out = array('subjects' => 0, 'resolved' => 0, 'pending' => 0, 'people' => 0); if (!self::load_subject_resolver()) { return $out; } $subs = $wpdb->prefix . 'aieo_subjects'; $ci = $wpdb->prefix . 'aieo_customer_intelligence'; if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $subs)) !== $subs) { return $out; } $row = $wpdb->get_row("SELECT COUNT(*) t, SUM(wp_user_id > 0 OR eponymous_id > 0) r FROM `{$subs}`", ARRAY_A); $out['subjects'] = (int) ($row['t'] ?? 0); $out['resolved'] = (int) ($row['r'] ?? 0); $out['pending'] = AIEO_Subject_Resolver::backfill_pending_count(); if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ci)) === $ci) { $out['people'] = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$ci}`"); } return $out; } private function render_feed_imports_card() { if (!class_exists('AIEO_Feed_Source_Store') || !class_exists('AIEO_DMM_Catalog_Importer')) { return; } $defs = AIEO_Feed_Source_Store::all(); list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => 'data-prep-scheduler-feed-imports', 'icon' => 'import', 'title' => __('Feed imports on a clock', 'ai-eshop-optimizer'), 'description' => __('Every saved feed source and when it imports itself. Schedules are set on the source itself; this card is the audit view.', 'ai-eshop-optimizer'), 'col' => 2, )); echo $open; $sources_url = add_query_arg(array('page' => AIEO_DMM::MENU_SLUG, 'dmm_tab' => 'catalog_importer', 'cati_section' => 'sources'), admin_url('admin.php')); echo '

' . esc_html__('Manage the feed sources.', 'ai-eshop-optimizer') . '

'; if (!$defs) { $none = \Rooster\Admin\States::state('first-use', array('title' => __('No feed sources yet.', 'ai-eshop-optimizer'))); echo $none; echo $close; return; } $labels = AIEO_Feed_Source_Store::schedules(); $fi_rows = array(); foreach ($defs as $def) { $cadence = isset($labels[$def['schedule']]) ? (string) $labels[$def['schedule']] : (string) $def['schedule']; $sd = (int) ($def['schedule_day'] ?? -1); if ($sd >= 1 && 'weekly' === $def['schedule']) { global $wp_locale; $cadence .= ' ' . sprintf( __('on %s', 'ai-eshop-optimizer'), $wp_locale->get_weekday($sd % 7) ); } elseif ($sd >= 1 && 'monthly' === $def['schedule']) { $cadence .= ' ' . sprintf( __('on day %s', 'ai-eshop-optimizer'), number_format_i18n($sd) ); } if (($def['schedule_hour'] ?? -1) >= 0 && in_array($def['schedule'], array('daily', 'weekly', 'monthly'), true)) { $cadence .= ' ' . sprintf( __('at %s', 'ai-eshop-optimizer'), sprintf('%02d:00', (int) $def['schedule_hour']) ); } $next = wp_next_scheduled(AIEO_DMM_Catalog_Importer::CRON_HOOK, array((int) $def['id'])); $next_out = $next ? esc_html(human_time_diff(time(), (int) $next) . ' (' . wp_date('Y-m-d H:i', (int) $next) . ')') : '' . esc_html__('not scheduled', 'ai-eshop-optimizer') . ''; $last = (array) $def['last_run']; if (!empty($last['when'])) { $last_out = \Rooster\Admin\Ui::badge(get_date_from_gmt((string) $last['when'], 'Y-m-d H:i'), !empty($last['ok']) ? 'success' : 'destructive'); } else { $last_out = '' . esc_html__('never', 'ai-eshop-optimizer') . ''; } $supplier = '—'; if (!empty($def['supplier_term_id'])) { $term = get_term((int) $def['supplier_term_id'], 'supplier'); if ($term && !is_wp_error($term)) { $supplier = $term->name; } } $fi_rows[] = array( 'id' => (int) $def['id'], 'name' => (string) $def['name'], 'supplier' => (string) $supplier, 'cadence' => (string) $cadence, 'next_html' => $next_out, 'next_sort' => $next ? (int) $next : PHP_INT_MAX, 'last_html' => $last_out, 'last_sort' => !empty($last['when']) ? (string) $last['when'] : '', ); } AIEO_Table::render(array( 'id' => 'aieo-dps-feed-imports', 'page_id' => 'data_prep_scheduler', 'row_key' => 'id', 'rows' => $fi_rows, 'columns' => array( array('key' => 'name', 'label' => __('Source', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'supplier', 'label' => __('Supplier', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'cadence', 'label' => __('Cadence', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'next', 'label' => __('Next run', 'ai-eshop-optimizer'), 'type' => 'control', 'sort_key' => 'next_sort', 'format' => array( 'render' => static function ($r) { return (string) $r['next_html']; }, )), array('key' => 'last', 'label' => __('Last run', 'ai-eshop-optimizer'), 'type' => 'control', 'sort_key' => 'last_sort', 'format' => array( 'render' => static function ($r) { return (string) $r['last_html']; }, )), ), )); echo $close; } private function render_identity_card() { if (!self::load_subject_resolver()) { return; } $s = self::identity_stats(); if ($s['subjects'] < 1 && $s['pending'] < 1) { return; } $pct = $s['subjects'] > 0 ? (100 * $s['resolved'] / $s['subjects']) : 0; list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => 'data-prep-scheduler-identity-resolution', 'icon' => 'users', 'title' => __('Identity resolution', 'ai-eshop-optimizer'), 'description' => __('Ties browsing sessions to the people in your customer database. Sessions are only linked as orders and logins happen, so a store that has just installed the plugin starts with a large backlog of past orders whose visitor is already known. Running the backfill resolves those in one pass; afterwards a daily job keeps up and re-running is a no-op.', 'ai-eshop-optimizer'), 'footer' => ' ' . (class_exists('\Rooster\Admin\States') ? \Rooster\Admin\States::outcome('', '', array('id' => 'aieo-identity-status')) : ''), 'col' => 1, )); echo $open; echo '
'; echo \Rooster\Admin\Ui::stat(__('visitors tracked', 'ai-eshop-optimizer'), number_format_i18n($s['subjects'])); echo \Rooster\Admin\Ui::stat(__('identified', 'ai-eshop-optimizer'), number_format_i18n($s['resolved']) . ' (' . number_format_i18n(round($pct, 1)) . '%)'); echo \Rooster\Admin\Ui::stat(__('awaiting backfill', 'ai-eshop-optimizer'), number_format_i18n($s['pending'])); echo '
'; $aieo_id_why = __('Safe to run at any time and as often as you like — it only looks at sessions that are not yet resolved. Equivalent CLI: wp aieo identity backfill', 'ai-eshop-optimizer'); echo class_exists('\Rooster\Admin\Guidance') ? \Rooster\Admin\Guidance::text($aieo_id_why) : '

' . esc_html($aieo_id_why) . '

'; echo $close; $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION); $ajax = admin_url('admin-ajax.php'); echo ''; } private function analytics_module() { if (!class_exists('AIEO_DMM') || !method_exists('AIEO_DMM', 'instance')) { return null; } $dmm = AIEO_DMM::instance(); if (!$dmm || !method_exists($dmm, 'get_module')) { return null; } return $dmm->get_module('product_orders_analytics'); } }