/** * Reconciliation: Scan all categories/pages, queue missing products for creation. */ public static function reconcile_missing_products() { if ( ! current_user_can( 'manage_woocommerce' ) ) { return new WP_Error( 'unauthorized', 'Unauthorized' ); } $settings = self::settings(); $all_cats = get_transient( 'imlss_all_categories' ); if ( ! $all_cats || !is_array($all_cats) || count($all_cats) === 0 ) { // Fallback: use currently selected categories from scheduler state $sched_state = get_option( self::SCHED_STATE_KEY, [] ); $all_cats = $sched_state['cats'] ?? []; } $missing_queue = []; foreach ( $all_cats as $cat ) { $cat_path = trim( (string) ( $cat['path'] ?? ( $cat['id'] ?? '' ) ), '/' ); $category_url_base = 'https://shop.imlss.com/item_view/shop/' . $cat_path . '/all?_l=120&_k=true&_of=__store&_ipp=50&_ist=2'; // Detect last page $settings['catalog_url'] = add_query_arg( 'item_page', 1, $category_url_base ); $settings['catalog_start_page'] = 1; $settings['catalog_page_param'] = 'item_page'; $settings['import_batch_size'] = 50; $settings['enrich_on_import'] = 0; $scrape_first = self::do_login_and_scrape( $settings, 1 ); $last_page = 1; if ( ! empty( $scrape_first['summary']['ok'] ) && ! empty( $scrape_first['summary']['pages_fetched'][0]['rows'] ) ) { if ( preg_match( '/([0-9,]+)\s+Items/i', $scrape_first['summary']['message'] ?? '', $m ) ) { $total_products = (int) str_replace( ',', '', $m[1] ); $last_page = max( 1, ceil( $total_products / 50 ) ); } } for ( $page = 1; $page <= $last_page; $page++ ) { $settings['catalog_url'] = add_query_arg( 'item_page', $page, $category_url_base ); $settings['catalog_start_page'] = $page; $scrape = self::do_login_and_scrape( $settings, 50 ); if ( empty( $scrape['summary']['ok'] ) ) continue; foreach ( $scrape['samples'] as $row ) { $sku = trim( (string) ( $row['sku'] ?? '' ) ); if ( $sku === '' ) continue; $existing_id = (int) wc_get_product_id_by_sku( $sku ); if ( $existing_id <= 0 ) { $row['url_base'] = $settings['catalog_url']; $missing_queue[] = $row; } } } } set_transient( 'imlss_reconcile_queue', $missing_queue, 12 * HOUR_IN_SECONDS ); return [ 'count' => count( $missing_queue ) ]; } // AJAX handler for reconciliation public static function ajax_reconcile_missing_products() { check_ajax_referer( 'imlss_reconcile' ); $result = self::reconcile_missing_products(); if ( is_wp_error( $result ) ) { wp_send_json_error( $result->get_error_message() ); } else { wp_send_json_success( $result ); } } add_action( 'wp_ajax_imlss_reconcile_missing_products', [ __CLASS__, 'ajax_reconcile_missing_products' ] );
Scan all supplier categories/pages and build a queue of products not yet created in WooCommerce.