'product_batch_request_item', 'plural' => 'product_batch_request_items', 'ajax' => false, ) ); list( $row_id, $user_selected ) = $this->resolve_row_id( $product_batch_request_row_id, 'product_batch_request_row_id', 'batch_request_id' ); if ( null !== $row_id ) { $this->product_batch_request_row_id = $row_id; $this->user_selected = $user_selected; } } /** * Let the base modal helper know which batch request row is currently active. * * @return int|null */ public function get_current_batch_request_row_id(): ?int { return $this->product_batch_request_row_id; } /** * Resolve the primary item ID from a row array. * * @param array $item Row item. * @return int */ protected function get_row_item_id( array $item ): int { return (int) ( $item['product_id'] ?? 0 ); } /** * Checkbox column. * * @param array $item Row item. * @return string */ public function column_cb( $item ) { $pid = (int) ( $item['product_id'] ?? 0 ); if ( $pid && $this->is_rejected( $pid ) ) { return ''; } return sprintf( '', esc_attr( $item['product_id'] ) ); } /** * Default column rendering for the table. * * @param array $item Current row item. * @param string $column_name Column key. * @return string */ public function column_default( $item, $column_name ) { $ellipsis = function ( string $val ): string { $short = mb_strimwidth( $val, 0, 140, '…' ); return sprintf( '%s', esc_attr( $val ), esc_html( $short ) ); }; $pid = (int) ( $item['product_id'] ?? 0 ); if ( $pid && $this->is_rejected( $pid ) && ! in_array( $column_name, array( 'status', 'name' ), true ) ) { return ''; } switch ( $column_name ) { case 'status': if ( $pid && $this->is_imported( $pid ) ) { return esc_html( Messages::get( 'details.successfully_imported' ) ); } if ( $pid && $this->is_rejected( $pid ) ) { return sprintf( '%s%s', esc_html( Messages::get( 'details.rejected' ) ), $pid, (int) ( $this->product_batch_request_row_id ?? 0 ), esc_html( Messages::get( 'details.undo_reject' ) ) ); } return esc_html( $item['status'] ); case 'name': $product = wc_get_product( (int) $item['product_id'] ); $label = $product ? $product->get_name() : ( '#' . (int) $item['product_id'] ); $edit_url = $product ? get_edit_post_link( $product->get_id() ) : ''; return $edit_url ? sprintf( '%s', esc_url( $edit_url ), esc_html( $label ) ) : esc_html( $label ); case 'current_meta_title': return $ellipsis( (string) ( $item['current']['_parallax_meta_title'] ?? '' ) ); case 'current_meta_desc': return $ellipsis( (string) ( $item['current']['_parallax_meta_desc'] ?? '' ) ); case 'current_desc': $product = wc_get_product( (int) $item['product_id'] ); return $ellipsis( $product ? (string) $product->get_description() : '' ); case 'opt_name': return $ellipsis( (string) ( $item['optimized']['optimized_name'] ?? '' ) ); case 'opt_meta_title': return $ellipsis( (string) ( $item['optimized']['_parallax_meta_title'] ?? '' ) ); case 'opt_meta_desc': return $ellipsis( (string) ( $item['optimized']['_parallax_meta_desc'] ?? '' ) ); case 'opt_desc': $desc = (string) ( $item['optimized']['description'] ?? $item['optimized']['short_description'] ?? '' ); return $ellipsis( $desc ); case 'actions': return wp_kses_post( $this->actions_html( $item ) ); case 'details': return wp_kses_post( $this->build_view_details_link( $item ) ); default: return isset( $item[ $column_name ] ) ? esc_html( (string) $item[ $column_name ] ) : ''; } } /** * Row actions cell renderer (Approve / Reject / Revert). * * @param array $item Current row item. * @return string */ protected function actions_html( array $item ): string { $pid = (int) ( $item['product_id'] ?? 0 ); if ( ! $pid ) { return ''; } $nonce = wp_create_nonce( 'ai_content_by_parallax_product_action' ); $base_url = $this->get_approval_import_base_url(); // If already imported, show a single Revert action. if ( $this->is_imported( $pid ) ) { return $this->build_revert_action_link( $pid, $this->product_batch_request_row_id ); } // Otherwise, standard Approve / Reject. $has_opt = ! empty( $item['optimized']['_parallax_meta_title'] ) || ! empty( $item['optimized']['_parallax_meta_desc'] ) || ! empty( $item['optimized']['short_description'] ) || ! empty( $item['optimized']['description'] ); if ( ! $has_opt && ( $item['status'] ?? '' ) !== 'Ready' ) { return '' . esc_html( Messages::get( 'details.processing_product' ) ) . ''; } elseif ( ! $has_opt ) { return '' . esc_html( Messages::get( 'details.optimization_failed' ) ) . ''; } $action_links = $this->build_single_item_action_links( 'product', $pid, $this->product_batch_request_row_id, Messages::get( 'details.import_data' ), Messages::get( 'details.reject' ), array( 'approve' => add_query_arg( array( 'product_action' => 'approve', 'product_id' => $pid, 'product_batch_request_row_id' => (int) $this->product_batch_request_row_id, '_wpnonce' => $nonce, ), $base_url ), 'reject' => add_query_arg( array( 'product_action' => 'reject', 'product_id' => $pid, 'product_batch_request_row_id' => (int) $this->product_batch_request_row_id, '_wpnonce' => $nonce, ), $base_url ), ) ); return implode( ' ', $action_links ); } /** * Provide the "Edit Product" link data for a row in the View Details panel. * * @param array $item Current row item. * @return array{url?: string, label?: string} */ protected function get_item_edit_link_data( array $item ): array { $product_id = (int) ( $item['product_id'] ?? 0 ); if ( ! $product_id ) { return array(); } $edit_url = esc_url_raw( (string) get_edit_post_link( $product_id, 'raw' ) ); if ( '' === $edit_url ) { return array(); } return array( 'url' => $edit_url, 'label' => Messages::get( 'details.edit_product' ), ); } /** * Empty state message with optional link to a populated batch request. */ public function no_items() { echo esc_html( Messages::get( 'details.no_products' ) ); if ( $this->suggest_populated_batch_request_id ) { printf( wp_kses_post( Messages::raw( 'details.try_recent' ) ), esc_url( add_query_arg( array( 'product_batch_request_row_id' => $this->suggest_populated_batch_request_id ) ) ) ); } } /** * Render the batch request selector shown above the table. */ protected function render_batch_request_select(): void { $batch_requests = $this->get_batch_requests_by_types( array( 'product', 'products' ), array( 'id', 'batch_request_id', 'status', 'type', 'metadata', 'created_at' ) ); $this->product_batch_request_row_id = $this->choose_default_batch_request_row_id( $this->product_batch_request_row_id, $batch_requests, function ( array $meta ): array { $ids = $this->get_item_ids_from_metadata( $meta ); return $ids ? $ids : $this->extract_product_ids_from_metadata( $meta ); } ); $this->render_batch_request_select_control( $batch_requests, 'wc-parallax-product-batch-request-select', 'product_batch_request_row_id', Messages::get( 'details.batch_request_label' ), Messages::get( 'details.choose_product' ), $this->product_batch_request_row_id, 'ai_content_by_parallax_product_action' ); } /** * Load and prepare the table items for the current view. */ public function prepare_items() { $this->process_actions(); $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array( $columns, $hidden, $sortable ); $per_page = $this->get_items_per_page( 'ai_content_by_parallax_batch_request_product_details_per_page', 20 ); $current_page = $this->get_pagenum(); // If no batch request was explicitly selected and no param is present, pick a sensible default for initial load. if ( ! $this->product_batch_request_row_id ) { $batch_requests = $this->get_batch_requests_by_types( array( 'product', 'products' ), array( 'id', 'metadata' ) ); $this->product_batch_request_row_id = $this->choose_default_batch_request_row_id( $this->product_batch_request_row_id, $batch_requests, function ( array $meta ): array { $ids = $this->get_item_ids_from_metadata( $meta ); return $ids ? $ids : $this->extract_product_ids_from_metadata( $meta ); } ); $this->write_to_logger( 'prepare_items(): defaulted product_batch_request_row_id=' . $this->product_batch_request_row_id ); } // Load batch request row & metadata (IDs from metadata; optimized values from API). $batch_request_result = $this->product_batch_request_row_id ? BatchRequest::get( $this->product_batch_request_row_id ) : null; $this->batch_request_row = null !== $batch_request_result ? $batch_request_result : array(); $metadata = $this->normalize_metadata( $this->batch_request_row['metadata'] ?? array() ); $batch_request_status = strtolower( (string) ( $this->batch_request_row['status'] ?? 'processing' ) ); $remote = (string) ( $this->batch_request_row['batch_request_id'] ?? '' ); $batch_request_type_raw = (string) ( $this->batch_request_row['type'] ?? 'product' ); $batch_request_type = in_array( strtolower( $batch_request_type_raw ), array( 'product', 'products' ), true ) ? 'product' : 'category'; $item_ids = $this->get_item_ids_from_metadata( $metadata ); // batch requested product_ids for the full batch. if ( ! $item_ids && ! empty( $this->batch_request_row['batch_request_id'] ) ) { $fallback_ids = $this->fetch_all_product_ids_from_api( (string) $this->batch_request_row['batch_request_id'], $batch_request_type ); if ( $fallback_ids ) { $item_ids = $fallback_ids; } } if ( $this->product_batch_request_row_id && $item_ids ) { $this->cache_batch_request_item_ids( (int) $this->product_batch_request_row_id, $item_ids ); } $this->write_to_logger( 'prepare_items(): product_batch_request_row_id=' . $this->product_batch_request_row_id . ' remote=' . $remote . ' type=' . $batch_request_type . ' item_ids_count=' . count( $item_ids ) ); if ( $item_ids ) { $sample = array_slice( $item_ids, 0, 5 ); $this->write_to_logger( 'prepare_items(): item_ids sample first 5 = ' . implode( ',', $sample ) ); } // 1) Determine the set of product IDs to show. $product_ids = $item_ids ? $item_ids : $this->extract_product_ids_from_metadata( $metadata ); // Suggest a populated batch request if user selected an empty one. if ( $this->user_selected && ! $product_ids ) { $this->suggest_populated_batch_request_id = $this->find_populated_batch_request_row_id( array( 'product', 'products' ), function ( array $meta ): array { $ids = $this->get_item_ids_from_metadata( $meta ); return $ids ? $ids : $this->extract_product_ids_from_metadata( $meta ); } ); } // 2) Paginate IDs. $total_items = count( $product_ids ); $offset = max( 0, ( $current_page - 1 ) * $per_page ); $page_ids = array_slice( $product_ids, $offset, $per_page ); // Pre-warm post and meta caches for the current page in two queries (one for posts, // one for meta) instead of N+1 individual DB hits inside the loop below. if ( ! empty( $page_ids ) ) { get_posts( array( 'post__in' => array_map( 'intval', $page_ids ), 'post_type' => array( 'product', 'product_variation' ), 'posts_per_page' => count( $page_ids ), 'update_post_meta_cache' => true, 'update_post_term_cache' => false, 'no_found_rows' => true, 'ignore_sticky_posts' => true, ) ); } // 3) Build rows with CURRENT values from WP (cache-hit reads after the bulk load above). $rows = array(); foreach ( $page_ids as $product_id ) { $product = wc_get_product( (int) $product_id ); $name = $product ? $product->get_name() : ''; $rows[ $product_id ] = array( 'product_id' => (int) $product_id, 'name' => $name, 'is_imported' => false, 'current' => array( '_parallax_meta_title' => (string) get_post_meta( $product_id, '_parallax_meta_title', true ), '_parallax_meta_desc' => (string) get_post_meta( $product_id, '_parallax_meta_desc', true ), 'short_description' => $product ? (string) $product->get_short_description() : '', 'description' => $product ? (string) $product->get_description() : '', ), 'optimized' => array( '_parallax_meta_title' => '', '_parallax_meta_desc' => '', 'short_description' => '', 'description' => '', ), 'status' => 'Pending', ); } // 4) Pull optimized values directly from API and apply (map by global index → item_ids). if ( '' !== $remote && in_array( $batch_request_status, BatchRequestStatus::api_fetchable(), true ) && $page_ids ) { $this->hydrate_rows_from_api_paged_json( $remote, $batch_request_type, $rows, $item_ids ); } // 5) Status: ready if optimized exists OR batch request status is completed-ish. foreach ( $rows as $pid => &$r ) { $is_imported = $this->is_imported( (int) $pid ); $has_opt = ! empty( $r['optimized']['_parallax_meta_title'] ) || ! empty( $r['optimized']['_parallax_meta_desc'] ) || ! empty( $r['optimized']['short_description'] ) || ! empty( $r['optimized']['description'] ); if ( $has_opt ) { $r['status'] = 'Ready'; } elseif ( in_array( $batch_request_status, BatchRequestStatus::hydration_eligible(), true ) ) { $r['status'] = 'Ready'; } else { $r['status'] = $batch_request_status ? ucwords( str_replace( '_', ' ', $batch_request_status ) ) : 'Processing'; } // If previously imported, override display status. if ( $is_imported ) { $r['status'] = 'Successfully Imported'; } $r['is_imported'] = $is_imported; } unset( $r ); $this->items = array_values( $rows ); $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => max( 1, (int) ceil( $total_items / $per_page ) ), ) ); } /** * Primary source for matching: batch requested product IDs saved at batch creation. * * @param array $meta Raw metadata payload. * @return int[] */ protected function get_item_ids_from_metadata( array $meta ): array { $keys = array( 'item_ids', 'items', 'ids', 'product_ids', 'products', 'targets' ); foreach ( $keys as $k ) { if ( ! isset( $meta[ $k ] ) ) { continue; } $cand = $meta[ $k ]; if ( 'targets' === $k && is_array( $cand ) && isset( $cand['products'] ) ) { $cand = $cand['products']; } $ids = $this->coerce_ids( $cand ); if ( $ids ) { $this->write_to_logger( 'get_item_ids_from_metadata(): using key ' . $k . ' count=' . count( $ids ) ); return array_values( $ids ); } } return array(); } /** * Fallback extractor to locate product IDs within metadata. * * @param array $meta Raw metadata payload. * @return int[] */ protected function extract_product_ids_from_metadata( array $meta ): array { foreach ( array( 'product_ids', 'products', 'ids', 'targets' ) as $key ) { if ( isset( $meta[ $key ] ) ) { $ids = $this->coerce_ids( $meta[ $key ] ); if ( $ids ) { return $ids; } if ( 'targets' === $key && ! empty( $meta['targets']['products'] ) ) { $ids = $this->coerce_ids( $meta['targets']['products'] ); if ( $ids ) { return $ids; } } } } // Deep scan fallback - validate candidates with a single batch DB query instead of // one wc_get_product() call per candidate (which could be hundreds of queries). $candidates = array(); $this->collect_ints_recursive( $meta, $candidates ); $candidates = array_values( array_unique( array_filter( $candidates, 'is_int' ) ) ); if ( empty( $candidates ) ) { return array(); } // Cap to avoid oversized IN clauses. $candidates = array_slice( $candidates, 0, 1000 ); global $wpdb; $placeholders = implode( ',', array_fill( 0, count( $candidates ), '%d' ) ); $table_name = esc_sql( $wpdb->posts ); // Identifiers are escaped/internally sourced; $placeholders is %d repeats; candidate values are passed to prepare() as positional args. // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = 'SELECT ID FROM `' . $table_name . '` WHERE ID IN (' . $placeholders . ") AND post_type IN ('product','product_variation') AND post_status != 'trash'"; $prepared = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $candidates ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $valid_ids = $wpdb->get_col( $prepared ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter return array_values( array_unique( array_map( 'intval', (array) $valid_ids ) ) ); } /** * Normalize the API payload into the shape expected by the table. * * @param array $payload Raw API payload. * @return array */ protected function normalize_result_payload( array $payload ): array { if ( isset( $payload['result'] ) && is_array( $payload['result'] ) ) { $payload = $payload['result']; } $title = $payload['optimizedMetaTitle'] ?? ''; $desc = $payload['optimizedMetaDescription'] ?? ''; $short = $payload['optimizedShortDescription'] ?? ''; $long = $payload['optimizedDescription'] ?? $payload['optimizedLongDescription'] ?? $payload['optimizedProductDescription'] ?? ''; $name = $payload['optimizedName'] ?? $payload['optimizedProductName'] ?? ''; // Gemini SEO rating fields (may be absent on legacy payloads). $original_rating = $payload['originalRating'] ?? null; $optimized_rating = $payload['optimizedRating'] ?? null; $rating_expl = $payload['ratingImprovementExplanation'] ?? ''; // Common alternative containers some versions may use. $fields = ( isset( $payload['fields'] ) && is_array( $payload['fields'] ) ) ? $payload['fields'] : null; $attributes = ( isset( $payload['attributes'] ) && is_array( $payload['attributes'] ) ) ? $payload['attributes'] : null; $seo = ( isset( $payload['seo'] ) && is_array( $payload['seo'] ) ) ? $payload['seo'] : null; $data = ( isset( $payload['data'] ) && is_array( $payload['data'] ) ) ? $payload['data'] : null; $get = function ( $src, array $keys ) { if ( ! is_array( $src ) ) { return ''; } foreach ( $keys as $k ) { if ( isset( $src[ $k ] ) && '' !== $src[ $k ] ) { return (string) $src[ $k ]; } } return ''; }; // Fallbacks if primary keys are missing/empty. if ( null === $title || '' === $title ) { $title = $this->first_non_empty( $get, array( $payload, $fields, $attributes, $seo, $data ), array( '_parallax_meta_title', 'title', 'meta_title', 'seo_title' ) ); } if ( null === $desc || '' === $desc ) { $desc = $this->first_non_empty( $get, array( $payload, $fields, $attributes, $seo, $data ), array( '_parallax_meta_desc', 'meta_desc', 'meta_description', 'seo_description', 'description_short', ) ); } if ( null === $short || '' === $short ) { $short = $this->first_non_empty( $get, array( $payload, $fields, $attributes, $data ), array( 'short_description', 'excerpt', 'description_short', 'content', 'body', ) ); } if ( null === $long || '' === $long ) { $long = $this->first_non_empty( $get, array( $payload, $fields, $attributes, $data ), array( 'description', 'long_description', 'full_description', 'optimizedDescription', 'optimizedLongDescription', 'body', 'content', ) ); } // Fallbacks for optimized name if primary keys missing. if ( null === $name || '' === $name ) { $name = $this->first_non_empty( $get, array( $payload, $fields, $attributes, $data ), array( 'optimizedName', 'optimizedProductName', 'productName', 'name', ) ); } // Normalize to strings and trim to avoid writing whitespace-only values. $title = trim( (string) $title ); $desc = trim( (string) $desc ); $short = trim( (string) $short ); $long = trim( (string) $long ); if ( '' === $short && '' !== $long ) { $short = $long; } // Debug: quick visibility on what we ended up with. if ( function_exists( 'error_log' ) ) { $this->write_to_logger( 'normalize_result_payload: lens title=' . strlen( $title ) . ' desc=' . strlen( $desc ) . ' short=' . strlen( $short ) . ' long=' . strlen( $long ) ); } return array( '_parallax_meta_title' => $title, '_parallax_meta_desc' => $desc, 'short_description' => $short, 'description' => $long, 'optimized_name' => $name, 'original_rating' => $this->stringify_rating( $original_rating ), 'seo_rating' => $this->stringify_rating( $optimized_rating ), 'rating_improvement_explanation' => is_scalar( $rating_expl ) ? trim( (string) $rating_expl ) : '', ); } /** * Hydrate current-page rows using the batch's batch requested item_ids to map API items → product_id. * * @param string $remote_batch_request_id Remote batch request identifier. * @param string $batch_request_type Batch request type (product/category). * @param array $rows Rows currently being rendered (by reference). * @param array $item_ids Ordered list of product ids for the batch. */ protected function hydrate_rows_from_api_paged_json( string $remote_batch_request_id, string $batch_request_type, array &$rows, array $item_ids ): void { if ( '' === $remote_batch_request_id || ! $rows ) { return; } if ( ! is_array( $item_ids ) || ! $item_ids ) { $this->write_to_logger( 'hydrate_rows(): missing item_ids for batch request ' . $remote_batch_request_id ); return; } for ( $p = 1; $p <= 50; $p++ ) { $raw = MiddlewareRequest::get_batch_request_paged( $remote_batch_request_id, $batch_request_type, $p ); if ( ! is_string( $raw ) || '' === $raw ) { break; } $decoded = json_decode( $raw, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { $this->write_to_logger( 'hydrate_rows(): JSON decode failed p=' . $p . ' err=' . json_last_error_msg() ); break; } $items = is_array( $decoded['items'] ?? null ) ? $decoded['items'] : array(); $page = (int) ( $decoded['page'] ?? $p ); $page_size = (int) ( $decoded['pageSize'] ?? 0 ); $total = (int) ( $decoded['total'] ?? 0 ); $this->write_to_logger( 'hydrate_rows(): page=' . $page . ' pageSize=' . $page_size . ' total=' . $total . ' items=' . count( $items ) ); foreach ( $items as $idx => $it ) { $global = $this->global_index( $page, $page_size, (int) $idx ); $product_id = $item_ids[ $global ] ?? null; if ( ! $product_id ) { $this->write_to_logger( 'hydrate_rows(): no product_id for global_index=' . $global ); continue; } $product_id = (int) $product_id; $this->maybe_store_parallax_id( (array) $it, $product_id, $batch_request_type ); if ( ! isset( $rows[ $product_id ] ) ) { // Not on current paginated view. continue; } $norm = $this->normalize_result_payload( (array) $it ); $title_length = strlen( $norm['_parallax_meta_title'] ?? '' ); $desc_length = strlen( $norm['_parallax_meta_desc'] ?? '' ); $short_desc_length = strlen( $norm['short_description'] ?? '' ); $long_desc_length = strlen( $norm['description'] ?? '' ); $this->write_to_logger( 'hydrate_rows(): map global=' . $global . ' -> product_id=' . $product_id . ' lens T/D/S/L=' . $title_length . '/' . $desc_length . '/' . $short_desc_length . '/' . $long_desc_length ); if ( $title_length || $desc_length || $short_desc_length || $long_desc_length ) { $rows[ $product_id ]['optimized'] = $norm; $rows[ $product_id ]['status'] = 'Ready'; // Mirror the original (pre-optimization) SEO rating into the current side so // the detail popup can render it in the Current column alongside the value. if ( '' !== ( $norm['original_rating'] ?? '' ) ) { $rows[ $product_id ]['current']['seo_rating'] = (string) $norm['original_rating']; } } } if ( $page_size > 0 && $page * $page_size >= $total ) { break; } } } /** * Fetch all pages and build a map product_id => normalized optimized payload, * using the batch's batch requested $item_ids to map global item position -> product_id. * * @param string $remote_batch_request_id Remote batch request identifier. * @param string $batch_request_type Batch request type (product/category). * @param array $item_ids Ordered list of product ids for the batch. * @return array */ protected function fetch_optimized_by_item_position( string $remote_batch_request_id, string $batch_request_type, array $item_ids ): array { $out = array(); if ( '' === $remote_batch_request_id || ! $item_ids ) { return $out; } for ( $p = 1; $p <= 50; $p++ ) { $raw = MiddlewareRequest::get_batch_request_paged( $remote_batch_request_id, $batch_request_type, $p ); if ( ! is_string( $raw ) || '' === $raw ) { break; } $decoded = json_decode( $raw, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { $this->write_to_logger( 'fetch_optimized_by_item_position(): JSON decode failed p=' . $p ); break; } $items = is_array( $decoded['items'] ?? null ) ? $decoded['items'] : array(); $page = (int) ( $decoded['page'] ?? $p ); $page_size = (int) ( $decoded['pageSize'] ?? 0 ); $total = (int) ( $decoded['total'] ?? 0 ); $this->write_to_logger( 'fetch_optimized_by_item_position(): page=' . $page . ' pageSize=' . $page_size . ' total=' . $total . ' items=' . count( $items ) ); foreach ( $items as $idx => $it ) { $global = $this->global_index( $page, $page_size, (int) $idx ); if ( ! array_key_exists( $global, $item_ids ) ) { $this->write_to_logger( 'fetch_optimized_by_item_position(): no product id for global index=' . $global ); continue; } $product_id = (int) $item_ids[ $global ]; $norm = $this->normalize_result_payload( (array) $it ); if ( $norm['_parallax_meta_title'] || $norm['_parallax_meta_desc'] || $norm['short_description'] || $norm['description'] ) { $out[ $product_id ] = $norm; } else { $this->write_to_logger( 'fetch_optimized_by_item_position(): empty normalized payload for product_id=' . $product_id . ' global=' . $global ); } } if ( $page_size > 0 && $page * $page_size >= $total ) { break; } } return $out; } /** * Delete the whole batch request row (and known related items) safely. * * @param int|null $product_batch_request_row_id Row id to delete. */ protected function delete_whole_batch_request( ?int $product_batch_request_row_id ): void { if ( ! $product_batch_request_row_id ) { return; } try { if ( method_exists( '\AIContentByParallax\Models\BatchRequest', 'delete_with_items' ) ) { BatchRequest::delete_with_items( $product_batch_request_row_id ); } elseif ( method_exists( '\AIContentByParallax\Models\BatchRequest', 'delete' ) ) { BatchRequest::delete( $product_batch_request_row_id ); } $this->write_to_logger( 'delete_whole_batch_request(): deleted product_batch_request_row_id=' . $product_batch_request_row_id ); } catch ( \Throwable $e ) { $this->write_to_logger( 'delete_whole_batch_request(): failed to delete via model: ' . $e->getMessage() ); } } /** * Build a name/slug resolver (kept for completeness, no longer used in main flow). * * @param int[] $product_ids Product ids to index. * @return array */ protected function build_resolver_for_products( array $product_ids ): array { $resolver = array(); foreach ( $product_ids as $pid ) { $product = wc_get_product( (int) $pid ); if ( $product ) { $name = $product->get_name(); $slug = $product->get_slug(); if ( ! empty( $name ) ) { $resolver[ 'n:' . $this->norm_key( (string) $name ) ] = (int) $pid; } if ( ! empty( $slug ) ) { $resolver[ 's:' . $this->norm_key( (string) $slug ) ] = (int) $pid; } } } return $resolver; } /** * Fetch the optimized payload for ONE product by using its position in the batch requested item_ids array. * Returns normalized keys: _parallax_meta_title, _parallax_meta_desc, short_description - or [] if not found. * * @param string $remote_batch_request_id Remote batch request identifier. * @param string $batch_request_type Batch request type (product/category). * @param array $item_ids Ordered list of product ids for the batch. * @param int $product_id Product id being fetched. * @param array $position_lookup Optional precomputed position map. * @return array */ protected function fetch_single_optimized_by_position( string $remote_batch_request_id, string $batch_request_type, array $item_ids, int $product_id, array $position_lookup = array() ): array { $item_ids = array_values( $item_ids ); if ( '' === $remote_batch_request_id || ! $item_ids ) { $this->write_to_logger( 'single_fetch: missing remote or empty item_ids' ); return array(); } if ( isset( $position_lookup[ $product_id ] ) ) { $pos = $position_lookup[ $product_id ]; } else { $pos = array_search( $product_id, $item_ids, true ); } if ( false === $pos ) { $this->write_to_logger( 'single_fetch: product_id ' . $product_id . ' not found in item_ids (' . count( $item_ids ) . ' ids)' ); return array(); } $raw1 = MiddlewareRequest::get_batch_request_paged( $remote_batch_request_id, $batch_request_type, 1 ); if ( ! is_string( $raw1 ) || '' === $raw1 ) { $this->write_to_logger( 'single_fetch: empty response on p1 for ' . $remote_batch_request_id ); return array(); } $d1 = json_decode( $raw1, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $d1 ) ) { $this->write_to_logger( 'single_fetch: JSON decode fail on p1: ' . json_last_error_msg() ); return array(); } $page_size = (int) ( $d1['pageSize'] ?? 0 ); if ( $page_size <= 0 ) { $page_size = max( 1, (int) ( is_array( $d1['items'] ?? null ) ? count( $d1['items'] ) : 10 ) ); } $total = (int) ( $d1['total'] ?? 0 ); $page = (int) floor( $pos / $page_size ) + 1; $local = (int) ( $pos % $page_size ); $this->write_to_logger( sprintf( '[wc-parallax] single_fetch: pid=%d pos=%d page=%d local=%d pageSize=%d total=%d', $product_id, $pos, $page, $local, $page_size, $total ) ); $raw = MiddlewareRequest::get_batch_request_paged( $remote_batch_request_id, $batch_request_type, $page ); if ( ! is_string( $raw ) || '' === $raw ) { $this->write_to_logger( 'single_fetch: empty response on page=' . $page ); return array(); } $decoded = json_decode( $raw, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { $this->write_to_logger( 'single_fetch: JSON decode fail page=' . $page . ' err=' . json_last_error_msg() ); return array(); } $items = is_array( $decoded['items'] ?? null ) ? $decoded['items'] : array(); $items_count = count( $items ); $page_log_p = (int) ( $decoded['page'] ?? $page ); $page_log_s = (int) ( $decoded['pageSize'] ?? $page_size ); $this->write_to_logger( 'single_fetch: fetched page=' . $page_log_p . ' pageSize=' . $page_log_s . ' items=' . $items_count ); if ( ! array_key_exists( $local, $items ) ) { $this->write_to_logger( 'single_fetch: items missing local idx ' . $local . ' (items=' . $items_count . ')' ); return array(); } $raw_item = (array) $items[ $local ]; // Snapshot of raw optimized fields (first 80 chars). $dbg_title = isset( $raw_item['optimizedMetaTitle'] ) ? mb_substr( (string) $raw_item['optimizedMetaTitle'], 0, 80 ) : ''; $dbg_desc = isset( $raw_item['optimizedMetaDescription'] ) ? mb_substr( (string) $raw_item['optimizedMetaDescription'], 0, 80 ) : ''; $dbg_short_desc = isset( $raw_item['optimizedShortDescription'] ) ? mb_substr( (string) $raw_item['optimizedShortDescription'], 0, 80 ) : ''; $dbg_long_desc = isset( $raw_item['optimizedDescription'] ) ? mb_substr( (string) $raw_item['optimizedDescription'], 0, 80 ) : ''; $this->write_to_logger( 'single_fetch: rawItem[' . $local . '] title="' . $dbg_title . '" desc="' . $dbg_desc . '" short="' . $dbg_short_desc . '" long="' . $dbg_long_desc . '"' ); $norm = $this->normalize_result_payload( $raw_item ); $title_length = strlen( $norm['_parallax_meta_title'] ?? '' ); $desc_length = strlen( $norm['_parallax_meta_desc'] ?? '' ); $short_desc_length = strlen( $norm['short_description'] ?? '' ); $long_desc_length = strlen( $norm['description'] ?? '' ); $this->write_to_logger( 'single_fetch: norm lens title=' . $title_length . ' desc=' . $desc_length . ' short=' . $short_desc_length . ' long=' . $long_desc_length ); return $norm; } /** * Fetch optimized payloads for a set of product IDs with minimal remote requests. * * @param string $remote_batch_request_id Remote batch request identifier. * @param string $batch_request_type Batch request type (product/category). * @param int[] $item_ids Ordered list of product ids for the batch. * @param int[] $target_product_ids Product ids to fetch. * @param int[] $position_lookup Precomputed position lookup map. * @return array Map product_id => normalized optimized payload. */ protected function fetch_bulk_optimized_by_products( string $remote_batch_request_id, string $batch_request_type, array $item_ids, array $target_product_ids, array $position_lookup ): array { return $this->fetch_bulk_optimized_by_targets( $remote_batch_request_id, $batch_request_type, $item_ids, $target_product_ids, $position_lookup ); } /** * Determine whether the product has already been imported. * * @param int $product_id Product id to check. * @return bool */ /** * Mark a product as imported and store a backup payload. * * @param int $product_id Product id to mark. * @param array $backup Backup payload of pre-import values. */ protected function mark_imported( int $product_id, array $backup ): void { // store a compact JSON backup of the pre-import state. update_post_meta( $product_id, '_parallax_prev_payload', wp_json_encode( $backup ) ); $this->set_imported_status( $product_id ); } /** * Retrieve the stored backup payload for a product. * * @param int $product_id Product id to read backup for. * @return array */ protected function get_backup_payload( int $product_id ): array { $raw = get_post_meta( $product_id, '_parallax_prev_payload', true ); if ( is_array( $raw ) ) { return $raw; } if ( is_string( $raw ) && '' !== $raw ) { $decoded = json_decode( $raw, true ); if ( is_array( $decoded ) ) { return $decoded; } } return array(); } /** * Restore previously backed-up values. Returns true on change/write. * * @param int $product_id Product id to restore. * @return bool */ protected function revert_import( int $product_id ): bool { $backup = $this->get_backup_payload( $product_id ); if ( ! $backup ) { $this->write_to_logger( 'revert_import: no backup payload for pid=' . $product_id . ' - attempting snapshot restore' ); } $restored = OriginalSnapshot::restore_product( $product_id, null, $backup ); if ( ! $restored ) { $this->write_to_logger( 'revert_import: restore_product did not modify pid=' . $product_id ); } $this->clear_import_markers( $product_id ); return $restored; } /** * Fetch post meta for products. * * @param int $item_id Item id. * @param string $key Meta key. * @return mixed */ protected function get_item_meta( int $item_id, string $key ) { return get_post_meta( $item_id, $key, true ); } /** * Update post meta for products. * * @param int $item_id Item id. * @param string $key Meta key. * @param mixed $value Meta value. * @return bool */ protected function update_item_meta( int $item_id, string $key, $value ): bool { return (bool) update_post_meta( $item_id, $key, $value ); } /** * Delete post meta for products. * * @param int $item_id Item id. * @param string $key Meta key. * @return bool */ protected function delete_item_meta( int $item_id, string $key ): bool { return (bool) delete_post_meta( $item_id, $key ); } /** * Return current WP field values for a single product. * * @param int $item_id Product ID. * @return array */ protected function build_current_values( int $item_id ): array { $product = wc_get_product( $item_id ); return array( '_parallax_meta_title' => (string) get_post_meta( $item_id, '_parallax_meta_title', true ), '_parallax_meta_desc' => (string) get_post_meta( $item_id, '_parallax_meta_desc', true ), 'short_description' => $product ? (string) $product->get_short_description() : '', 'description' => $product ? (string) $product->get_description() : '', ); } /** * Return the product display name. * * @param int $item_id Product ID. * @return string */ protected function get_item_display_name( int $item_id ): string { $product = wc_get_product( $item_id ); return $product ? $product->get_name() : ( '#' . $item_id ); } /** * Ensure pagination preserves the currently selected product batch request. * * @return array */ protected function get_context_query_args(): array { $args = parent::get_context_query_args(); if ( $this->product_batch_request_row_id ) { $args['product_batch_request_row_id'] = (int) $this->product_batch_request_row_id; } return $args; } /** * Capture a fresh original snapshot for all products about to be imported. * Runs once per import execution (bulk or single) even if multiple hooks fire. * * @param int[] $product_ids Product IDs slated for import. */ protected function ensure_pre_import_snapshots( array $product_ids ): void { static $snapshot_taken = false; if ( $snapshot_taken ) { return; } $snapshot_taken = true; foreach ( array_unique( array_map( 'absint', $product_ids ) ) as $product_id ) { if ( $product_id <= 0 ) { continue; } // Force a new snapshot right before import to ensure current data is preserved. OriginalSnapshot::save_original_if_missing_product( $product_id, true ); } } /** * Handle approve, reject, and revert actions for the table rows. */ public function process_actions(): void { // Log incoming request params relevant to actions. $rq = array( 'method' => $this->get_request_method(), 'get' => $this->get_params_snapshot( array( 'product_action', 'product_id', 'product_batch_request_row_id', '_wpnonce', 'action' ), 'get' ), 'post' => $this->get_params_snapshot( array( 'action', '_wpnonce', 'product_batch_request_item_ids' ), 'post' ), ); $this->write_to_logger( 'process_actions: request snapshot ' . wp_json_encode( $rq ) ); // Accept nonce from either GET (row action link) or POST (bulk). $nonce = $this->get_request_param( '_wpnonce' ); $nonce_ok = false; if ( $nonce ) { $nonce_ok = wp_verify_nonce( $nonce, 'ai_content_by_parallax_product_action' ) || wp_verify_nonce( $nonce, 'bulk-' . $this->_args['plural'] ); } if ( ! $nonce_ok ) { $this->write_to_logger( 'process_actions: nonce missing/invalid - aborting' ); return; } // Prefer our custom GET param for row actions; fallback to list-table action. $action = $this->get_request_param( 'product_action' ) ?? $this->current_action(); $this->write_to_logger( 'process_actions: entry, action=' . $action ); if ( ! $action ) { return; } $product_batch_request_row_id = $this->get_request_int_param( 'product_batch_request_row_id' ) ?? $this->product_batch_request_row_id; $batch_request_result = $product_batch_request_row_id ? BatchRequest::get( $product_batch_request_row_id ) : null; $batch_request = null !== $batch_request_result ? $batch_request_result : array(); $remote = (string) ( $batch_request['batch_request_id'] ?? '' ); $otype = (string) ( $batch_request['type'] ?? 'product' ); $otype = in_array( strtolower( $otype ), array( 'product', 'products' ), true ) ? 'product' : 'category'; $metadata = $this->normalize_metadata( $batch_request['metadata'] ?? array() ); $item_ids = $product_batch_request_row_id ? $this->get_cached_batch_request_item_ids( $product_batch_request_row_id ) : array(); if ( ! $item_ids ) { $item_ids = $this->get_item_ids_from_metadata( $metadata ); if ( $product_batch_request_row_id && $item_ids ) { $this->cache_batch_request_item_ids( $product_batch_request_row_id, $item_ids ); } } $position_lookup = array(); foreach ( $item_ids as $idx => $id ) { $pid = (int) $id; if ( $pid > 0 && ! isset( $position_lookup[ $pid ] ) ) { $position_lookup[ $pid ] = (int) $idx; } } $this->write_to_logger( 'process_actions: product_batch_request_row_id=' . $product_batch_request_row_id . ' remote=' . $remote . ' type=' . $otype . ' item_ids_count=' . count( $item_ids ) ); // Collect product IDs from request (row or bulk). $product_ids = array(); if ( 'bulk_approve' === $action || 'bulk_reject' === $action ) { $product_ids = $this->get_request_int_array_param( 'product_batch_request_item_ids' ); } elseif ( in_array( $action, array( 'approve', 'reject', 'revert', 'undo_reject' ), true ) ) { $selected_id = $this->get_request_int_param( 'product_id' ); $product_ids = $selected_id ? array( $selected_id ) : array(); } $product_ids = array_values( array_filter( $product_ids ) ); $this->write_to_logger( 'process_actions: product_ids=' . wp_json_encode( $product_ids ) ); // BULK REJECT: delete the whole batch request and bounce. if ( 'bulk_reject' === $action ) { $this->write_to_logger( 'process_actions: BULK REJECT triggered' ); $this->delete_whole_batch_request( $product_batch_request_row_id ); if ( $this->is_ajax_context() ) { return; } $this->redirect_back( array( 'product_action', 'product_id', '_wpnonce', 'product_batch_request_row_id' ) ); } // SINGLE REJECT: mark item rejected, notify API only; batch and row are preserved. if ( 'reject' === $action ) { $this->write_to_logger( 'process_actions: SINGLE REJECT - notify only, batch preserved' ); foreach ( $product_ids as $pid ) { $this->set_rejected_status( (int) $pid ); } if ( $this->is_ajax_context() ) { return; } $this->redirect_back( array( 'product_action', 'product_id', '_wpnonce', 'product_batch_request_row_id' ) ); } // UNDO REJECT: clear the rejected flag; item returns to its ready/unimported state. if ( 'undo_reject' === $action && $product_ids ) { foreach ( $product_ids as $pid ) { $this->clear_rejected_status( (int) $pid ); } if ( $this->is_ajax_context() ) { return; } $add = $product_batch_request_row_id ? array( 'product_batch_request_row_id' => $product_batch_request_row_id ) : array(); $this->redirect_back( array( 'product_action', 'product_id', '_wpnonce' ), $add ); } // REVERT: restore backup per selected product. if ( 'revert' === $action && $product_ids ) { foreach ( $product_ids as $pid ) { $pid = (int) $pid; $ok = $this->revert_import( $pid ); $this->write_to_logger( 'process_actions: REVERT pid=' . $pid . ' ok=' . ( $ok ? 'yes' : 'no' ) ); } if ( $this->is_ajax_context() ) { return; } $add = $product_batch_request_row_id ? array( 'product_batch_request_row_id' => $product_batch_request_row_id ) : array(); $this->redirect_back( array( 'product_action', 'product_id', '_wpnonce' ), $add ); } // APPROVE: write optimized values and mark imported (with backup), per product. if ( ( 'approve' === $action || 'bulk_approve' === $action ) && $remote && $product_ids ) { // process_actions is the earliest common entry point for all imports (AJAX, CLI, single row, bulk), // so take a one-time snapshot here before any product data can be mutated. $this->ensure_pre_import_snapshots( $product_ids ); $this->write_to_logger( 'process_actions: APPROVE start (remote=' . $remote . ')' ); $optimized_cache = array(); if ( 'bulk_approve' === $action ) { $optimized_cache = $this->fetch_bulk_optimized_by_products( $remote, $otype, $item_ids, $product_ids, $position_lookup ); $this->write_to_logger( 'approve: prefetched optimized payloads count=' . count( $optimized_cache ) ); } foreach ( $product_ids as $pid ) { $pid = (int) $pid; if ( $this->is_rejected( $pid ) ) { $this->write_to_logger( 'approve: skipping rejected pid=' . $pid ); continue; } // BEFORE snapshot for backup. $product = wc_get_product( $pid ); $before_name = $product ? (string) $product->get_name() : ''; $before_title = (string) get_post_meta( $pid, '_parallax_meta_title', true ); $before_desc = (string) get_post_meta( $pid, '_parallax_meta_desc', true ); $before_yoast_title = (string) get_post_meta( $pid, '_yoast_wpseo_title', true ); $before_yoast_desc = (string) get_post_meta( $pid, '_yoast_wpseo_metadesc', true ); $before_short = $product ? (string) $product->get_short_description() : ''; $before_long = $product ? (string) $product->get_description() : ''; $this->write_to_logger( sprintf( '[wc-parallax] approve: BEFORE pid=%d len(name)=%d len(title)=%d len(desc)=%d len(short)=%d len(long)=%d', $pid, strlen( $before_name ), strlen( $before_title ), strlen( $before_desc ), strlen( $before_short ), strlen( $before_long ) ) ); // Deterministic single fetch by position. if ( isset( $optimized_cache[ $pid ] ) ) { $opt = $optimized_cache[ $pid ]; } else { $opt = $this->fetch_single_optimized_by_position( $remote, $otype, $item_ids, $pid, $position_lookup ); } $title = isset( $opt['_parallax_meta_title'] ) ? trim( (string) $opt['_parallax_meta_title'] ) : ''; $desc = isset( $opt['_parallax_meta_desc'] ) ? trim( (string) $opt['_parallax_meta_desc'] ) : ''; $short = isset( $opt['short_description'] ) ? trim( (string) $opt['short_description'] ) : ''; $long = isset( $opt['description'] ) ? trim( (string) $opt['description'] ) : ''; $oname = isset( $opt['optimized_name'] ) ? trim( (string) $opt['optimized_name'] ) : ''; $this->write_to_logger( 'approve: FETCH pid=' . $pid . ' lens title=' . strlen( $title ) . ' desc=' . strlen( $desc ) . ' short=' . strlen( $short ) . ' long=' . strlen( $long ) . ' name=' . strlen( $oname ) ); $wrote = false; $ret_title = null; $ret_desc = null; if ( '' !== $title ) { $ret_title = update_post_meta( $pid, '_parallax_meta_title', wp_kses_post( Sanitize::truncate_meta( $title, 'meta_title' ) ) ); $wrote = $wrote || (bool) $ret_title; $this->write_to_logger( 'approve: update_post_meta(title) pid=' . $pid . ' return=' . $ret_title ); } if ( '' !== $desc ) { $ret_desc = update_post_meta( $pid, '_parallax_meta_desc', wp_kses_post( $desc ) ); $wrote = $wrote || (bool) $ret_desc; $this->write_to_logger( 'approve: update_post_meta(desc) pid=' . $pid . ' return=' . $ret_desc ); } // rename product if provided. if ( '' !== $oname ) { $res_name = wp_update_post( array( 'ID' => $pid, 'post_title' => wp_kses_post( $oname ), ), true ); if ( is_wp_error( $res_name ) ) { $this->write_to_logger( 'approve: wp_update_post(name) ERROR pid=' . $pid . ' : ' . $res_name->get_error_message() ); } else { $wrote = true; $this->write_to_logger( 'approve: wp_update_post(name) pid=' . $pid . ' ok new_name="' . $oname . '"' ); } } if ( '' !== $short ) { // Convert block-level HTML to newlines then strip tags. // Builders read post_excerpt as plain text, so HTML // renders as literal tags on the frontend. $res = wp_update_post( array( 'ID' => $pid, 'post_excerpt' => Sanitize::html_to_plain_text( $short ), ), true ); if ( is_wp_error( $res ) ) { $this->write_to_logger( 'approve: wp_update_post(excerpt) ERROR pid=' . $pid . ' : ' . $res->get_error_message() ); } else { $wrote = true; $this->write_to_logger( 'approve: wp_update_post(excerpt) pid=' . $pid . ' ok' ); } } if ( '' !== $long ) { $res_long = wp_update_post( array( 'ID' => $pid, 'post_content' => wp_kses_post( $long ), ), true ); if ( is_wp_error( $res_long ) ) { $this->write_to_logger( 'approve: wp_update_post(content) ERROR pid=' . $pid . ' : ' . $res_long->get_error_message() ); } else { $wrote = true; $this->write_to_logger( 'approve: wp_update_post(content) pid=' . $pid . ' ok' ); } } // Clear caches aggressively (post_meta + posts). if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( $pid, 'post_meta' ); wp_cache_delete( $pid, 'posts' ); } clean_post_cache( $pid ); // AFTER values (lengths). $product2 = wc_get_product( $pid ); $after_name = $product2 ? (string) $product2->get_name() : ''; $after_title = (string) get_post_meta( $pid, '_parallax_meta_title', true ); $after_desc = (string) get_post_meta( $pid, '_parallax_meta_desc', true ); $after_short = $product2 ? (string) $product2->get_short_description() : ''; $after_long = $product2 ? (string) $product2->get_description() : ''; $this->write_to_logger( sprintf( '[wc-parallax] approve: AFTER pid=%d wrote=%s len(name)=%d len(title)=%d len(desc)=%d len(short)=%d len(long)=%d', $pid, $wrote ? 'yes' : 'no', strlen( $after_name ), strlen( $after_title ), strlen( $after_desc ), strlen( $after_short ), strlen( $after_long ) ) ); // If we actually changed something, mark imported and store backup. if ( $wrote ) { $backup = array( 'name' => $before_name, '_parallax_meta_title' => $before_title, '_parallax_meta_desc' => $before_desc, 'short_description' => $before_short, 'description' => $before_long, 'yoast_title' => $before_yoast_title, 'yoast_desc' => $before_yoast_desc, ); $this->mark_imported( $pid, $backup ); } } } // Redirect back, keep the selected batch request in view. if ( $this->is_ajax_context() ) { // Skip redirects when called via admin-ajax (e.g., bulk import). return; } $add = $product_batch_request_row_id ? array( 'product_batch_request_row_id' => $product_batch_request_row_id ) : array(); $this->redirect_back( array( 'product_action', 'product_id', '_wpnonce' ), $add ); } }