generator = $generator ?? new ContentGenerator(); } public function register_routes(): void { register_rest_route( self::REST_NAMESPACE . '/description-generator', '/history', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_history' ), 'permission_callback' => array( $this, 'check_permissions' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/apply', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'apply_content' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/bulk-apply', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_apply' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/approve-description', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'approve_description' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/approve-descriptions', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'approve_descriptions' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'items' => array( 'type' => 'array', 'required' => true, 'minItems' => 1, 'maxItems' => self::MAX_APPROVE_PRODUCTS, 'items' => array( 'type' => 'object', 'properties' => array( 'product_id' => array( 'type' => 'integer' ), 'cells' => array( 'type' => 'array', 'maxItems' => 3, 'items' => array( 'type' => 'object', 'properties' => array( 'description_type' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ), ), ), ), ), ), ), 'options' => array( 'type' => 'object' ), ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/reject-description', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'reject_description' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/bulk-approve', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_approve' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/bulk-reject', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_reject' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'results' => array( 'type' => 'array', 'items' => array( 'type' => 'object' ), 'maxItems' => self::MAX_BULK_REJECT_ITEMS, ), ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/delete-history-item', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'delete_history_item' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/bulk-delete', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_delete' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/delete-all-history', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'delete_all_history' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/cancel', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'cancel_generation' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'history_id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), ), ) ); } public function get_history(): WP_REST_Response { return $this->retired_route_response(); } public function apply_content( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function bulk_apply( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function approve_description( WP_REST_Request $request ): WP_REST_Response { $json_params = $request->get_json_params(); $product_id = absint( $json_params['product_id'] ?? $request->get_param( 'product_id' ) ?? 0 ); $type = sanitize_text_field( $json_params['description_type'] ?? $request->get_param( 'description_type' ) ?? '' ); $content = wp_kses_post( $json_params['description'] ?? $request->get_param( 'description' ) ?? '' ); $raw_options = $json_params['options'] ?? $request->get_param( 'options' ) ?? array(); $options = is_array( $raw_options ) ? $this->sanitize_generation_options( $raw_options ) : array(); if ( ! $product_id ) { return new WP_REST_Response( array( 'success' => false, 'message' => $this->missing_product_message() ), 400 ); } $refusal = $this->cell_refusal( $type, $content ); if ( null !== $refusal ) { return new WP_REST_Response( array( 'success' => false, 'message' => $refusal ), 400 ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return new WP_REST_Response( array( 'success' => false, 'message' => $this->forbidden_product_message() ), 403 ); } $options['executionPath'] = $this->approve_execution_path(); $blueprint = $this->approve_blueprint( $json_params['blueprint'] ?? $request->get_param( 'blueprint' ) ?? null, $options['executionPath'] ); $outcomes = $this->apply_product_cells( $product_id, array( $type => array( 'content' => $content, 'blueprint' => $blueprint, ), ), $options ); $outcome = $outcomes[ $type ]; if ( 'applied' === $outcome['status'] ) { $this->record_usage_event( 'advanced_desc', 'approved', 1, array( 'product_id' => $product_id ) ); return new WP_REST_Response( array( 'success' => true, 'message' => __( 'Description approved and applied', 'ai-product-tools' ) ), 200 ); } if ( 'kept' === $outcome['status'] ) { return new WP_REST_Response( array( 'success' => true, 'skipped' => true, 'kept' => true, 'message' => $outcome['message'], ), 200 ); } return new WP_REST_Response( array( 'success' => false, 'message' => $outcome['message'] ), 'tags' === $type ? 422 : 500 ); } /** * Approves the "Show me first" results of up to MAX_APPROVE_PRODUCTS * products in one request: each product's texts in one write and its * tags in another, with the same checks and answers per cell as * approve-description. Every cell gets a result: applied, kept (Fill * empty only left a field alone), failed with a reason, or not_attempted * when the time budget ran out before its product, for the page to send * again. * * @param WP_REST_Request $request Request with `items` [{product_id, cells: [{description_type, description, blueprint?}]}] and `options`. * @return WP_REST_Response */ public function approve_descriptions( WP_REST_Request $request ): WP_REST_Response { $items = $request->get_param( 'items' ); $raw_options = $request->get_param( 'options' ); $options = is_array( $raw_options ) ? $this->sanitize_generation_options( $raw_options ) : array(); if ( ! is_array( $items ) || empty( $items ) ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'No items to approve', 'ai-product-tools' ) ), 400 ); } $options['executionPath'] = $this->approve_execution_path(); $started = microtime( true ); $results = array(); $applied_count = 0; $first_applied_product = 0; $out_of_time = false; foreach ( array_values( $items ) as $position => $item ) { $item = is_array( $item ) ? $item : array(); $product_id = absint( $item['product_id'] ?? 0 ); $raw_cells = is_array( $item['cells'] ?? null ) ? $item['cells'] : array(); if ( ! $out_of_time && $position > 0 && $this->seconds_since( $started ) >= self::APPROVE_TIME_BUDGET_SECONDS ) { $out_of_time = true; } $outcomes = $out_of_time ? $this->cells_with_status( $raw_cells, 'not_attempted', null ) : $this->approve_product_cells( $product_id, $raw_cells, $options ); foreach ( $outcomes as $outcome ) { if ( 'applied' === $outcome['status'] ) { ++$applied_count; if ( 0 === $first_applied_product ) { $first_applied_product = $product_id; } } $results[] = array_merge( array( 'product_id' => $product_id ), $outcome ); } } if ( $applied_count > 0 ) { $this->record_usage_event( 'advanced_desc', 'approved', $applied_count, array( 'product_id' => $first_applied_product ) ); } $settled = array_filter( $results, static function ( array $result ): bool { return in_array( $result['status'], array( 'applied', 'kept' ), true ); } ); return new WP_REST_Response( array( 'success' => ! empty( $settled ), 'results' => $results, ), 200 ); } /** * Checks one product of approve-descriptions and applies its valid cells. * * @param int $product_id Product id from the request (0 when missing). * @param array $raw_cells The product's cells as sent. * @param array $options Sanitized apply options with `executionPath`. * @return array One outcome per cell sent. */ private function approve_product_cells( int $product_id, array $raw_cells, array $options ): array { if ( ! $product_id ) { return $this->cells_with_status( $raw_cells, 'failed', $this->missing_product_message() ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return $this->cells_with_status( $raw_cells, 'failed', $this->forbidden_product_message() ); } $order = array(); $refused = array(); $accepted = array(); foreach ( $raw_cells as $index => $raw_cell ) { $raw_cell = is_array( $raw_cell ) ? $raw_cell : array(); $type = sanitize_text_field( (string) ( $raw_cell['description_type'] ?? '' ) ); $content = wp_kses_post( (string) ( $raw_cell['description'] ?? '' ) ); $refusal = $this->cell_refusal( $type, $content ); if ( null === $refusal && isset( $accepted[ $type ] ) ) { $refusal = __( 'Each description type can be sent once per product.', 'ai-product-tools' ); } $order[ $index ] = $type; if ( null !== $refusal ) { $refused[ $index ] = array( 'description_type' => $type, 'status' => 'failed', 'message' => $refusal, ); continue; } $accepted[ $type ] = array( 'content' => $content, 'blueprint' => $this->approve_blueprint( $raw_cell['blueprint'] ?? null, (string) ( $options['executionPath'] ?? '' ) ), ); } $applied = empty( $accepted ) ? array() : $this->apply_product_cells( $product_id, $accepted, $options ); $outcomes = array(); foreach ( $order as $index => $type ) { $outcomes[] = $refused[ $index ] ?? array_merge( array( 'description_type' => $type ), $applied[ $type ] ); } return $outcomes; } /** * Writes one product's checked cells: the texts that carry the same * content template attribution in one applyContent() call (one product * save), then the tags in their own call, the order every other caller * of applyContent() uses. * * @param int $product_id Product id, already checked with edit_post. * @param array $cells Cells by type (short, full, tags). * @param array $options Sanitized apply options. * @return array Outcome by type. */ private function apply_product_cells( int $product_id, array $cells, array $options ): array { $writes = array(); foreach ( $cells as $type => $cell ) { if ( 'tags' === $type ) { continue; } foreach ( $writes as $index => $write ) { if ( $write['blueprint'] === $cell['blueprint'] ) { $writes[ $index ]['cells'][ $type ] = $cell['content']; continue 2; } } $writes[] = array( 'blueprint' => $cell['blueprint'], 'cells' => array( $type => $cell['content'] ), ); } if ( isset( $cells['tags'] ) ) { $writes[] = array( 'blueprint' => $cells['tags']['blueprint'], 'cells' => array( 'tags' => $cells['tags']['content'] ), ); } $outcomes = array(); foreach ( $writes as $write ) { $content = array(); foreach ( $write['cells'] as $type => $text ) { $content[ $this->map_db_type_to_internal( $type ) ] = $text; } $applied = $this->generator->applyContent( $product_id, $content, $options, $write['blueprint'] ); $kept = ( $applied && 1 === count( $content ) ) ? array() : $this->kept_fields(); foreach ( array_keys( $write['cells'] ) as $type ) { $outcomes[ $type ] = $this->cell_outcome( $type, $applied, in_array( $this->map_db_type_to_internal( $type ), $kept, true ) ); } } return $outcomes; } /** * Internal field names the last applyContent() call left alone because * "Fill empty only" found them filled. * * @return string[] */ private function kept_fields(): array { $kept = array(); foreach ( $this->generator->getSkippedFields() as $skipped_field ) { if ( 'not_empty' === ( $skipped_field['reason'] ?? '' ) ) { $kept[] = (string) ( $skipped_field['field'] ?? '' ); } } return $kept; } /** * One cell's outcome, with approve-description's messages. A field kept * by "Fill empty only" is a kept result, not a failed write. * * @param string $type Cell type (short, full, tags). * @param bool $applied Whether its write landed. * @param bool $kept Whether "Fill empty only" left its field alone. * @return array{status:string,message?:string} */ private function cell_outcome( string $type, bool $applied, bool $kept ): array { if ( $kept ) { return array( 'status' => 'kept', 'message' => __( 'Kept the existing text: this field already has content and Fill empty only is on. Switch Existing content to Replace to overwrite it.', 'ai-product-tools' ), ); } if ( $applied ) { return array( 'status' => 'applied' ); } if ( 'tags' === $type ) { return array( 'status' => 'failed', 'message' => __( 'No tags were saved. The generated tags were empty, the product already has them, or saving them failed. Try again.', 'ai-product-tools' ), ); } return array( 'status' => 'failed', 'message' => __( 'Failed to approve description', 'ai-product-tools' ), ); } /** * Why a cell cannot be approved, or null when its type and content are usable. * * @param string $type Sanitized cell type. * @param string $content Sanitized cell content. * @return string|null */ private function cell_refusal( string $type, string $content ): ?string { if ( empty( $type ) || ! in_array( $type, array( 'short', 'full', 'tags' ), true ) ) { return __( 'Valid description type is required (short, full, or tags)', 'ai-product-tools' ); } if ( empty( $content ) ) { return __( 'Description content is required', 'ai-product-tools' ); } return null; } /** * The same answer for every cell of one product. * * @param array $raw_cells The product's cells as sent. * @param string $status Status for each cell. * @param string|null $message Message for each cell, or null for none. * @return array */ private function cells_with_status( array $raw_cells, string $status, ?string $message ): array { $outcomes = array(); foreach ( $raw_cells as $raw_cell ) { $raw_cell = is_array( $raw_cell ) ? $raw_cell : array(); $outcome = array( 'description_type' => sanitize_text_field( (string) ( $raw_cell['description_type'] ?? '' ) ), 'status' => $status, ); if ( null !== $message ) { $outcome['message'] = $message; } $outcomes[] = $outcome; } return $outcomes; } /** * The generator's current execution path for an approve call. * * An approve call never went through generate(), so it has no * ProductResult to read an execution path from. Resolve the generator's * CURRENT path the same way processProduct() would, so an approved * Blueprint tags cell keeps the blueprint's own companions.tags.max * instead of being re-clamped to the Settings max_tags_count. These * endpoints never run inside an Automation job, so job-trusted facts are * always empty here. * * @return string */ private function approve_execution_path(): string { $decision = BlueprintIntegration::executionPath( BlueprintGenerators::DESCRIPTION, BlueprintIntegration::jobTrustedFacts() ); return $decision['path']; } /** * Denormalized blueprint attribution for an approve call. * * An approve never runs through generate(), so it has no ProductResult * to read a blueprint from. The page echoes back the generation * response's `blueprint` object; it is sanitized (untrusted input) and * only threaded through when the cell is actually in Blueprint mode: a * custom-prompts (advanced) write records nothing. * * @param mixed $raw_blueprint Blueprint value from the request. * @param string $execution_path The generator's current execution path. * @return array|null */ private function approve_blueprint( $raw_blueprint, string $execution_path ): ?array { if ( BlueprintIntegration::PATH_BLUEPRINT !== $execution_path ) { return null; } return BlueprintAttributionSanitizer::sanitize( $raw_blueprint ); } /** * Seconds since $start. A method of its own so a test can drive the time budget. * * @param float $start A microtime( true ) reading. * @return float */ protected function seconds_since( float $start ): float { return microtime( true ) - $start; } private function missing_product_message(): string { return __( 'Product ID is required', 'ai-product-tools' ); } private function forbidden_product_message(): string { return __( 'You do not have permission to edit this product.', 'ai-product-tools' ); } public function reject_description( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function bulk_approve( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function bulk_reject( WP_REST_Request $request ): WP_REST_Response { $data = $request->get_json_params(); $results = $data['results'] ?? array(); if ( empty( $results ) ) { return new WP_REST_Response( array( 'success' => false, 'message' => __( 'No items to reject', 'ai-product-tools' ) ), 400 ); } $success_count = 0; $first_rejected_pid = 0; foreach ( $results as $item ) { $product_id = absint( $item['product_id'] ?? 0 ); $type = sanitize_text_field( $item['description_type'] ?? '' ); if ( ! $product_id || ! $type ) { continue; } $success_count++; if ( 0 === $first_rejected_pid ) { $first_rejected_pid = $product_id; } } if ( $success_count > 0 ) { $this->record_usage_event( 'advanced_desc', 'rejected', $success_count, array( 'product_id' => $first_rejected_pid ) ); } return new WP_REST_Response( array( 'success' => true, /* translators: %d: number of items rejected */ 'message' => sprintf( _n( '%d item rejected', '%d items rejected', $success_count, 'ai-product-tools' ), $success_count ), 'rejected_count' => $success_count, ), 200 ); } public function delete_history_item( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function bulk_delete( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } public function delete_all_history(): WP_REST_Response { return $this->retired_route_response(); } public function cancel_generation( WP_REST_Request $request ): WP_REST_Response { return $this->retired_route_response(); } /** * Standard 410 Gone response for a legacy approval-queue route. * * Matches the SeoMeta deprecation precedent, and is actionable rather * than a bare status code: a stale admin tab (bundle loaded before this * update) needs "reload the page" surfaced, not an unexplained failure. * * @return WP_REST_Response */ private function retired_route_response(): WP_REST_Response { return new WP_REST_Response( array( 'success' => false, 'code' => 'aipt_route_retired', 'message' => __( 'This action is no longer available from this tab. Please reload the page to load the latest version.', 'ai-product-tools' ), ), 410 ); } private function map_db_type_to_internal( string $type ): string { $mapping = array( 'short' => 'short_description', 'full' => 'description', 'tags' => 'tags', ); return $mapping[ $type ] ?? $type; } /** * Record usage telemetry without breaking the approval workflow. * * @param string $feature Feature identifier. * @param string $action Action identifier. * @param int $count Event count. * @param array $meta Event metadata. * @return void */ private function record_usage_event( string $feature, string $action, int $count, array $meta ): void { try { \AIPT\Core\Services\UsageTracker::record_event( $feature, $action, $count, $meta ); } catch ( \Throwable $throwable ) { do_action( 'aipt_usage_tracking_failed', $throwable, $feature, $action, $count, $meta ); } } }