'POST', 'callback' => array( __CLASS__, 'test' ), 'permission_callback' => array( __CLASS__, 'check_test_permission' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/results/(?P[a-f0-9]{32})/regenerate', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'regenerate_section' ), 'permission_callback' => array( __CLASS__, 'check_test_permission' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/results/(?P[a-f0-9]{32})', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_result' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/results/(?P[a-f0-9]{32})/apply', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'apply_result' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/results/(?P[a-f0-9]{32})/conflicts/(?P[a-zA-Z0-9_-]+)', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'decide_conflict' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/runs', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_run' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/runs/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_run' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ) ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/(?P\d+)/bulk', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'bulk' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ) ), ), ) ); } /** * USE: anyone who can generate may test a structure, including an * unsaved draft nobody has saved yet. * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_test_permission( $request ) { return self::check_permissions_read( $request ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function test( WP_REST_Request $request ) { $gate = AiSupportGate::guard(); if ( is_wp_error( $gate ) ) { return $gate; } $user_id = get_current_user_id(); $body = (array) $request->get_json_params(); $client_request_id = isset( $body['clientRequestId'] ) ? sanitize_text_field( (string) $body['clientRequestId'] ) : ''; $claim = self::dedupeClaim( $user_id, $client_request_id ); if ( is_wp_error( $claim ) ) { return $claim; } if ( is_array( $claim ) ) { return self::success( $claim ); } $rate_check = self::checkRateLimitStatic( $user_id, self::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { self::dedupeRelease( $user_id, $client_request_id ); return self::rateLimitErrorStatic( $rate_check ); } $generator = sanitize_key( (string) ( $body['generator'] ?? '' ) ); $subject = is_array( $body['subject'] ?? null ) ? $body['subject'] : array(); $run_options = self::withSavedFaqQuestions( $generator, $subject, is_array( $body['runOptions'] ?? null ) ? $body['runOptions'] : array() ); $exec_request = ExecutionRequest::fromArray( array( 'generator' => $generator, 'subject' => $subject, 'mode' => 'test', 'draft' => is_array( $body['draft'] ?? null ) ? $body['draft'] : null, 'blueprintId' => isset( $body['blueprintId'] ) ? (int) $body['blueprintId'] : null, 'runOptions' => $run_options, 'origin' => 'test', 'userId' => $user_id, 'clientVersion' => isset( $body['clientVersion'] ) ? (int) $body['clientVersion'] : null, 'clientRequestId' => $client_request_id, ) ); $result = self::executionService()->generate( $exec_request ); if ( is_wp_error( $result ) ) { self::dedupeRelease( $user_id, $client_request_id ); return $result; } self::dedupeStore( $user_id, $client_request_id, $result ); return self::success( $result ); } /** * A product's FAQ run that will add to the saved questions (every plan * without FAQ replace, which is what applying a result does there) is told * which questions the product already shows, so it does not repeat them in * different words. Questions the caller sent keep their place after them. * * @param string $generator Generator key. * @param array $subject Request subject. * @param array $run_options Request runOptions. * @return array runOptions with `excludeQuestions` filled when it applies. */ private static function withSavedFaqQuestions( string $generator, array $subject, array $run_options ): array { if ( Generators::FAQ !== $generator || 'product' !== ( $subject['type'] ?? '' ) || apply_filters( 'aipt_faq_replace_enabled', false ) ) { return $run_options; } $saved = SavedFaqQuestions::forProduct( (int) ( $subject['id'] ?? 0 ) ); if ( empty( $saved ) ) { return $run_options; } $sent = is_array( $run_options['excludeQuestions'] ?? null ) ? $run_options['excludeQuestions'] : array(); $run_options['excludeQuestions'] = array_merge( $saved, $sent ); return $run_options; } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function regenerate_section( WP_REST_Request $request ) { $gate = AiSupportGate::guard(); if ( is_wp_error( $gate ) ) { return $gate; } $user_id = get_current_user_id(); $body = (array) $request->get_json_params(); $client_request_id = isset( $body['clientRequestId'] ) ? sanitize_text_field( (string) $body['clientRequestId'] ) : ''; $claim = self::dedupeClaim( $user_id, $client_request_id ); if ( is_wp_error( $claim ) ) { return $claim; } if ( is_array( $claim ) ) { return self::success( $claim ); } $rate_check = self::checkRateLimitStatic( $user_id, self::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { self::dedupeRelease( $user_id, $client_request_id ); return self::rateLimitErrorStatic( $rate_check ); } $unit_id = isset( $body['sectionId'] ) ? sanitize_text_field( (string) $body['sectionId'] ) : ''; if ( '' === $unit_id ) { self::dedupeRelease( $user_id, $client_request_id ); return self::error( 'aipt_blueprint_invalid_request', __( 'A sectionId is required.', 'ai-product-tools' ), 400 ); } $draft = is_array( $body['draft'] ?? null ) ? $body['draft'] : null; $result = self::executionService()->regenerateSection( (string) $request->get_param( 'key' ), $unit_id, $draft, $user_id ); if ( is_wp_error( $result ) ) { self::dedupeRelease( $user_id, $client_request_id ); return $result; } self::dedupeStore( $user_id, $client_request_id, $result ); return self::success( $result ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_result( WP_REST_Request $request ) { $key = (string) $request->get_param( 'key' ); $row = ( new \AIPT\Core\ContentStructure\Storage\ResultStore() )->get( $key ); if ( null === $row ) { return self::error( 'aipt_blueprint_result_not_found', __( 'This result no longer exists.', 'ai-product-tools' ), 404 ); } if ( (int) $row['createdBy'] !== get_current_user_id() && ! current_user_can( RestConstants::CAP_MANAGE ) ) { return self::error( 'rest_forbidden', __( 'You do not have permission to view this result.', 'ai-product-tools' ), 403 ); } $payload = is_array( $row['payload'] ) ? $row['payload'] : array(); $payload['resultKey'] = $key; return self::success( $payload ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function apply_result( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $params = array( 'expectedDefinitionHash' => (string) ( $body['expectedDefinitionHash'] ?? '' ), 'overwrite' => (string) ( $body['overwrite'] ?? 'replace' ), 'destination' => (string) ( $body['destination'] ?? 'apply' ), 'confirmReview' => ! empty( $body['confirmReview'] ), 'outputs' => $body['outputs'] ?? null, 'screen' => isset( $body['screen'] ) ? sanitize_key( (string) $body['screen'] ) : '', ); $result = self::resultApplier()->apply( (string) $request->get_param( 'key' ), $params, get_current_user_id() ); if ( is_wp_error( $result ) ) { return $result; } return self::success( $result ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function decide_conflict( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $params = array( 'action' => (string) ( $body['action'] ?? '' ), 'ref' => (string) ( $body['ref'] ?? '' ), ); $result = ( new ConflictDecisionService() )->decide( (string) $request->get_param( 'key' ), (string) $request->get_param( 'conflictId' ), $params, get_current_user_id() ); if ( is_wp_error( $result ) ) { return $result; } return self::success( $result ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function create_run( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = sanitize_key( (string) ( $body['generator'] ?? '' ) ); if ( ! Generators::isValid( $generator ) ) { return self::error( 'aipt_blueprint_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), 400 ); } $blueprint_id = isset( $body['blueprintId'] ) && null !== $body['blueprintId'] ? (int) $body['blueprintId'] : null; if ( null !== $blueprint_id ) { $mismatch = self::checkGeneratorMatch( $blueprint_id, $generator ); if ( is_wp_error( $mismatch ) ) { return $mismatch; } } $pin = ( new RunPinService() )->createRunPin( $generator, $blueprint_id, get_current_user_id() ); if ( RunPinService::pinFailed( $pin ) ) { return self::error( 'aipt_blueprint_pin_failed', __( 'This run could not be pinned. Please try again.', 'ai-product-tools' ), 500 ); } return self::success( self::runPinShape( $pin ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_run( WP_REST_Request $request ) { $pin = ( new RunPinService() )->loadRunPin( (int) $request->get_param( 'id' ) ); if ( null === $pin ) { return self::error( 'aipt_blueprint_pin_missing', __( 'This run pin no longer exists.', 'ai-product-tools' ), 404 ); } return self::success( self::runPinShape( $pin ) ); } /** * @param array $pin RunPinService's pin shape (carries a raw `payload`). * @return array RunPin, without the internal payload. */ private static function runPinShape( array $pin ): array { return array( 'id' => $pin['id'], 'hash' => $pin['hash'], 'generator' => $pin['generator'], 'manualBlueprintId' => $pin['manualBlueprintId'], 'blueprints' => $pin['blueprints'], 'createdAt' => self::isoDate( (string) $pin['createdAt'] ), ); } /** * @param int $blueprint_id Blueprint id. * @param string $generator Expected generator key. * @return WP_Error|null */ private static function checkGeneratorMatch( int $blueprint_id, string $generator ): ?WP_Error { $blueprint = ( new BlueprintStore() )->get( $blueprint_id ); if ( null === $blueprint ) { return self::error( 'aipt_blueprint_not_found', __( 'This template no longer exists.', 'ai-product-tools' ), 404 ); } if ( $blueprint['generator'] !== $generator ) { return self::error( 'aipt_blueprint_generator_mismatch', __( 'This template is for a different content type.', 'ai-product-tools' ), 400 ); } return null; } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function bulk( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $blueprint = ( new BlueprintStore() )->get( $id ); if ( null === $blueprint ) { return self::error( 'aipt_blueprint_not_found', __( 'This template no longer exists.', 'ai-product-tools' ), 404 ); } $body = (array) $request->get_json_params(); $expected_revision = isset( $body['expectedRevision'] ) ? (int) $body['expectedRevision'] : -1; if ( (int) $blueprint['revision'] !== $expected_revision ) { return self::error( 'aipt_blueprint_revision_conflict', __( 'This template changed since it was loaded. Reload and try again.', 'ai-product-tools' ), 409, array( 'current' => array( 'revision' => (int) $blueprint['revision'] ) ) ); } $generator = (string) $blueprint['generator']; $overwrite = 'empty_only' === ( $body['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace'; $destination = 'review' === ( $body['destination'] ?? 'apply' ) ? 'review' : 'apply'; if ( 'review' === $destination && ! apply_filters( 'aipt_content_review_enabled', false ) ) { return self::error( 'aipt_blueprint_review_unavailable', __( 'The review queue is not available on this plan. Choose apply instead.', 'ai-product-tools' ), 403 ); } if ( 'review' === $destination && ! apply_filters( 'aipt_draft_review_enabled', false ) ) { return self::error( 'aipt_blueprint_draft_review_unavailable', __( 'Queuing this as a background job needs the review queue for Automation jobs, which is not available on this plan. Choose apply instead.', 'ai-product-tools' ), 403 ); } $scope = ( new AssignmentScope() )->productsForBlueprint( $generator, $id, 2000 ); $product_count = (int) $scope['total']; $approximate = ! empty( $scope['approximate'] ); if ( empty( $scope['ids'] ) ) { return self::success( array( 'productCount' => 0, 'revision' => (int) $blueprint['revision'] ) ); } $pin = ( new RunPinService() )->createRunPin( $generator, $id, get_current_user_id() ); if ( RunPinService::pinFailed( $pin ) ) { return self::error( 'aipt_blueprint_pin_failed', __( 'This run could not be pinned. Please try again.', 'ai-product-tools' ), 500 ); } $tool_type = Generators::automationToolType( $generator ); if ( '' === $tool_type ) { return self::success( AutomationJobLauncher::deepLinkPayload( $generator, $pin, $scope['ids'], $product_count, (int) $blueprint['revision'], $approximate, AutomationJobLauncher::FALLBACK_NO_JOB_TYPE ) ); } $status = 'review' === $destination ? 'draft' : 'published'; $job_payload = array( 'name' => sprintf( /* translators: %s: template name. */ __( 'Apply "%s"', 'ai-product-tools' ), $blueprint['name'] ), 'toolType' => $tool_type, 'settings' => array( 'provider' => get_option( 'aipt_api_provider', '' ), 'model' => get_option( 'aipt_model', '' ), 'contentSettings' => array( 'status' => $status ), 'blueprint' => array( 'mode' => 'blueprint', 'manualBlueprintId' => $id, 'runPinId' => $pin['id'], 'runPinHash' => $pin['hash'], 'pinnedAt' => $pin['createdAt'], 'blueprints' => $pin['blueprints'], 'overwrite' => $overwrite, ), ), 'schedule' => array( 'type' => 'once' ), 'productFilter' => array( 'includeIds' => implode( ',', $scope['ids'] ) ), 'totalProducts' => $product_count, ); $nonce = (string) ( $request->get_header( 'X-WP-Nonce' ) ?? '' ); $job_response = AutomationJobLauncher::createJob( $job_payload, $nonce ); if ( is_wp_error( $job_response ) || $job_response->get_status() >= 400 ) { return self::success( AutomationJobLauncher::deepLinkPayload( $generator, $pin, $scope['ids'], $product_count, (int) $blueprint['revision'], $approximate, AutomationJobLauncher::FALLBACK_JOB_FAILED, AutomationJobLauncher::refusalMessage( $job_response ) ) ); } $data = $job_response->get_data(); $job_id = (int) ( $data['data']['id'] ?? 0 ); if ( $job_id <= 0 ) { return self::success( AutomationJobLauncher::deepLinkPayload( $generator, $pin, $scope['ids'], $product_count, (int) $blueprint['revision'], $approximate, AutomationJobLauncher::FALLBACK_JOB_FAILED ) ); } return self::success( array( 'jobId' => $job_id, 'jobUrl' => function_exists( 'admin_url' ) ? admin_url( 'admin.php?page=aipt-automation-jobs&jobId=' . $job_id ) : '', 'productCount' => $product_count, 'approximate' => $approximate, 'revision' => (int) $blueprint['revision'], ) ); } /** * @return ExecutionService */ private static function executionService(): ExecutionService { if ( null !== self::$executionServiceOverride ) { return self::$executionServiceOverride; } return ExecutionService::withSourcesAndDecisions(); } /** * @return ResultApplier */ private static function resultApplier(): ResultApplier { return self::$resultApplierOverride ?? new ResultApplier(); } }