blueprintResolver = $blueprintResolver ?? new GoverningBlueprintResolver(); $this->pinService = $pinService ?? new RunPinService(); $this->tokenStore = $tokenStore ?? new ConfirmTokenStore(); $this->blueprintStore = $blueprintStore ?? new BlueprintStore(); $this->entitlementPolicy = $entitlementPolicy ?? new EntitlementPolicy(); $this->clock = $clock ?? static function () { return microtime( true ); }; $this->brandProfiles = $brandProfiles ?? new BrandProfileStore(); } /** * @param array{generator:string,product_ids:int[],destination?:string,overwrite?:string} $input Ability input, already schema-validated. * @param int $user_id Acting user id. * @return array|WP_Error Preview response, or an error. */ public function preview( array $input, int $user_id ) { $gate = AiSupportGate::guard(); if ( $gate instanceof WP_Error ) { return $gate; } $requested = count( array_unique( array_map( 'absint', (array) ( $input['product_ids'] ?? array() ) ) ) ); if ( ! AgentBulkGenerationGate::allows( $requested ) ) { return AgentBulkGenerationGate::denial( (string) ( $input['generator'] ?? '' ) ); } $rate_error = AbilityRateLimiter::consume( $user_id, 1 ); if ( null !== $rate_error ) { return $rate_error; } $generator = (string) ( $input['generator'] ?? '' ); $path = BlueprintIntegration::executionPath( $generator, array() ); if ( BlueprintIntegration::PATH_BLUEPRINT !== $path['path'] ) { return new WP_Error( 'aipt_ability_custom_prompts', __( 'This content type runs on custom prompts. Preview and confirm work only with its content template.', 'ai-product-tools' ), array( 'status' => 409 ) ); } $destination = 'review' === ( $input['destination'] ?? 'apply' ) ? 'review' : 'apply'; if ( 'review' === $destination && ! apply_filters( 'aipt_content_review_enabled', false ) ) { return new WP_Error( 'aipt_ability_review_unavailable', __( 'The review queue is not available on this plan. Choose apply instead.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $overwrite = 'empty_only' === ( $input['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace'; $product_ids = array_values( array_unique( array_map( 'absint', (array) ( $input['product_ids'] ?? array() ) ) ) ); $skipped = array(); $remaining = array(); foreach ( $product_ids as $product_id ) { $reason = $this->permissionSkipReason( $product_id ); if ( null !== $reason ) { $skipped[] = array( 'product_id' => $product_id, 'reason' => $reason ); continue; } $remaining[] = $product_id; } if ( empty( $remaining ) ) { return $this->noProductsError( $skipped ); } $pin = $this->pinService->createRunPin( $generator, null, $user_id ); if ( RunPinService::pinFailed( $pin ) ) { return new WP_Error( 'aipt_ability_pin_failed', __( 'This run could not be pinned. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } $resolved = $this->blueprintResolver->resolveForProducts( $generator, $remaining ); $groups_by_product = array(); $groups = array(); $order = 0; foreach ( $remaining as $product_id ) { $resolution = $resolved[ $product_id ] ?? array( 'conflict' => true ); if ( ! empty( $resolution['conflict'] ) ) { $skipped[] = array( 'product_id' => $product_id, 'reason' => 'conflict' ); continue; } $blueprint_id = $resolution['blueprintId']; $group_key = null === $blueprint_id ? 'builtin' : (string) $blueprint_id; $groups_by_product[ $product_id ] = $group_key; if ( ! isset( $groups[ $group_key ] ) ) { $name = $resolution['builtin'] /* translators: %s: built-in template name. */ ? sprintf( __( 'Built-in: %s', 'ai-product-tools' ), (string) $resolution['name'] ) : (string) $resolution['name']; $groups[ $group_key ] = array( 'blueprint_id' => $blueprint_id, 'name' => $name, 'revision' => $resolution['revision'], 'builtin' => (bool) $resolution['builtin'], 'product_count' => 0, '_order' => $order++, ); } $groups[ $group_key ]['product_count']++; } if ( empty( $groups_by_product ) ) { return $this->noProductsError( $skipped ); } $groups = array_values( $groups ); usort( $groups, static function ( array $a, array $b ): int { return $b['product_count'] <=> $a['product_count'] ?: $a['_order'] <=> $b['_order']; } ); foreach ( $groups as &$group ) { unset( $group['_order'] ); } unset( $group ); $final_product_ids = array_keys( $groups_by_product ); $product_count = count( $final_product_ids ); $sync_cap = max( 1, min( 5, (int) apply_filters( 'aipt_ability_sync_product_limit', 5 ) ) ); if ( $product_count <= $sync_cap ) { $mode = 'sync'; } elseif ( apply_filters( 'aipt_automation_surface_is_business', false ) ) { $mode = 'queued'; } else { $mode = 'deep_link'; } $plan_limits = $this->planLimits( $generator, $groups, $overwrite, $mode ); $skip_counts = array(); foreach ( $skipped as $entry ) { $skip_counts[ $entry['reason'] ] = ( $skip_counts[ $entry['reason'] ] ?? 0 ) + 1; } $token = $this->tokenStore->create( array( 'user_id' => $user_id, 'generator' => $generator, 'product_ids' => $final_product_ids, 'product_count' => $product_count, 'groups_by_product' => $groups_by_product, 'pin_id' => $pin['id'], 'pin_hash' => $pin['hash'], 'destination' => $destination, 'overwrite' => $overwrite, ) ); return array( 'confirm_token' => $token, 'expires_at' => gmdate( 'c', (int) $this->now() + 900 ), 'generator' => $generator, 'run_pin' => array( 'id' => $pin['id'], 'hash' => $pin['hash'], 'created_at' => $this->isoDate( (string) $pin['createdAt'] ) ), 'blueprints' => $groups, 'product_count' => $product_count, 'skipped' => $skipped, 'destination' => $destination, 'overwrite' => $overwrite, 'plan_limits' => $plan_limits, 'execution' => array( 'mode' => $mode, 'estimated_ai_calls' => array( 'min' => $product_count, 'max' => $product_count * self::MAX_CALLS_PER_PRODUCT ), ), 'summary' => SummaryTextBuilder::preview( $generator, $groups, $skip_counts ), ); } /** * @param array $skipped Skipped-products list so far. * @return WP_Error */ private function noProductsError( array $skipped ): WP_Error { return new WP_Error( 'aipt_ability_no_products', __( 'No products are left to run after permission and assignment checks.', 'ai-product-tools' ), array( 'status' => 400, 'skipped' => $skipped ) ); } /** * @param int $product_id Candidate product id. * @return string|null 'not_found' | 'forbidden' | null (usable). */ private function permissionSkipReason( int $product_id ): ?string { $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : false; if ( ! ProductEligibility::isEligible( $product ) ) { return 'not_found'; } if ( ! current_user_can( 'edit_post', $product_id ) ) { return 'forbidden'; } return null; } /** * Collect this preview's plan-limit notes: each involved Blueprint/ * built-in definition's own entitlement clamps * (SEO meta length/keyword, additional instructions, custom field * refs — every definition-level {@see EntitlementPolicy::apply()} * clamp, deduped by key across the groups involved), a voice's * withheld writing samples, FAQ's * replace-to-append downgrade (a separate gate `EntitlementPolicy` * does not cover; verified real behavior: {@see * \AIPT\Core\ContentReview\ContentReviewApplier::applyFaq()} silently * writes `append` instead of `replace` when `aipt_faq_replace_enabled` * is false — it never blocks the write), and the sync-cap deep-link * note. Per-subject clamps that need a resolved product (the image_alt * gallery entitlement, a withheld AI note) are not reported here: they * depend on each product's own state, which an AI-free, per-blueprint * preview does not resolve. * * @param string $generator Generator key. * @param array $groups This preview's `blueprints` groups (already built). * @param string $overwrite 'replace' | 'empty_only'. * @param string $mode Execution mode already decided for this run. * @return array */ private function planLimits( string $generator, array $groups, string $overwrite, string $mode ): array { $by_key = array(); foreach ( $groups as $group ) { $blueprint = $group['builtin'] ? null : $this->blueprintStore->get( (int) $group['blueprint_id'] ); $definition = $this->rawDefinition( $generator, $group, $blueprint ); $applied = $this->entitlementPolicy->apply( $generator, $definition )['appliedFreeDefaults']; if ( $this->voiceSamplesWithheld( $blueprint ) ) { $applied[] = $this->entitlementPolicy->voiceSamplesFreeDefault(); } foreach ( $applied as $entry ) { $by_key[ $entry['key'] ] = $entry; } } if ( Generators::FAQ === $generator && 'empty_only' !== $overwrite && ! apply_filters( 'aipt_faq_replace_enabled', false ) ) { $by_key['faq:replace'] = array( 'key' => 'faq:replace', 'reason' => __( 'New questions were added to the existing FAQ instead of replacing it.', 'ai-product-tools' ), 'business' => __( 'replacing the existing FAQ', 'ai-product-tools' ), ); } if ( 'deep_link' === $mode ) { $by_key['ability:deepLink'] = array( 'key' => 'ability:deepLink', 'reason' => __( 'More products matched than can be applied directly in one run. Use the link to continue with every matched product on the generator page.', 'ai-product-tools' ), 'business' => __( 'running every matched product at once with Automation', 'ai-product-tools' ), ); } return array_values( $by_key ); } /** * @param string $generator Generator key. * @param array $group A preview group entry ({@see preview()}'s `blueprints` shape). * @param array|null $blueprint The group's stored Blueprint row; null for the built-in one or a missing row. * @return array Raw (unclamped) BlueprintDefinition. */ private function rawDefinition( string $generator, array $group, ?array $blueprint ): array { if ( $group['builtin'] ) { $template_key = TemplateCatalog::defaultKey( $generator ); $template = TemplateCatalog::get( $generator, $template_key ); return null !== $template ? $template['definition'] : array(); } return null !== $blueprint && is_array( $blueprint['definition'] ) ? $blueprint['definition'] : array(); } /** * Whether a run of $blueprint withholds its voice's writing samples * ({@see EntitlementPolicy::clampBrandProfile()}). The voice is not * part of the definition, so `apply()` cannot say so on its own. * * @param array|null $blueprint Stored Blueprint row; null for the built-in one, which has no voice. * @return bool */ private function voiceSamplesWithheld( ?array $blueprint ): bool { $profile_id = null !== $blueprint ? (int) ( $blueprint['brandProfileId'] ?? 0 ) : 0; $profile = $profile_id > 0 ? $this->brandProfiles->get( $profile_id ) : null; return null !== $profile && $this->entitlementPolicy->clampBrandProfile( is_array( $profile['profile'] ?? null ) ? $profile['profile'] : null )['dropped']; } /** * @param string $mysql_datetime A stored MySQL UTC datetime, or an already-ISO string. * @return string ISO 8601. */ private function isoDate( string $mysql_datetime ): string { $timestamp = strtotime( $mysql_datetime . ' UTC' ); return false !== $timestamp ? gmdate( 'c', $timestamp ) : $mysql_datetime; } /** * @return float */ private function now(): float { return (float) call_user_func( $this->clock ); } }