Skip to content

Conversation

@arifulhoque7
Copy link
Contributor

@arifulhoque7 arifulhoque7 commented Nov 28, 2025

Close issue

AI Form Builder with Pre-built Integration Templates for WooCommerce, EDD, and The Events Calendar


📋 Overview

This feature adds integration-specific AI form generation capabilities to the WP User Frontend AI Form Builder, enabling users to create specialized forms for popular WordPress plugins with pre-configured field structures and intelligent prompts.


✨ Key Features

🎯 Integration Selector UI

  • Added dropdown selector in the AI Form Builder input stage (post forms only)
  • Users can choose from:
    • Regular Form (default)
    • WooCommerce Product Form
    • Easy Digital Downloads Product Form
    • The Events Calendar Event Form
  • Dynamic integration detection based on active plugins
  • Graceful fallback when integrations are not available

🤖 Specialized AI Prompts

Added three comprehensive prompt templates with precise field structures:

  1. wpuf-ai-prompt-woocommerce.md (463 lines)

    • Complete WooCommerce product submission form structure
    • Includes: Product Name, Description, Pricing, Gallery, Catalog Visibility, Reviews
    • Sets post_type: "product" automatically
  2. wpuf-ai-prompt-edd.md (325 lines)

    • Easy Digital Downloads product form template
    • Includes: Download Name, Description, Pricing, Files, Categories
    • Sets post_type: "download" automatically
  3. wpuf-ai-prompt-events-calendar.md (408 lines)

    • The Events Calendar event submission form
    • Includes: Event Title, Description, Date/Time, Venue, Organizer
    • Sets post_type: "tribe_events" automatically

🔌 Backend API

  • New REST endpoint: GET /wpuf/v1/ai-form-builder/integrations
  • Returns available integrations based on active plugins
  • Integration detection logic in AI_Manager.php
  • Integration-specific prompt loading in FormGenerator.php

📁 Modified Files

File | Changes | Lines -- | -- | -- assets/js/components/AIFormBuilder.vue | Integration state management | +42 assets/js/components/FormInputStage.vue | Integration selector UI | +167 includes/AI/FormGenerator.php | Integration-specific prompts | +53 includes/AI/Form_Builder.php | Integration context passing | +15 includes/AI/RestController.php | Integrations endpoint | +86 includes/AI_Manager.php | Integration detection | +11

New Files:

  • includes/AI/wpuf-ai-prompt-woocommerce.md (+463 lines)
  • includes/AI/wpuf-ai-prompt-edd.md (+325 lines)
  • includes/AI/wpuf-ai-prompt-events-calendar.md (+408 lines)

Total: +1,548 lines, -22 lines


🎨 User Experience

Before:

  • Users had to manually describe WooCommerce/EDD/Event fields
  • No guidance on required WooCommerce meta fields
  • Generic AI prompts for all form types

After:

  • One-click selection of integration type
  • Pre-configured field structures matching plugin standards
  • Context-aware AI that understands WooCommerce _regular_price, EDD pricing tiers, Event date/time fields
  • Automatic post_type configuration

🌍 Multilingual Support

All prompts include:

  • Multi-language field label generation
  • Support for RTL languages (Arabic, Hebrew)
  • Language detection from user input
  • Automatic label translation when target language is specified

🔧 Technical Details

Integration Detection:

// WooCommerce
class_exists('WooCommerce')

// Easy Digital Downloads
class_exists('Easy_Digital_Downloads')

// The Events Calendar
class_exists('Tribe__Events__Main')

API Response Format:

{
"success": true,
"integrations": [
{
"id": "woocommerce",
"label": "WooCommerce Product Form",
"active": true
}
]
}

✅ Testing Checklist

  •  Integration selector shows only when plugins are active
  •  AI generates correct field structure for each integration
  •  post_type is set correctly in form settings
  •  WooCommerce meta fields use is_meta: "yes"
  •  Event dates use proper date/time pickers
  •  Multilingual labels work correctly
  •  Fallback to regular form when no integration selected
  •  REST API endpoint returns correct integrations

🚀 Ready for Review

This feature significantly enhances the AI Form Builder by providing intelligent, plugin-specific form generation that reduces setup time and ensures compatibility with popular WordPress eCommerce and events plugins.

 

Branch: feat/integration-specific-ai-builder
Base: develop
Commits: 1 feature commit
Status: ✅ Ready for review


Summary by CodeRabbit

  • New Features

    • Integration selector UI and new API to list/support integrations (WooCommerce, EDD, Events Calendar); selection persists across generation and regenerations.
  • Improvements

    • Generation flow now includes and preserves integration context; improved request payloads, token handling, error parsing, and admin form-type exposure.
    • AI-provided form settings are merged with defaults for safer overrides.
  • Documentation

    • Added detailed AI prompt templates for WooCommerce, EDD, and Events Calendar.

✏️ Tip: You can customize this high-level summary in your review settings.

@arifulhoque7 arifulhoque7 self-assigned this Nov 28, 2025
@arifulhoque7 arifulhoque7 added needs: testing needs: dev review This PR needs review by a developer labels Nov 28, 2025
@coderabbitai
Copy link

coderabbitai bot commented Nov 28, 2025

Walkthrough

Adds integration-aware AI form generation: frontend integration selector and persistence, new REST route to list integrations, integration-aware system prompts and prompt files, merged AI settings helper, extended sanitization for AI-created fields, and admin form_type localization.

Changes

Cohort / File(s) Summary
Frontend: AI form flow
assets/js/components/AIFormBuilder.vue, assets/js/components/FormInputStage.vue, assets/js/components/FormSuccessStage.vue
Add initialIntegration prop, selectedIntegration state, integration selector UI, fetch GET /ai-form-builder/integrations; emit start-generation with integration; persist and pass integration into generation API; adjust payload/comment cleanup.
REST API & controller
includes/AI/RestController.php
Add integration parameter to generate endpoint (enum: '', woocommerce, edd, events_calendar); add GET /ai-form-builder/integrations route and get_integrations(); propagate integration into conversation_context and responses; map post_type → form_template; extend sanitize_form_fields with normalization/defaulting.
AI generation / prompts
includes/AI/FormGenerator.php, includes/AI/wpuf-ai-prompt-woocommerce.md, includes/AI/wpuf-ai-prompt-edd.md, includes/AI/wpuf-ai-prompt-events-calendar.md
Make system prompts integration-aware, select integration-specific prompt files, append version/language/context blocks, adjust max_tokens for integrations, add three new integration prompt files (WooCommerce, EDD, Events Calendar) with strict JSON/form templates.
Form builder settings
includes/AI/Form_Builder.php
Add merge_form_settings($ai_settings) to merge AI-provided form_settings over defaults and route build_form through this helper.
AI Manager / Admin localization
includes/AI_Manager.php
Determine runtime formType for admin, sanitize page checks, and expose formType in localization payload and admin-footer fallback.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

needs: dev review, needs: testing

Suggested reviewers

  • sapayth

Poem

🐇 I hopped through prompts with a curious twitch,

