mostRecentProductIdResolver = $mostRecentProductIdResolver ?? array( $this, 'queryMostRecentProductId' ); } /** * Get onboarding status * * Determines if onboarding popup should be shown based on API key existence, * setup completion, and snooze state. * * Since 2.6.0: hasApiKey/shouldShow consult CredentialResolver chain (Connectors → Local). * New connectorsManaged and connectorsAvailable fields added for UI consumption. * * @since 2.6.0 * * @return array Onboarding state with shouldShow, isFirstTime, hasApiKey, setupCompleted, * isSnoozed, snoozeUntil, onboardingDismissed, connectorsManaged, * connectorsAvailable, hasAnyUsableKey, mcpReachable, firstRun. * setupCompleted is derived: the setup option or any usable key. */ public function getStatus(): array { $resolver = CredentialResolver::instance(); $has_any_usable_key = $resolver->hasAnyConfiguredProvider(); $setup_completed = get_option( 'aipt_setup_completed', false ); $snooze_until = get_option( 'aipt_onboarding_snoozed_until', 0 ); $is_snoozed = $snooze_until > time(); $onboarding_dismissed = get_option( 'aipt_onboarding_dismissed', false ); $connectors_managed = $resolver->connectorsManagedProviders(); $setup_fields = SetupState::statusFields( $resolver ); return array( 'shouldShow' => current_user_can( 'manage_aipt_settings' ) && ! $setup_completed && ! $is_snoozed && ! $onboarding_dismissed && ! $resolver->hasAnyLocalUsableKey(), 'isFirstTime' => ! get_option( 'aipt_first_run_completed', false ), 'hasApiKey' => $has_any_usable_key, 'setupCompleted' => $setup_fields['setupCompleted'], 'isSnoozed' => $is_snoozed, 'snoozeUntil' => $snooze_until, 'onboardingDismissed' => (bool) $onboarding_dismissed, 'connectorsManaged' => $connectors_managed, 'connectorsAvailable' => $this->supportsConnectorsApi(), 'hasAnyUsableKey' => $setup_fields['hasAnyUsableKey'], 'mcpReachable' => $setup_fields['mcpReachable'], 'firstRun' => $setup_fields['firstRun'], 'firstProductEditUrl' => $this->firstProductEditUrl(), 'newProductUrl' => admin_url( 'post-new.php?post_type=product' ), ); } /** * Completion's "Preview on your first product": the edit URL of the most * recent product in any non-trash status, with the Description drawer's * auto-open flag appended. Public so Init::get_onboarding_status_fast(), * the payload the setup wizard actually reads, can include it too. * * @return string|null */ public function firstProductEditUrl(): ?string { $product_id = (int) call_user_func( $this->mostRecentProductIdResolver ); if ( $product_id <= 0 ) { return null; } $edit_url = admin_url( 'post.php?post=' . $product_id . '&action=edit' ); return (string) add_query_arg( 'aipt_open', 'description', $edit_url ); } /** * Default `$mostRecentProductIdResolver`: the newest product's post id * (any non-trash status), via a cheap ids-only, single-row, * no-found-rows query. * * @since 2.8.0 * * @return int */ protected function queryMostRecentProductId(): int { $query = new \WP_Query( array( 'post_type' => 'product', 'post_status' => 'any', 'posts_per_page' => 1, 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ) ); $ids = $query->posts; return ! empty( $ids ) ? (int) $ids[0] : 0; } /** * Checks if the WordPress Connectors API is available. * * Extracted as a protected method to allow overriding in tests without * depending on function_exists() state, which persists across the test * process once Brain Monkey first defines the connector functions. * * @since 2.6.0 * * @return bool True if Connectors API functions exist. */ protected function supportsConnectorsApi(): bool { return WordPressRuntimeDetector::supportsConnectorsApi(); } /** * Complete setup wizard * * Validates and saves API key, sets default model for provider, and marks setup as complete. * * @param array $data Setup data containing api_key and api_provider * @return array|\WP_Error Success response or error * @throws \Exception If validation or save operations fail */ public function completeSetup( array $data ) { $api_key = isset( $data['api_key'] ) ? sanitize_text_field( $data['api_key'] ) : ''; $api_key = preg_replace( '/\s+/', '', $api_key ); $api_provider = isset( $data['api_provider'] ) ? sanitize_text_field( $data['api_provider'] ) : 'openai'; $claude_workspace_id = isset( $data['claude_workspace_id'] ) ? sanitize_text_field( $data['claude_workspace_id'] ) : ''; try { if ( ! current_user_can( 'manage_aipt_settings' ) ) { return new \WP_Error( 'rest_forbidden', esc_html__( 'Sorry, you are not allowed to do that.', 'ai-product-tools' ), array( 'status' => 401 ) ); } if ( ! in_array( $api_provider, array( 'openai', 'gemini', 'openrouter', 'claude' ), true ) ) { return new \WP_Error( 'invalid_provider', esc_html__( 'Invalid API provider selected.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $provider_configured = CredentialResolver::instance()->isConfigured( $api_provider ); if ( ! empty( $api_key ) && $provider_configured ) { return new \WP_Error( 'aipt_api_key_already_configured', __( 'This provider already has an API key. Remove it in Settings -> API to replace it.', 'ai-product-tools' ), array( 'status' => 409 ) ); } if ( empty( $api_key ) ) { if ( $provider_configured ) { $api_key_saved = true; } else { return new \WP_Error( 'empty_api_key', esc_html__( 'API key cannot be empty. Please enter a valid API key.', 'ai-product-tools' ), array( 'status' => 400 ) ); } } else { $api_key_saved = false; } $provider_dashboards = array( 'openai' => 'https://platform.openai.com/api-keys', 'gemini' => 'https://aistudio.google.com/app/apikey', 'openrouter' => 'https://openrouter.ai/keys', 'claude' => 'https://console.anthropic.com/settings/keys', ); if ( ! empty( $api_key ) ) { try { if ( $api_provider === 'gemini' ) { GeminiClient::validate_api_key( $api_key ); } elseif ( $api_provider === 'openrouter' ) { OpenRouterClient::validate_api_key( $api_key ); } elseif ( $api_provider === 'claude' ) { ClaudeClient::validate_api_key( $api_key, $claude_workspace_id ); } else { OpenAIClient::validate_api_key( $api_key ); } } catch ( ProviderCallException $e ) { if ( ProviderCallException::AUTH_INVALID_KEY !== $e->reason() ) { return new \WP_Error( 'provider_error', $e->merchantMessage( $api_provider ), array( 'status' => $e->isRetryable() ? 503 : 400, 'reason' => $e->reason(), 'error_details' => $e->getMessage(), ) ); } return self::invalidApiKeyResponse( $api_provider, $provider_dashboards, $e->getMessage(), $e->reason() ); } catch ( \Exception $e ) { return self::invalidApiKeyResponse( $api_provider, $provider_dashboards, $e->getMessage() ); } } Encryption::setup_new_installation(); $default_model = \AIPT\Api\ModelCatalog::get_default_model( $api_provider ); if ( ! empty( $api_key ) ) { if ( $api_provider === 'gemini' ) { $api_key_saved = ApiKeyManager::set_gemini_key( $api_key ); } elseif ( $api_provider === 'openrouter' ) { $api_key_saved = ApiKeyManager::set_openrouter_key( $api_key ); } elseif ( $api_provider === 'claude' ) { $api_key_saved = ApiKeyManager::set_claude_key( $api_key ); } else { $api_key_saved = ApiKeyManager::set_openai_key( $api_key ); } } if ( ! $api_key_saved ) { $provider_display = ucfirst( $api_provider ); if ( $api_provider === 'openrouter' ) { $provider_display = 'OpenRouter'; } elseif ( $api_provider === 'openai' ) { $provider_display = 'OpenAI'; } elseif ( $api_provider === 'gemini' ) { $provider_display = 'Gemini'; } elseif ( $api_provider === 'claude' ) { $provider_display = 'Claude'; } return new \WP_Error( 'api_key_save_failed', sprintf( /* translators: %s: API provider name (e.g., OpenAI, Gemini, OpenRouter) */ esc_html__( 'Failed to save %s API key. This may be due to database permissions or server configuration issues. Please try again or contact your hosting provider.', 'ai-product-tools' ), $provider_display ), array( 'status' => 500, 'provider' => $api_provider, 'troubleshooting' => 'Check database permissions and server configuration', ) ); } update_option( 'aipt_api_provider', $api_provider ); update_option( 'aipt_model', $default_model ); if ( 'claude' === $api_provider ) { update_option( 'aipt_claude_workspace_id', $claude_workspace_id ); } update_option( 'aipt_setup_completed', true, false ); update_option( 'aipt_needs_setup', false, false ); update_option( 'aipt_first_run_completed', true, false ); FunnelMilestones::record( 'key_saved' ); return array( 'success' => true, 'message' => esc_html__( 'Setup completed successfully.', 'ai-product-tools' ), ); } catch ( \Exception $e ) { return new \WP_Error( 'setup_failed', esc_html__( 'Error completing setup: ', 'ai-product-tools' ) . esc_html( $e->getMessage() ), array( 'status' => 500 ) ); } } /** * The "this key is invalid, go verify and re-issue it" response, shared * by the ProviderCallException::AUTH_INVALID_KEY branch and the plain * \Exception safety-net branch above. * * @param string $api_provider AIPT provider id. * @param array $provider_dashboards Provider id => dashboard URL map. * @param string $error_message Technical message, for error_details. * @param string|null $reason ProviderCallException reason, when known. * @return \WP_Error * * @since 2.8.0 */ private static function invalidApiKeyResponse( string $api_provider, array $provider_dashboards, string $error_message, ?string $reason = null ): \WP_Error { $provider_lower = strtolower( $api_provider ); $dashboard_url = $provider_dashboards[ $provider_lower ] ?? ''; $troubleshooting = array( 'dashboard_url' => $dashboard_url, 'bullets' => array( __( 'Copy the key fully without leading/trailing spaces.', 'ai-product-tools' ), __( 'Verify the key has not been revoked or rate limited.', 'ai-product-tools' ), __( 'Confirm the key is the correct type (server-side API key, not a client/org ID).', 'ai-product-tools' ), ), ); $message = sprintf( /* translators: 1: provider name, 2: dashboard URL or empty */ __( 'Invalid %1$s API key. Visit %2$s to verify and re-issue.', 'ai-product-tools' ), ucfirst( $provider_lower ), $dashboard_url ); $data = array( 'status' => 400, 'error_details' => $error_message, 'troubleshooting' => $troubleshooting, ); if ( null !== $reason ) { $data['reason'] = $reason; } return new \WP_Error( 'invalid_api_key', $message, $data ); } /** * Snooze onboarding popup * * Sets a timestamp for 1 hour from now to temporarily hide onboarding. * * @return array Success response with snooze_until timestamp */ public function snooze(): array { $snooze_until = time() + ( 60 * 60 ); update_option( 'aipt_onboarding_snoozed_until', $snooze_until, false ); return array( 'success' => true, 'message' => 'Onboarding snoozed for 1 hour', 'snooze_until' => $snooze_until, ); } /** * Skip setup process * * Marks setup as completed and dismissed without requiring API key configuration. * * @return array Success response */ public function skipSetup(): array { update_option( 'aipt_setup_completed', true, false ); update_option( 'aipt_needs_setup', false, false ); update_option( 'aipt_onboarding_dismissed', true, false ); update_option( 'aipt_first_run_completed', true, false ); return array( 'success' => true, 'message' => 'Setup skipped successfully', ); } /** * Valid quick start step IDs, in tour order. * * Must stay byte-identical, id-for-id and in the same order, to the * client tour's `TOUR_STEPS` (src/Components/QuickStart/tourSteps.ts; * checked by tests/js/Components/QuickStart/tourParity.test.ts). Public * so Init::get_onboarding_status_fast() can derive totalSteps from it * instead of hardcoding a count. * * @var string[] */ public const QUICKSTART_STEPS = array( 'content-templates', 'structure-tab', 'try-on-product', 'generation-tab', 'content-bank', 'automation' ); /** * Get quick start guide status * * Returns current progress state for preloading into frontend. * * @return array Quick start state with completedSteps, dismissed, completed, totalSteps */ public function getQuickStartStatus(): array { $completed_steps = get_option( 'aipt_quickstart_completed_steps', '[]' ); if ( is_string( $completed_steps ) ) { $completed_steps = json_decode( $completed_steps, true ); if ( ! is_array( $completed_steps ) ) { $completed_steps = array(); } } $completed_steps = array_values( array_intersect( $completed_steps, self::QUICKSTART_STEPS ) ); $is_completed = count( $completed_steps ) >= count( self::QUICKSTART_STEPS ); return array( 'completedSteps' => $completed_steps, 'dismissed' => (bool) get_option( 'aipt_quickstart_dismissed', false ), 'completed' => $is_completed, 'totalSteps' => count( self::QUICKSTART_STEPS ), ); } /** * Complete a quick start step * * Marks a specific step as completed. Auto-completes guide when all steps are done. * * @param string $step_id Step identifier to mark complete * @return array|\WP_Error Updated state or error */ public function completeQuickStartStep( string $step_id ) { if ( ! in_array( $step_id, self::QUICKSTART_STEPS, true ) ) { return new \WP_Error( 'invalid_step', esc_html__( 'Invalid quick start step.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $completed_steps = get_option( 'aipt_quickstart_completed_steps', '[]' ); if ( is_string( $completed_steps ) ) { $completed_steps = json_decode( $completed_steps, true ); if ( ! is_array( $completed_steps ) ) { $completed_steps = array(); } } if ( ! in_array( $step_id, $completed_steps, true ) ) { $completed_steps[] = $step_id; update_option( 'aipt_quickstart_completed_steps', wp_json_encode( array_values( $completed_steps ) ), false ); } $all_done = count( array_intersect( $completed_steps, self::QUICKSTART_STEPS ) ) >= count( self::QUICKSTART_STEPS ); if ( $all_done ) { update_option( 'aipt_quickstart_completed', true, false ); } return $this->getQuickStartStatus(); } /** * Dismiss quick start guide * * Permanently hides the guide panel. Can be reversed via reset. * * @return array Updated state */ public function dismissQuickStart(): array { update_option( 'aipt_quickstart_dismissed', true, false ); return $this->getQuickStartStatus(); } /** * Reset quick start guide * * Clears all progress and makes the guide visible again. * * @return array Reset state */ public function resetQuickStart(): array { update_option( 'aipt_quickstart_completed_steps', '[]', false ); update_option( 'aipt_quickstart_dismissed', false, false ); update_option( 'aipt_quickstart_completed', false, false ); return $this->getQuickStartStatus(); } }