-
Notifications
You must be signed in to change notification settings - Fork 154
Feat/integration specific ai builder #1754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Feat/integration specific ai builder #1754
Conversation
WalkthroughAdds 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✨ Finishing touches
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. Comment |
There was a problem hiding this 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
$keyis 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_existschecks 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 usingloadingIntegrationsstate in the UI.The
loadingIntegrationsstate 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
📒 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
formTypeis 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_settingscorrectly 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_settingshelper is well-implemented. Usingarray_mergecorrectly 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_catandproduct_taginstead 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_fieldis 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:
- Whether the prompt header actually marks this as a Pro field
- How the pricing field documentation handles Pro guidance
- 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_fieldfor 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
integrationparameter 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
/integrationsendpoint 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
selectedIntegrationbetween 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_Eventprefix.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.
There was a problem hiding this 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.
|
@arifulhoque7 vai
2 fields are missing for all kind of woocommerce form
2 fields are missing for digital product form
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
2 fields are missing for digital downloads form
Unnecessary field (product tag) for product form according to manual woo tmplate creation |
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.
There was a problem hiding this 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_typedetection and propagation intoformTypeare correctly sanitized and restricted to read-only admin context, and the broaderpagesubstring 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.Recommendedwith 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
integrationarg to/generate, validating viaenum, and sanitizing withsanitize_text_fieldis correct./ai-form-builder/integrationscleanly exposes only enabled integrations for the requestedform_typeand usesclass_exists()checks in a cheap, safe way.generate_form()’s injection of$integrationinto$conversation_contextand 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(withcurrent_formetc.) and aform_type, but no explicitintegrationparameter. For integration‑specific forms, you’ll want the frontend to include theintegrationvalue insidemodification_data.conversation_contextso thatget_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 debugerror_log()calls.Using a higher max token budget (
4000) whencontext.integrationis present makes sense for large integration templates, and the fallback tooptions.max_tokens || 2000otherwise 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
availableIntegrationsfrom/ai-form-builder/integrations, is a clean UX and respects loading state.initialIntegration→selectedIntegration→update:selectedIntegrationkeeps parent and child in sync, andupdatePromptTemplates()swaps in the correct prompt set for WooCommerce, EDD, or Events Calendar (or falls back to generic post prompts).startGeneration()now includesintegration: this.selectedIntegrationin the emitted payload, which lines up with the backend changes and AIFormBuilder’s API call.Optional: after
fetchAvailableIntegrations()resolves, you could clearselectedIntegrationif its value isn’t present inavailableIntegrationsanymore (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
📒 Files selected for processing (8)
assets/js/components/AIFormBuilder.vueassets/js/components/FormInputStage.vueincludes/AI/FormGenerator.phpincludes/AI/RestController.phpincludes/AI/wpuf-ai-prompt-edd.mdincludes/AI/wpuf-ai-prompt-events-calendar.mdincludes/AI/wpuf-ai-prompt-woocommerce.mdincludes/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 explicitpost_type: "download"anddownload_category/download_tagrules 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_tagare 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 afile_exists()check ensures WooCommerce/EDD/Events Calendar prompts are used when available, with a clean fallback to the minimal prompt.- The added final
elsebranch that falls back to the minimal prompt for unexpectedform_typevalues addresses the earlier uninitialized$prompt_filerisk 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_fieldfor Pro vstext_fieldon Free) without changing non‑integration behavior.Overall this makes prompt selection deterministic for all combinations of
form_typeandintegration.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, standardpost_tags, and TEC meta keys like_EventStartDate/_EventEndDate/_EventCost, and thepost_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.
selectedIntegrationis now a first‑class piece of state, fed intoFormInputStageasinitialIntegrationand kept in sync via@update:selectedIntegration.handleStartGenerationstoresdata.integrationand passes it through tocallAIFormGenerationAPI, which conditionally includesintegrationin the JSON payload.- On a successful response, the backend’s
result.data.integrationis written back toselectedIntegration, so the chosen integration survives the full round‑trip.regenerateForm()resets description and prompt but intentionally does not clearselectedIntegration, 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
|
@Rubaiyat-E-Mohammad vai, now check please |
2 issues (unchecked) are still remaining here. @arifulhoque7 vai |
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.
@Rubaiyat-E-Mohammad vai, issue-2 is fixed now please check |
There was a problem hiding this 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:
- URL construction (line 234): Using string concatenation could be problematic if
formTypecontains special characters. Consider usingURLSearchParams:const params = new URLSearchParams({ form_type: this.formType }); const response = await fetch(`${restUrl}wpuf/v1/ai-form-builder/integrations?${params}`, {
- 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
📒 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
initialIntegrationprop 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
initialIntegrationduring 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
.mdprompt files rather than these short instruction strings.
362-370: LGTM! Payload correctly includes integration context.The
startGenerationmethod now properly passes integration context to the backend:
- Uses optional chaining (
selectedPrompt?.id) to safely handle different data types- Includes
integrationfield 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.
|
The downloadable product field is a radio field with yes & no options. but showing a checkbox @arifulhoque7 vai |
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.
Now it should be fixed @Rubaiyat-E-Mohammad vai, check this |
There was a problem hiding this 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:
- Add a warning comment indicating that logs may contain sensitive data and should be secured
- Further truncate to just the first 100-200 characters rather than 500
- Sanitize the content before logging by removing potential PII patterns
- 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_fieldinstead ofnumeric_text_fieldfor 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
📒 Files selected for processing (2)
includes/AI/FormGenerator.phpincludes/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(notcheckbox_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_existscheck (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_filefor unexpected form types.
|
The price field for the WooCommerce product form is not saving the price while the form is created with AI. @arifulhoque7 vai |
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.
fixed @Rubaiyat-E-Mohammad vai |
There was a problem hiding this 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
📒 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:
- ✓ AI sets
post_type: 'product'in form_settings (verified in wpuf-ai-prompt-woocommerce.md)- ✓ Code maps
post_type: 'product'→form_template: 'post_form_template_woocommerce'(line 867)- ✓
form_templateis saved to post_meta and retrieved during form submission (Form_Template.php:247)- ✓ Template instance is instantiated and
after_insert()is called on form submission (Form_Template.php:253, 262)- ✓ WooCommerce's
update_price()hook is triggered to update the_pricemeta field (Post_Form_Template_WooCommerce.php:292)The reported price-saving issue should be resolved with this implementation.
| 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); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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.
| /** | ||
| * 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; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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 -30Repository: 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 -20Repository: 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.
| /** | |
| * 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.
includes/AI/FormGenerator.php
Outdated
| ]; | ||
|
|
||
| // Log request details for debugging | ||
| error_log('WPUF AI: Google AI Request - Model: ' . $this->current_model); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove this comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done @sapayth vai
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.
There was a problem hiding this 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
📒 Files selected for processing (3)
assets/js/components/AIFormBuilder.vueassets/js/components/FormSuccessStage.vueincludes/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_existscheck forwpuf_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:
selectedIntegrationdata property at the parent level (line 67)- Passed as
initialIntegrationprop to FormInputStage (line 8)- Updates captured via
update:selectedIntegrationevent (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
selectedPromptbeing cleared (line 698) whileselectedIntegrationpersists is the intended behavior to maintain integration context across regenerations.Also applies to: 696-699
| // 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; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.












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
🤖 Specialized AI Prompts
Added three comprehensive prompt templates with precise field structures:
wpuf-ai-prompt-woocommerce.md(463 lines)post_type: "product"automaticallywpuf-ai-prompt-edd.md(325 lines)post_type: "download"automaticallywpuf-ai-prompt-events-calendar.md(408 lines)post_type: "tribe_events"automatically🔌 Backend API
GET /wpuf/v1/ai-form-builder/integrationsAI_Manager.phpFormGenerator.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 | +11New 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:
After:
_regular_price, EDD pricing tiers, Event date/time fieldspost_typeconfiguration🌍 Multilingual Support
All prompts include:
🔧 Technical Details
Integration Detection:
API Response Format:
✅ Testing Checklist
post_typeis set correctly in form settingsis_meta: "yes"🚀 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-builderBase:
developCommits: 1 feature commit
Status: ✅ Ready for review
Summary by CodeRabbit
New Features
Improvements
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.