picked Woo, EDD, Events from my carrot-rich niche.
JSON seeds planted, tidy and bright,
forms sprout in rows by moon and by light.
Hop, merge, celebrate — code done just right.

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Feat/integration specific ai builder' refers to a real and substantial part of the changeset, but uses a vague phrasing ('integration specific ai builder') that doesn't clearly convey the main feature. Consider a more descriptive title such as 'Add integration-specific AI form templates for WooCommerce, EDD, and Events Calendar' to clearly indicate which integrations are supported and what the feature enables.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
includes/AI_Manager.php (1)

106-114: Consider sanitizing $_GET['page'] input.

While this code runs in an authenticated admin context and the value is only used for comparison (not stored or output), it's good practice to sanitize superglobal access. The static analysis tool flagged this for nonce verification, but since this is just determining context during script enqueueing (not processing a form submission), nonce verification isn't strictly necessary here.

Apply this diff for improved defensive coding:

         // Determine form type based on current admin page
         $form_type = 'post'; // Default to post
         if ( isset( $_GET['page'] ) ) {
-            if ( 'wpuf-profile-forms' === $_GET['page'] ) {
+            $page = sanitize_text_field( wp_unslash( $_GET['page'] ) );
+            if ( 'wpuf-profile-forms' === $page ) {
                 $form_type = 'profile';
-            } elseif ( 'wpuf-post-forms' === $_GET['page'] ) {
+            } elseif ( 'wpuf-post-forms' === $page ) {
                 $form_type = 'post';
             }
         }
includes/AI/RestController.php (2)

489-496: Remove unused loop variable $key.

The static analysis correctly identified that $key is unused in the foreach loop.

Apply this diff:

         // Filter integrations based on form type and enabled status
         $available_integrations = [];
-        foreach ( $all_integrations as $key => $integration ) {
+        foreach ( $all_integrations as $integration ) {
             // Only include if enabled and supports the current form type
             if ( $integration['enabled'] && in_array( $form_type, $integration['form_types'], true ) ) {
                 $available_integrations[] = $integration;
             }
         }

462-487: Consider caching integration availability checks.

The class_exists checks for WooCommerce, EDD, and Events Calendar run on every API request. While these are fast operations, consider caching the result using a transient if this endpoint is called frequently.

This is a minor optimization that could be deferred. The current implementation is functionally correct.

assets/js/components/FormInputStage.vue (2)

271-342: Consider extracting default prompts to reduce duplication.

The default post form prompts (lines 323-340) duplicate the initial prompts in data() (lines 148-165). Consider extracting to a constant or shared method for maintainability.

// At the top of the script, before export default:
const DEFAULT_POST_PROMPTS = {
    templates: [
        { id: 'paid_guest_post', label: 'Paid Guest Post' },
        // ... other templates
    ],
    instructions: {
        paid_guest_post: 'Create a Paid Guest Post submission form...',
        // ... other instructions
    }
};

// Then use in both data() and updatePromptTemplates():
// this.promptTemplates = DEFAULT_POST_PROMPTS.templates.map(t => ({...t, label: this.__(t.label, 'wp-user-frontend')}));

187-190: Consider using loadingIntegrations state in the UI.

The loadingIntegrations state is tracked but not reflected in the UI. Consider showing a loading indicator or disabling the select while loading.

 <select
     v-model="selectedIntegration"
+    :disabled="loadingIntegrations"
     class="..."
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47b6597 and ce96227.

📒 Files selected for processing (9)
  • assets/js/components/AIFormBuilder.vue (4 hunks)
  • assets/js/components/FormInputStage.vue (5 hunks)
  • includes/AI/FormGenerator.php (2 hunks)
  • includes/AI/Form_Builder.php (1 hunks)
  • includes/AI/RestController.php (5 hunks)
  • includes/AI/wpuf-ai-prompt-edd.md (1 hunks)
  • includes/AI/wpuf-ai-prompt-events-calendar.md (1 hunks)
  • includes/AI/wpuf-ai-prompt-woocommerce.md (1 hunks)
  • includes/AI_Manager.php (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
includes/AI/FormGenerator.php (1)
wpuf-functions.php (1)
  • wpuf_is_pro_active (4988-4990)
🪛 GitHub Check: Run PHPCS inspection
includes/AI_Manager.php

[warning] 111-111:
Processing form data without nonce verification.


[warning] 109-109:
Processing form data without nonce verification.


[warning] 108-108:
Processing form data without nonce verification.

🪛 LanguageTool
includes/AI/wpuf-ai-prompt-woocommerce.md

[uncategorized] ~423-~423: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

includes/AI/wpuf-ai-prompt-events-calendar.md

[grammar] ~143-~143: Use a hyphen to join words.
Context: ...y-mm-dd", "time": "yes" } ### All Day Event:json { "template": "chec...

(QB_NEW_EN_HYPHEN)


[uncategorized] ~365-~365: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

includes/AI/wpuf-ai-prompt-edd.md

[uncategorized] ~282-~282: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

🪛 PHPMD (2.15.0)
includes/AI/RestController.php

491-491: Avoid unused local variables such as '$key'. (undefined)

(UnusedLocalVariable)

🔇 Additional comments (19)
includes/AI_Manager.php (1)

116-129: LGTM!

The formType is correctly added to the localization data, enabling the frontend to determine which integrations to display based on the current form context.

includes/AI/Form_Builder.php (2)

78-78: LGTM!

The call to merge_form_settings correctly passes the AI settings with a null-coalescing fallback to an empty array, ensuring the merge logic handles both present and absent settings gracefully.


82-93: LGTM!

The merge_form_settings helper is well-implemented. Using array_merge correctly gives AI-provided settings precedence over defaults. This approach is clean and follows the single responsibility principle.

includes/AI/FormGenerator.php (2)

708-709: Consider using the existing helper function consistently.

The code uses function_exists( 'wpuf_is_pro_active' ) && wpuf_is_pro_active() here, which is correct. This pattern is safe since the function is defined in wpuf-functions.php. The defensive check is appropriate.


742-765: LGTM!

The Pro version guidance is correctly scoped to integration forms only, providing context-aware field recommendations. The WooCommerce and Events Calendar specific notes help the AI generate appropriate field types based on the plugin version.

includes/AI/wpuf-ai-prompt-woocommerce.md (3)

34-54: LGTM!

The form_settings with post_type: "product" is correctly documented as mandatory for WooCommerce forms. The example JSON structure is clear and matches the expected format.


56-64: Good emphasis on WooCommerce-specific taxonomies.

The critical notes about using product_cat and product_tag instead of generic WordPress taxonomies are important for correct form generation. This guidance will help prevent common integration issues.


265-275: Based on the verification attempt, I've encountered limitations in accessing the repository directly. However, the web search results provide some insight:

The web search indicates that numeric_text_field is available in both WP User Frontend and WP User Frontend Pro, suggesting it may not be an exclusive Pro feature. However, the results are somewhat ambiguous about the distinction between free and Pro availability.

Since I cannot access the file to verify:

  1. Whether the prompt header actually marks this as a Pro field
  2. How the pricing field documentation handles Pro guidance
  3. The document's overall scope and audience

I cannot definitively confirm or refute the original review comment's concern.


Manual verification is needed to confirm whether numeric_text_field for Stock Quantity is documented as Pro-only and whether comparable Pro-feature guidance exists for other fields in this prompt file.

includes/AI/RestController.php (3)

101-107: LGTM!

The integration parameter is properly defined with validation (enum), sanitization, and sensible defaults. The empty string in the enum allows for "no integration" selection.


145-159: LGTM!

The new /integrations endpoint is correctly registered with proper permission callback and form_type filtering parameter. The enum validation ensures only valid form types are accepted.


305-308: LGTM!

The integration is correctly propagated into the conversation context when provided, enabling the FormGenerator to select the appropriate integration-specific prompt.

includes/AI/wpuf-ai-prompt-edd.md (1)

1-325: LGTM! Comprehensive EDD prompt template.

The prompt correctly enforces EDD-specific requirements including post_type: "download", EDD taxonomies (download_category, download_tag), and meta fields (edd_price, edd_download_files, edd_product_notes). The JSON examples are valid and the documentation is thorough.

assets/js/components/AIFormBuilder.vue (2)

8-14: LGTM! Integration prop and event handling properly wired.

The bi-directional binding for selectedIntegration between parent and child components is correctly implemented using the prop and event pattern.


115-143: LGTM! API call correctly handles optional integration parameter.

The integration parameter is conditionally added to the request body only when provided, maintaining backward compatibility.

includes/AI/wpuf-ai-prompt-events-calendar.md (1)

1-53: Well-structured Events Calendar prompt template.

The prompt correctly enforces TEC-specific requirements including post_type: "tribe_events", proper taxonomy usage (tribe_events_cat), and meta field conventions with _Event prefix.

assets/js/components/FormInputStage.vue (4)

30-53: LGTM! Integration selector UI implementation.

The selector is conditionally rendered only for post forms with available integrations, uses appropriate form styling, and includes helpful description text.


223-255: LGTM! Integration fetching with proper error handling.

The fetch logic correctly handles the REST API call with appropriate headers, checks response status, and gracefully handles errors without breaking the UI.


257-269: LGTM! Clean state management on integration change.

Properly clears prompt selection and form description when integration changes, ensuring a clean slate for the new integration's prompts.


364-372: LGTM! Generation payload includes integration.

The start-generation event correctly includes the selected integration alongside the description and prompt.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@Rubaiyat-E-Mohammad
Copy link
Contributor

Rubaiyat-E-Mohammad commented Dec 2, 2025

@arifulhoque7 vai

  • Issue 1:

2 fields are missing for all kind of woocommerce form
image

  • Issues 2

2 fields are missing for digital product form
image

  • Issue 3

While regenerating form, it's not loading woocommerce or edd templates automatically as pre-selected

Screen.Recording.2025-12-02.at.4.08.23.PM.mov
  • Issue 4

2 fields are missing for digital downloads form
image

  • Issue 5

Unnecessary field (product tag) for product form according to manual woo tmplate creation
image

arifulhoque7 and others added 2 commits December 26, 2025 10:05
Enhances integration persistence in the AI form builder, improves loading and selection UX for integrations, and updates prompt templates for WooCommerce, EDD, and Events Calendar to clarify required fields and template structure. Increases token limits for integration forms, adds detailed logging for AI requests and JSON errors, and ensures integration is included in API responses for regeneration. Also refines admin page detection and sanitization in AI_Manager.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
includes/AI_Manager.php (1)

106-115: Sanitized formType wiring looks good; consider silencing PHPCS false-positive on $_GET.

The new form_type detection and propagation into formType are correctly sanitized and restricted to read-only admin context, and the broader page substring check is reasonable for deciding when to inject the AI builder config.

PHPCS’ “nonce verification” warnings here are noise because no state change is performed; if they bother CI, you could add a targeted // phpcs:ignore WordPress.Security.NonceVerification.Recommended with a short comment explaining it’s a read-only admin-page check.

Also applies to: 123-123, 165-169

includes/AI/RestController.php (1)

101-107: Integration plumbing for generation looks solid; ensure modify‑form keeps using the same integration.

  • Adding the integration arg to /generate, validating via enum, and sanitizing with sanitize_text_field is correct.
  • /ai-form-builder/integrations cleanly exposes only enabled integrations for the requested form_type and uses class_exists() checks in a cheap, safe way.
  • generate_form()’s injection of $integration into $conversation_context and echoing it back in $result['integration'] is exactly what the frontend needs to persist integration across regenerations.

One thing to double‑check: modify_form_from_ai() currently only passes $modification_context (with current_form etc.) and a form_type, but no explicit integration parameter. For integration‑specific forms, you’ll want the frontend to include the integration value inside modification_data.conversation_context so that get_system_prompt() can still select the WooCommerce / EDD / Events Calendar prompt during modifications instead of falling back to the minimal post prompt.

Also applies to: 145-159, 283-288, 305-309, 334-337, 453-508

includes/AI/FormGenerator.php (1)

588-598: Google integration token handling is fine; consider gating debug error_log() calls.

Using a higher max token budget (4000) when context.integration is present makes sense for large integration templates, and the fallback to options.max_tokens || 2000 otherwise is safe.

However, the new error_log() calls that run on every Google request (model, tokens, integration) plus the extra logs on JSON decode failure will quickly clutter logs on busy sites. It would be better to:

  • Wrap these logs in a check like if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) or a plugin‑specific debug flag, and/or
  • Keep the detailed logs only in the error path (JSON decode failure), not for all successful calls.

This preserves the diagnostics you need without spamming production logs.

Also applies to: 609-613, 665-670

assets/js/components/FormInputStage.vue (1)

30-62: Integration selector and prompt plumbing are well‑wired; minor optional hardening.

  • The integration dropdown for post forms, backed by availableIntegrations from /ai-form-builder/integrations, is a clean UX and respects loading state.
  • initialIntegrationselectedIntegrationupdate:selectedIntegration keeps parent and child in sync, and updatePromptTemplates() swaps in the correct prompt set for WooCommerce, EDD, or Events Calendar (or falls back to generic post prompts).
  • startGeneration() now includes integration: this.selectedIntegration in the emitted payload, which lines up with the backend changes and AIFormBuilder’s API call.

Optional: after fetchAvailableIntegrations() resolves, you could clear selectedIntegration if its value isn’t present in availableIntegrations anymore (e.g., plugin deactivated between runs) to avoid a dropdown value that no longer exists, but this is a minor edge case.

Also applies to: 116-119, 178-184, 187-198, 221-267, 269-340, 365-369

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ce96227 and 65ffeac.

📒 Files selected for processing (8)
  • assets/js/components/AIFormBuilder.vue
  • assets/js/components/FormInputStage.vue
  • includes/AI/FormGenerator.php
  • includes/AI/RestController.php
  • includes/AI/wpuf-ai-prompt-edd.md
  • includes/AI/wpuf-ai-prompt-events-calendar.md
  • includes/AI/wpuf-ai-prompt-woocommerce.md
  • includes/AI_Manager.php
🧰 Additional context used
🧬 Code graph analysis (1)
includes/AI/FormGenerator.php (1)
wpuf-functions.php (1)
  • wpuf_is_pro_active (5042-5044)
🪛 GitHub Check: Run PHPCS inspection
includes/AI_Manager.php

[warning] 109-109:
Processing form data without nonce verification.


[warning] 108-108:
Processing form data without nonce verification.


[warning] 166-166:
Processing form data without nonce verification.


[warning] 165-165:
Processing form data without nonce verification.

🪛 LanguageTool
includes/AI/wpuf-ai-prompt-edd.md

[uncategorized] ~297-~297: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

includes/AI/wpuf-ai-prompt-events-calendar.md

[grammar] ~143-~143: Use a hyphen to join words.
Context: ...y-mm-dd", "time": "yes" } ### All Day Event:json { "template": "chec...

(QB_NEW_EN_HYPHEN)


[uncategorized] ~368-~368: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

includes/AI/wpuf-ai-prompt-woocommerce.md

[uncategorized] ~426-~426: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

🔇 Additional comments (5)
includes/AI/wpuf-ai-prompt-edd.md (1)

1-340: EDD prompt template looks consistent; please re‑verify against the manual EDD form used in QA.

The canonical EDD template (title, category, description, excerpt, edd_price, featured image, edd_product_notes, edd_download_files) plus explicit post_type: "download" and download_category/download_tag rules is thorough and should address the “missing fields” issues for digital downloads.

Given the earlier QA screenshots about 2 missing EDD fields, please double‑check that this “EXACT EDD TEMPLATE STRUCTURE” matches your hand‑built EDD form (field list, order, and required flags), and adjust the template if QA still expects any additional defaults (e.g., tags or extra meta).

includes/AI/wpuf-ai-prompt-woocommerce.md (1)

1-466: WooCommerce prompt now matches an explicit standard template and de‑emphasizes tags—good fix for the extra tag field.

The “EXACT WOOCOMMERCE TEMPLATE STRUCTURE” plus the note that product_cat/product_tag are not part of the standard template (tags only when explicitly requested) should prevent the unwanted “Product Tag” field QA reported, while still allowing tags when the user asks for them.

As with EDD, it’s worth re‑confirming that this 10‑field standard template (including catalog visibility, purchase note, and reviews) matches your hand‑configured WooCommerce form so the previously missing fields are fully covered.

includes/AI/FormGenerator.php (1)

721-785: Integration‑aware system prompt selection and Pro/Free guidance look correct and resilient.

  • Reading $context['integration'] and using an integration→prompt map with a file_exists() check ensures WooCommerce/EDD/Events Calendar prompts are used when available, with a clean fallback to the minimal prompt.
  • The added final else branch that falls back to the minimal prompt for unexpected form_type values addresses the earlier uninitialized $prompt_file risk from the previous review.
  • Appending a “WPUF VERSION INFO” section only for integration forms, with wpuf_is_pro_active() gating, is a good way to steer the model toward the right field types (e.g., numeric_text_field for Pro vs text_field on Free) without changing non‑integration behavior.

Overall this makes prompt selection deterministic for all combinations of form_type and integration.

includes/AI/wpuf-ai-prompt-events-calendar.md (1)

1-412: TEC prompt is coherent and the Event Address example is now well‑formed.

The Events Calendar prompt correctly enforces tribe_events_cat, standard post_tags, and TEC meta keys like _EventStartDate/_EventEndDate/_EventCost, and the post_type: "tribe_events" requirement.

The previously broken “Event Address” example is now a valid JSON code block, which should help keep provider responses consistent and parsable.

assets/js/components/AIFormBuilder.vue (1)

8-15: Integration state is correctly persisted across generation and regeneration.

  • selectedIntegration is now a first‑class piece of state, fed into FormInputStage as initialIntegration and kept in sync via @update:selectedIntegration.
  • handleStartGeneration stores data.integration and passes it through to callAIFormGenerationAPI, which conditionally includes integration in the JSON payload.
  • On a successful response, the backend’s result.data.integration is written back to selectedIntegration, so the chosen integration survives the full round‑trip.
  • regenerateForm() resets description and prompt but intentionally does not clear selectedIntegration, ensuring the integration selector remains pre‑selected on the next input stage.

This wiring should resolve the “integration template not pre‑selected on regenerate” behavior from QA, at least at the integration dropdown level.

Also applies to: 59-81, 98-107, 115-143, 199-203, 696-701

@arifulhoque7
Copy link
Contributor Author

@Rubaiyat-E-Mohammad vai, now check please

@Rubaiyat-E-Mohammad
Copy link
Contributor

Rubaiyat-E-Mohammad commented Dec 29, 2025

@arifulhoque7 vai

  • Issue 1:

2 fields are missing for all kind of woocommerce form image

  • Issues 2

2 fields are missing for digital product form image

  • Issue 3

While regenerating form, it's not loading woocommerce or edd templates automatically as pre-selected

Screen.Recording.2025-12-02.at.4.08.23.PM.mov

  • Issue 4

2 fields are missing for digital downloads form image

  • Issue 5

Unnecessary field (product tag) for product form according to manual woo tmplate creation image

2 issues (unchecked) are still remaining here. @arifulhoque7 vai

@arifulhoque7
Copy link
Contributor Author

Member

these are optional fields , the required fields for woocommerce products are already attached with the form . @Rubaiyat-E-Mohammad vai

Expanded the AI instructions for WooCommerce Digital Product forms to include Downloadable Product and Downloadable Files fields.
@arifulhoque7
Copy link
Contributor Author

@arifulhoque7 vai

  • Issue 1:

2 fields are missing for all kind of woocommerce form image

  • Issues 2

2 fields are missing for digital product form image

  • Issue 3

While regenerating form, it's not loading woocommerce or edd templates automatically as pre-selected
Screen.Recording.2025-12-02.at.4.08.23.PM.mov

  • Issue 4

2 fields are missing for digital downloads form image

  • Issue 5

Unnecessary field (product tag) for product form according to manual woo tmplate creation image

2 issues (unchecked) are still remaining here. @arifulhoque7 vai

@Rubaiyat-E-Mohammad vai, issue-2 is fixed now please check

@arifulhoque7 arifulhoque7 removed the bug label Dec 29, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
assets/js/components/FormInputStage.vue (2)

221-253: Consider using URLSearchParams for URL construction.

The integration fetching logic is solid with proper loading state management and response validation. However, there are two areas for improvement:

  1. URL construction (line 234): Using string concatenation could be problematic if formType contains special characters. Consider using URLSearchParams:
const params = new URLSearchParams({ form_type: this.formType });
const response = await fetch(`${restUrl}wpuf/v1/ai-form-builder/integrations?${params}`, {
  1. Silent error handling (line 249): Errors are logged to console but not displayed to users. The integration selector will simply not appear if the fetch fails. This provides graceful degradation but could be improved with user-facing feedback.
🔎 Proposed refactor with URLSearchParams and optional error feedback
         async fetchAvailableIntegrations() {
             // Only fetch integrations for post forms
             if (this.formType !== 'post') {
                 return;
             }
 
             this.loadingIntegrations = true;
 
             try {
                 const config = window.wpufAIFormBuilder || {};
                 const restUrl = config.rest_url || (window.location.origin + '/wp-json/');
                 const nonce = config.nonce || '';
 
-                const response = await fetch(restUrl + 'wpuf/v1/ai-form-builder/integrations?form_type=' + this.formType, {
+                const params = new URLSearchParams({ form_type: this.formType });
+                const response = await fetch(`${restUrl}wpuf/v1/ai-form-builder/integrations?${params}`, {
                     method: 'GET',
                     headers: {
                         'Content-Type': 'application/json',
                         'X-WP-Nonce': nonce
                     }
                 });
 
                 if (response.ok) {
                     const result = await response.json();
                     if (result.success && result.integrations) {
                         this.availableIntegrations = result.integrations;
                     }
                 }
             } catch (error) {
                 console.error('Error fetching integrations:', error);
+                // Optionally, set an error flag or show user feedback here
             } finally {
                 this.loadingIntegrations = false;
             }
         },

255-267: Consider adding a clarifying comment.

The integration change handler correctly updates prompt templates and clears the form state to prevent confusion with mismatched integration-specific prompts. The logic is sound, but adding a brief comment would improve maintainability:

🔎 Suggested comment for clarity
         onIntegrationChange() {
             // Update prompt templates based on selected integration
             this.updatePromptTemplates();
             
-            // Clear current prompt selection when integration changes
+            // Clear current prompt selection and description when integration changes
+            // to prevent mismatched integration-specific content
             this.selectedPrompt = '';
             this.formDescription = '';
             
             // Emit the selected integration to parent
             this.$emit('update:selectedIntegration', this.selectedIntegration);
             this.$emit('update:selectedPrompt', '');
             this.$emit('update:formDescription', '');
         },
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65ffeac and 823c842.

📒 Files selected for processing (1)
  • assets/js/components/FormInputStage.vue
🔇 Additional comments (5)
assets/js/components/FormInputStage.vue (5)

30-62: LGTM! Clean integration selector UI with proper loading states.

The integration selector is well-implemented with:

  • Appropriate conditional rendering (post forms only)
  • Clear loading states with spinner
  • Good accessibility (label, disabled state)
  • Helpful descriptive text

The selector will gracefully hide if no integrations are available, which provides a smooth fallback experience.


116-119: LGTM! Proper integration state initialization.

The new initialIntegration prop and related data properties are well-structured:

  • Standard prop definition with appropriate defaults
  • Post form prompts correctly deferred to mounted() for integration-aware initialization
  • State properties follow Vue conventions

Also applies to: 157-160, 180-184


187-198: LGTM! Proper component initialization flow.

The mounted() hook correctly:

  • Fetches available integrations
  • Preserves initial integration state by emitting to parent
  • Initializes prompt templates for post forms

The sequence handles the regeneration use case mentioned in PR comments (Issue 3), assuming the parent component correctly passes initialIntegration during regeneration.


269-340: LGTM! Well-structured prompt templates for each integration.

The updatePromptTemplates() method provides appropriate prompt options for each integration:

  • WooCommerce: Product-focused prompts (Simple, Digital, Service, Handmade)
  • EDD: Download-focused prompts (Digital Download, Software, eBook, Course)
  • Events Calendar: Event-focused prompts (Conference, Workshop, Meetup, Webinar)
  • Default: General post prompts with good variety

The AI instruction strings appropriately reference integration-specific fields (e.g., WooCommerce price fields, EDD downloadable files, Events Calendar venue/date fields).

Note: Based on PR reviewer comments (Issues 1, 2, 4, 5) about missing fields in generated forms, the actual field completeness depends on the backend .md prompt files rather than these short instruction strings.


362-370: LGTM! Payload correctly includes integration context.

The startGeneration method now properly passes integration context to the backend:

  • Uses optional chaining (selectedPrompt?.id) to safely handle different data types
  • Includes integration field to enable integration-specific form generation
  • Maintains backward compatibility with fallback chain

This change enables the backend to select the appropriate integration-specific prompt file for AI generation.

@Rubaiyat-E-Mohammad
Copy link
Contributor

The downloadable product field is a radio field with yes & no options. but showing a checkbox @arifulhoque7 vai
image

Enhanced WooCommerce integration by adding support for digital product fields in Pro mode. Updated system prompts and documentation to include 'Downloadable Product' (radio_field) and 'Downloadable Files' (file_upload) as Pro-only fields, with clear instructions and JSON templates for their usage.
@arifulhoque7
Copy link
Contributor Author

The downloadable product field is a radio field with yes & no options. but showing a checkbox @arifulhoque7 vai image

Now it should be fixed @Rubaiyat-E-Mohammad vai, check this

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
includes/AI/FormGenerator.php (4)

589-598: Appropriate token allocation for integration forms.

The logic correctly allocates higher token limits for integration forms (4000 vs 2000), which is necessary given the increased complexity and field count of WooCommerce/EDD/Events Calendar forms.

The implementation properly respects the model configuration's token parameter location (line 597).

Optional: Consider making token limits configurable

If different integrations have varying complexity, you might want to make the token limit configurable per integration:

// Optional: Integration-specific token limits
$integration_token_limits = [
    'woocommerce' => 4000,
    'edd' => 3500,
    'events_calendar' => 4000,
];

if ( ! empty( $context['integration'] ) ) {
    $max_tokens = $integration_token_limits[$context['integration']] ?? 4000;
} else {
    $max_tokens = intval($options['max_tokens'] ?? 2000);
}

However, the current uniform approach is simpler and likely sufficient.


609-612: Consider conditional debug logging.

The debug logging is helpful for troubleshooting but runs unconditionally on every request, which could impact performance and fill logs on production sites.

Wrap debug logs in a conditional check
+if ( defined('WP_DEBUG') && WP_DEBUG ) {
     // Log request details for debugging
     error_log('WPUF AI: Google AI Request - Model: ' . $this->current_model);
     error_log('WPUF AI: Google AI Request - Max Tokens: ' . ($body['generationConfig'][$model_config['token_param']] ?? 'not set'));
     error_log('WPUF AI: Google AI Request - Integration: ' . ($context['integration'] ?? 'none'));
+}

Alternatively, add a dedicated debug flag in WPUF settings to allow granular control.


666-669: Potential sensitive data in error logs.

The enhanced error logging helpfully captures response content for debugging, but could inadvertently log sensitive user data (form field values, PII) if the AI response contains such information.

Consider one of these approaches:

  1. Add a warning comment indicating that logs may contain sensitive data and should be secured
  2. Further truncate to just the first 100-200 characters rather than 500
  3. Sanitize the content before logging by removing potential PII patterns
  4. Make it conditional on a debug flag similar to the other logging

Example:

+// Note: Only log in debug mode to prevent sensitive data exposure
+if ( defined('WP_DEBUG') && WP_DEBUG ) {
     // Log the actual response for debugging
     error_log('WPUF AI: Invalid JSON from Google AI. Error: ' . json_last_error_msg());
-    error_log('WPUF AI: Raw content: ' . substr($content, 0, 500));
-    error_log('WPUF AI: Cleaned JSON: ' . substr($json_content, 0, 500));
+    error_log('WPUF AI: Raw content: ' . substr($content, 0, 200));
+    error_log('WPUF AI: Cleaned JSON: ' . substr($json_content, 0, 200));
+}

762-787: Comprehensive PRO/FREE context for integration forms.

The PRO version status context appropriately guides the AI based on the active WPUF version:

PRO active path (lines 765-774):

  • Enables advanced fields like numeric_text_field, phone_field, address_field
  • For WooCommerce: Includes downloadable product fields (radio_field for _downloadable, file_upload for _woo_files)
  • Aligns with the WooCommerce prompt specifications reviewed earlier

FREE version path (lines 775-786):

  • Restricts to basic field types (text_field, textarea_field, etc.)
  • For WooCommerce: Excludes downloadable product fields and uses text_field instead of numeric_text_field for pricing
  • Provides clear guidance to prevent the AI from generating unsupported fields

The integration-specific guidance ensures forms are generated with appropriate field types for the user's license level.

Optional: Extract field type mappings to constants

For maintainability, consider extracting the field type lists to class constants:

private const PRO_FIELDS = [
    'numeric_text_field',
    'phone_field',
    'country_list_field',
    'address_field',
    // ...
];

private const FREE_FIELDS = [
    'text_field',
    'textarea_field',
    'dropdown_field',
    // ...
];

However, the current inline approach is clear and sufficient.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 823c842 and 9010e34.

📒 Files selected for processing (2)
  • includes/AI/FormGenerator.php
  • includes/AI/wpuf-ai-prompt-woocommerce.md
🧰 Additional context used
🧬 Code graph analysis (1)
includes/AI/FormGenerator.php (1)
wpuf-functions.php (1)
  • wpuf_is_pro_active (5042-5044)
🪛 LanguageTool
includes/AI/wpuf-ai-prompt-woocommerce.md

[uncategorized] ~531-~531: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...ur form" or ANY other text - DO NOT use markdown code blocks (no ```) - DO NOT add expla...

(MARKDOWN_NNP)

🔇 Additional comments (5)
includes/AI/wpuf-ai-prompt-woocommerce.md (4)

1-315: LGTM! Comprehensive prompt structure with clear WooCommerce guidance.

The prompt template is well-structured with:

  • Clear role definition and multilingual support (lines 1-14)
  • Explicit template structure emphasizing required fields (lines 15-34)
  • Critical emphasis on correct WooCommerce taxonomies (product_cat, product_tag) to prevent common mistakes (lines 58-66)
  • Extensive field examples with proper meta field configuration

The instructions are detailed and should help the AI generate accurate WooCommerce forms.


316-347: Correct field type for downloadable products.

The PRO-only fields are properly specified:

  • Line 318 correctly emphasizes using radio_field (not checkbox_field) for the Downloadable Product field with yes/no options
  • The implementation example (lines 319-332) matches the specification
  • This aligns with the PR comments indicating this was corrected based on reviewer feedback

The emphatic warnings should help prevent the AI from generating incorrect field types.


445-515: Complete and consistent PRO template.

The Digital Product Form template is well-structured:

  • Correctly reiterates the radio_field requirement at line 447
  • Shows proper implementation within a complete form context (lines 492-502)
  • Includes all necessary PRO fields with correct configuration
  • Provides a working reference for the AI to follow

The repeated emphasis on field types ensures consistency throughout the prompt.


517-572: Clear response format rules with appropriate emphasis.

The response format and final rules are well-defined:

  • JSON formatting rules (lines 517-535) are explicit and should prevent malformed responses
  • The final rules section (560-572) provides a comprehensive checklist
  • Line 572 correctly reinforces the radio_field requirement for downloadable products

Note: The static analysis hint about "markdown" vs "Markdown" on line 531 is a false positive—the lowercase usage is intentional and contextually appropriate.

includes/AI/FormGenerator.php (1)

722-752: Well-structured integration-aware prompt selection.

The prompt selection logic correctly handles all form types with appropriate fallbacks:

  • Lines 729-731: Profile/registration forms use dedicated registration prompt
  • Lines 732-745: Post forms with integration use integration-specific prompts (WooCommerce, EDD, Events Calendar) with fallback to minimal prompt if integration prompt doesn't exist
  • Lines 746-748: Post forms without integration use minimal prompt
  • Lines 749-751: Fallback for unexpected form types (addresses previous review concern)

The defensive programming is solid:

  • PRO detection uses function_exists check (line 726)
  • Integration prompts validated with file_exists (line 741)
  • File existence confirmed before loading (line 755)

Note: The fallback at lines 749-751 addresses the previous review comment about potential uninitialized $prompt_file for unexpected form types.

@Rubaiyat-E-Mohammad
Copy link
Contributor

Rubaiyat-E-Mohammad commented Dec 30, 2025

The price field for the WooCommerce product form is not saving the price while the form is created with AI. @arifulhoque7 vai
image

Adds logic to assign the form_template field in form settings based on the post_type, ensuring proper integration with plugins like WooCommerce, EDD, and The Events Calendar. Introduces a private get_form_template_for_post_type() method to map post types to their corresponding form templates, allowing integrations to correctly trigger their hooks and save meta fields.
@arifulhoque7
Copy link
Contributor Author

The price field for the WooCommerce product form is not saving the price while the form is created with AI. @arifulhoque7 vai image

fixed @Rubaiyat-E-Mohammad vai

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9010e34 and 29e154c.

📒 Files selected for processing (1)
  • includes/AI/RestController.php
🔇 Additional comments (6)
includes/AI/RestController.php (6)

101-107: LGTM! Integration parameter properly defined.

The integration parameter follows WordPress REST API best practices with proper validation, sanitization, and enum constraints.


287-287: LGTM! Integration properly extracted and propagated.

The integration parameter is correctly extracted and conditionally added to the conversation context for downstream processing.

Also applies to: 305-308


334-337: LGTM! Integration persisted for regeneration flow.

Adding the integration to the response ensures the frontend can maintain the selected integration when regenerating forms.


145-159: LGTM! Integrations endpoint properly registered.

The endpoint follows WordPress REST API conventions with appropriate permission checks and parameter validation.


1344-1351: LGTM! Consistent form_template handling in update path.

The logic correctly mirrors the implementation in create_form_from_ai, ensuring that form template mapping is applied consistently during both creation and modification flows.


863-872: Implementation correctly enables WooCommerce price-saving via form templates.

The entire integration chain is properly implemented:

  1. ✓ AI sets post_type: 'product' in form_settings (verified in wpuf-ai-prompt-woocommerce.md)
  2. ✓ Code maps post_type: 'product'form_template: 'post_form_template_woocommerce' (line 867)
  3. form_template is saved to post_meta and retrieved during form submission (Form_Template.php:247)
  4. ✓ Template instance is instantiated and after_insert() is called on form submission (Form_Template.php:253, 262)
  5. ✓ WooCommerce's update_price() hook is triggered to update the _price meta field (Post_Form_Template_WooCommerce.php:292)

The reported price-saving issue should be resolved with this implementation.

Comment on lines +463 to +508
public function get_integrations(WP_REST_Request $request) {
$form_type = $request->get_param('form_type') ?? 'post';

// Define all possible integrations with their requirements
$all_integrations = [
'woocommerce' => [
'id' => 'woocommerce',
'label' => __( 'WooCommerce Product', 'wp-user-frontend' ),
'description' => __( 'Create WooCommerce product submission forms', 'wp-user-frontend' ),
'enabled' => class_exists( 'WooCommerce' ),
'form_types' => [ 'post' ],
'icon' => 'woocommerce'
],
'edd' => [
'id' => 'edd',
'label' => __( 'Easy Digital Downloads', 'wp-user-frontend' ),
'description' => __( 'Create EDD download submission forms', 'wp-user-frontend' ),
'enabled' => class_exists( 'Easy_Digital_Downloads' ),
'form_types' => [ 'post' ],
'icon' => 'download'
],
'events_calendar' => [
'id' => 'events_calendar',
'label' => __( 'The Events Calendar', 'wp-user-frontend' ),
'description' => __( 'Create event submission forms', 'wp-user-frontend' ),
'enabled' => class_exists( 'Tribe__Events__Main' ),
'form_types' => [ 'post' ],
'icon' => 'calendar'
]
];

// Filter integrations based on form type and enabled status
$available_integrations = [];
foreach ( $all_integrations as $integration ) {
// Only include if enabled and supports the current form type
if ( $integration['enabled'] && in_array( $form_type, $integration['form_types'], true ) ) {
$available_integrations[] = $integration;
}
}

return new WP_REST_Response([
'success' => true,
'integrations' => $available_integrations,
'form_type' => $form_type
], 200);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

WooCommerce plugin main class name class_exists detection

💡 Result:

Short answer: the main WooCommerce class is WooCommerce (global, root namespace). To detect it use class_exists('WooCommerce', false) or check the WC() function/woocommerce_loaded hook.

Example:

  • class_exists check:
    if ( class_exists( 'WooCommerce', false ) ) { /* WooCommerce loaded */ }

  • or prefer hooking into WooCommerce readiness:
    add_action( 'woocommerce_loaded', 'your_cb' );

Sources: WooCommerce plugin file (main class included as WooCommerce). [1][2][3]

References:
[1] WooCommerce plugin source / woocommerce.php (shows include_once and class_exists('WooCommerce', false)).
[2] WooCommerce developer docs — How to check if WooCommerce is active (recommend using woocommerce_loaded / woocommerce_init).
[3] WooCommerce code reference — class WooCommerce details.


🌐 Web query:

Easy Digital Downloads EDD main class name class_exists

💡 Result:

The EDD plugin's main class is Easy_Digital_Downloads — plugins/themes commonly check it with class_exists('Easy_Digital_Downloads'). Many integrations also check the helper function EDD() (function_exists('EDD')) as an alternative. [1][2]

Sources:

  • StackOverflow answer showing class_exists('Easy_Digital_Downloads') / function_exists('EDD'). [1]
  • Examples from plugin/theme docs/themes using class_exists('Easy_Digital_Downloads'). [2]

🌐 Web query:

The Events Calendar Tribe Events main class name Tribe__Events__Main

💡 Result:

Yes — the plugin's main PHP class is named Tribe__Events__Main (with double underscores). It's defined in src/Tribe/Main.php and replaces the old TribeEvents class (calling the old name will trigger a deprecation notice). [1][2]

Sources:
[1] The Events Calendar class reference — Tribe__Events__Main.
[2] Support thread explaining TribeEvents was renamed to Tribe__Events__Main.


Add false parameter to WooCommerce class_exists check.

The class names are correct, but the WooCommerce detection should use class_exists('WooCommerce', false) instead of class_exists('WooCommerce') to avoid unnecessary autoloading. The EDD and Events Calendar checks are correct as-is.

🤖 Prompt for AI Agents
In includes/AI/RestController.php around lines 463 to 508, the WooCommerce
detection currently calls class_exists('WooCommerce') which can trigger
autoloading; change only the 'enabled' value for the 'woocommerce' entry to use
class_exists('WooCommerce', false) so it checks for the class without attempting
to autoload, leaving the EDD and Events Calendar checks unchanged.

Comment on lines +1441 to +1462
/**
* Get form template for a given post type
*
* Maps integration post types to their corresponding form templates.
* This is critical for integrations to properly trigger their hooks
* (e.g., WooCommerce's update_price() hook to set _price meta).
*
* @since WPUF_SINCE
*
* @param string $post_type The post type
*
* @return string|null Form template identifier or null if no mapping exists
*/
private function get_form_template_for_post_type( $post_type ) {
$post_type_to_template_map = [
'product' => 'post_form_template_woocommerce', // WooCommerce products
'download' => 'post_form_template_edd', // Easy Digital Downloads
'tribe_events' => 'post_form_template_events_calendar', // The Events Calendar
];

return $post_type_to_template_map[ $post_type ] ?? null;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify form_template identifiers and @since placeholder

echo "=== Searching for WooCommerce template identifier ==="
rg -nP "post_form_template_woocommerce" -C2

echo -e "\n=== Searching for EDD template identifier ==="
rg -nP "post_form_template_edd" -C2

echo -e "\n=== Searching for Events Calendar template identifier ==="
rg -nP "post_form_template_events_calendar" -C2

echo -e "\n=== Searching for form_template usage pattern ==="
rg -nP "form_template.*=>" --type=php -C2 | head -50

echo -e "\n=== Searching for WPUF_SINCE constant ==="
rg -nP "WPUF_SINCE|define.*SINCE" --type=php -C1 | head -30

Repository: weDevsOfficial/wp-user-frontend

Length of output: 10484


🏁 Script executed:

#!/bin/bash
# Find version numbers and context for RestController.php

echo "=== Searching for @since tags in RestController.php ==="
rg -n "@since" includes/AI/RestController.php | head -20

echo -e "\n=== Checking for version constant or define ==="
rg -n "version|VERSION" includes/AI/RestController.php | head -10

echo -e "\n=== Check wpuf-functions.php for version context ==="
rg -n "define.*VERSION|WPUF_VERSION" --type=php | head -5

echo -e "\n=== Search for recent @since tags to infer current version ==="
rg -n "@since 4\." --type=php | tail -20

Repository: weDevsOfficial/wp-user-frontend

Length of output: 2737


Update @SInCE tag from placeholder to actual version.

The form template identifiers are correct and properly defined throughout the codebase. However, line 1448 contains a placeholder @since WPUF_SINCE that needs to be replaced with the actual version number 4.2.1 (matching other AI module methods).

-     * @since WPUF_SINCE
+     * @since 4.2.1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Get form template for a given post type
*
* Maps integration post types to their corresponding form templates.
* This is critical for integrations to properly trigger their hooks
* (e.g., WooCommerce's update_price() hook to set _price meta).
*
* @since WPUF_SINCE
*
* @param string $post_type The post type
*
* @return string|null Form template identifier or null if no mapping exists
*/
private function get_form_template_for_post_type( $post_type ) {
$post_type_to_template_map = [
'product' => 'post_form_template_woocommerce', // WooCommerce products
'download' => 'post_form_template_edd', // Easy Digital Downloads
'tribe_events' => 'post_form_template_events_calendar', // The Events Calendar
];
return $post_type_to_template_map[ $post_type ] ?? null;
}
/**
* Get form template for a given post type
*
* Maps integration post types to their corresponding form templates.
* This is critical for integrations to properly trigger their hooks
* (e.g., WooCommerce's update_price() hook to set _price meta).
*
* @since 4.2.1
*
* @param string $post_type The post type
*
* @return string|null Form template identifier or null if no mapping exists
*/
private function get_form_template_for_post_type( $post_type ) {
$post_type_to_template_map = [
'product' => 'post_form_template_woocommerce', // WooCommerce products
'download' => 'post_form_template_edd', // Easy Digital Downloads
'tribe_events' => 'post_form_template_events_calendar', // The Events Calendar
];
return $post_type_to_template_map[ $post_type ] ?? null;
}
🤖 Prompt for AI Agents
In includes/AI/RestController.php around lines 1441 to 1462, the docblock for
get_form_template_for_post_type uses a placeholder "@since WPUF_SINCE"; update
that tag to the actual version "4.2.1" to match other AI module methods, i.e.,
replace "@since WPUF_SINCE" with "@since 4.2.1" in the method's docblock and
keep the rest of the comment unchanged.

];

// Log request details for debugging
error_log('WPUF AI: Google AI Request - Model: ' . $this->current_model);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the error and console logs

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done @sapayth vai

session_id: this.getSessionId(),
form_type: config.formType || 'post', // Pass form type to API
provider: config.provider || 'openai'
// Note: temperature and max_tokens are now handled by backend based on model configuration
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this comment

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done @sapayth vai

@sapayth sapayth added needs: author reply This PR needs author feedback or code changes and removed needs: dev review This PR needs review by a developer labels Jan 1, 2026
arifulhoque7 and others added 2 commits January 1, 2026 14:52
Eliminated error_log debug statements from AIFormBuilder.vue, FormSuccessStage.vue, and FormGenerator.php to clean up code and prevent unnecessary logging in production. No functional changes were made.
@arifulhoque7 arifulhoque7 requested a review from sapayth January 1, 2026 09:11
@arifulhoque7 arifulhoque7 added needs: dev review This PR needs review by a developer needs: testing and removed bug needs: author reply This PR needs author feedback or code changes labels Jan 1, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29e154c and 1136ad4.

📒 Files selected for processing (3)
  • assets/js/components/AIFormBuilder.vue
  • assets/js/components/FormSuccessStage.vue
  • includes/AI/FormGenerator.php
✅ Files skipped from review due to trivial changes (1)
  • assets/js/components/FormSuccessStage.vue
🧰 Additional context used
🧬 Code graph analysis (1)
includes/AI/FormGenerator.php (1)
wpuf-functions.php (1)
  • wpuf_is_pro_active (5017-5019)
🔇 Additional comments (6)
includes/AI/FormGenerator.php (2)

712-742: LGTM! Comprehensive prompt selection logic with proper fallback.

The integration-aware prompt selection is well-structured:

  • Registration/profile forms correctly use the registration prompt
  • Post forms with integration select integration-specific prompts (WooCommerce, EDD, Events Calendar)
  • Proper fallback to minimal prompt for unexpected form types (lines 739-741) addresses the previous review concern
  • Defensive function_exists check for wpuf_is_pro_active() (line 716) prevents potential errors

752-777: LGTM! Clear Pro/Free version differentiation for integration forms.

The conditional Pro version messaging appropriately:

  • Limits version info to integration forms only (line 753)
  • Provides different field type guidance based on Pro status
  • Tailors guidance to specific integrations (WooCommerce vs Events Calendar)
  • Helps the AI generate forms compatible with the active version
assets/js/components/AIFormBuilder.vue (4)

8-8: LGTM! Clean integration state management setup.

The integration flow is properly wired:

  • selectedIntegration data property at the parent level (line 67)
  • Passed as initialIntegration prop to FormInputStage (line 8)
  • Updates captured via update:selectedIntegration event (line 13)

This enables integration persistence across the generation lifecycle.

Also applies to: 13-13, 67-67


98-106: LGTM! Correct integration handling in start generation flow.

The integration value is properly extracted from the event data (line 101) with a safe fallback to empty string, and correctly passed to the API generation call (line 106).


115-142: LGTM! Clean API request construction with optional integration.

The method signature accepts an optional integration parameter (line 115), and the request body conditionally includes it only when provided (lines 131-133). This prevents unnecessary empty integration values in API requests.


198-201: LGTM! Integration persistence across regeneration is correctly implemented.

The integration value is stored from the API response (lines 198-201) and intentionally preserved during regeneration (line 699 comment). This addresses the PR objective: "When regenerating a form, WooCommerce/EDD templates were not auto-selected as the pre-selected integration."

The asymmetry with selectedPrompt being cleared (line 698) while selectedIntegration persists is the intended behavior to maintain integration context across regenerations.

Also applies to: 696-699

Comment on lines +589 to 598
// Use higher token limit for integration forms (they have more fields)
if ( ! empty( $context['integration'] ) ) {
$max_tokens = 4000; // Integration forms need more tokens
} else {
$max_tokens = intval($options['max_tokens'] ?? 2000);
}

if ($model_config['token_location'] === 'generationConfig') {
$body['generationConfig'][$model_config['token_param']] = intval($options['max_tokens'] ?? 2000);
$body['generationConfig'][$model_config['token_param']] = $max_tokens;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Apply integration-aware token limits to all providers, not just Google.

Lines 589-594 set a higher token limit (4000) for integration forms when using Google, but OpenAI (lines 256-261) and Anthropic (lines 431-438) lack equivalent checks. Integration forms with many fields (WooCommerce, EDD, Events Calendar) likely need higher token limits across all providers to avoid truncated or incomplete responses.

🔎 Suggested fix: Add integration-aware token logic to OpenAI and Anthropic

For OpenAI (around line 256):

         // Set token parameter based on model
         if ($model_config['token_location'] === 'body') {
             // GPT-5 needs significantly more tokens for reasoning + output
             if (strpos($this->current_model, 'gpt-5') === 0) {
                 $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 65536);
+            } elseif ( ! empty( $context['integration'] ) ) {
+                // Integration forms need more tokens for many fields
+                $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 4000);
             } else {
                 $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 2000);
             }
         }

For Anthropic (around line 431):

         // Set token parameter based on model
         if ($model_config['token_location'] === 'body') {
             // GPT-5 needs significantly more tokens for reasoning + output
             if (strpos($this->current_model, 'gpt-5') === 0) {
                 $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 65536);
+            } elseif ( ! empty( $context['integration'] ) ) {
+                // Integration forms need more tokens for many fields
+                $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 4000);
             } else {
                 $body[$model_config['token_param']] = intval($options['max_tokens'] ?? 2000);
             }
         }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
includes/AI/FormGenerator.php around lines 589-598: the higher token limit for
integration forms is only applied for the Google provider; replicate the same
integration-aware token selection for OpenAI (around lines 256-261) and
Anthropic (around lines 431-438) so integration forms get the elevated token
limit across all providers. For each provider, detect if $context['integration']
is non-empty and set the provider-specific max tokens variable to 4000
(otherwise use the existing intval($options['max_tokens'] ?? 2000) fallback),
then assign that value into the provider's request payload at the correct token
param/location used by that provider (e.g., OpenAI's max_tokens field and
Anthropic's token param/config) so all providers honor the integration-aware
token limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs: dev review This PR needs review by a developer needs: testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants