# Part of Odoo. See LICENSE file for full copyright and licensing details. import contextlib import json import re import secrets from lxml import etree, html as lxml_html from odoo import api, models from odoo.addons.ai_website.models.ai_website_service import _WHOLE_ZONE_SELECTORS # The public form runtime re-injects a fresh signature on every render # (website/tools.py add_form_signature), so any signature in generated or # fetched markup is dead weight, and a hardcoded hash trips the safety # reviewer. Strip them everywhere. _FORM_SIGNATURE_RE = re.compile(r']*website_form_signature[^>]*>\s*', re.IGNORECASE) _SUCCESS_MODES = ('redirect', 'message', 'nothing') # The field types the editor can render, one website.form_field_* template # each (website_form_editor.xml). Any other data-type crashes the sidebar's # field rendering. _FIELD_TYPES = frozenset(( 'char', 'text', 'email', 'tel', 'url', 'integer', 'float', 'monetary', 'date', 'datetime', 'binary', 'boolean', 'selection', 'many2one', 'one2many', 'many2many', 'html', )) _EMAIL_TO_INPUT_RE = re.compile(r']*\bname="email_to"[^>]*>', re.IGNORECASE) # The accept values the editor's file-type options produce. The submit # validator matches them against the files' MIME types, so anything else # (e.g. an extension list) rejects every upload. _FILE_ACCEPT_VALUES = frozenset(( 'image/*', 'application/pdf', 'application/*', 'video/*', 'audio/*', )) def _blank_email_to_values(html): """Clear the `value` attribute of any `email_to` inputs in the HTML. This prevents the AI from silently copying the default company address from snippets without the user's explicit approval.""" return _EMAIL_TO_INPUT_RE.sub( lambda match: re.sub(r'\bvalue="[^"]*"', 'value=""', match.group(0)), html, ) def _with_class(cls): """Generate an XPath condition to safely match a class name within a space-separated class attribute.""" return f'contains(concat(" ", normalize-space(@class), " "), " {cls} ")' def _field_name(field_el): """The name a field wrapper submits under. A multi-option field carries it on its group wrapper, every other field on its input.""" return next(iter(field_el.xpath( f'.//*[{_with_class("s_website_form_multiple")}]/@data-name' f' | .//*[{_with_class("s_website_form_input")}]/@name')), None) class AIToolWebform(models.AbstractModel): """Webform support for the website builder agent. The agent builds forms by writing HTML adapted from the canonical form snippets; this layer makes those forms functional by construction: - a normalizer gates every HTML apply: purely mechanical details (signatures, ids, submit anchor, custom-vs-bound markers) are repaired in place, while anything that would break the submission or the editor and needs the model's (or the user's) intent raises, so the error goes back through the tool result and the model corrects its own output; - the "Set Form Action" tool wires a form through the form editor's own client-side code paths, and the "Get Webform Info" tool describes the available form actions and their bindable fields. """ _inherit = 'ai.tool' @api.model def _ai_tool_apply_html_to_page(self, tool_context, actions): """Normalize the webforms in the actions before the base apply pipeline runs.""" # Some providers send structured arguments JSON-encoded; parse before # normalizing. if isinstance(actions, str): with contextlib.suppress(json.JSONDecodeError): actions = json.loads(actions) if isinstance(actions, list): # Before super(): the safety reviewer must never see a signature. self._normalize_webform_actions(actions) return super()._ai_tool_apply_html_to_page(tool_context, actions) @api.model def _ai_tool_get_snippets(self, snippet_keys): """Strip live signatures and blank out email recipients from fetched snippets to prevent the model from faithfully copying them.""" result = super()._ai_tool_get_snippets(snippet_keys) if isinstance(result, str): result = _FORM_SIGNATURE_RE.sub('', result) result = _blank_email_to_values(result) return result @api.model def _normalize_webform_actions(self, actions): """Validate and normalize the webforms of every action's content, in place.""" for index, action in enumerate(actions): if not isinstance(action, dict): continue content = action.get('content') or '' if 's_website_form' not in content and ', and a non-empty end message for every form whose success mode shows one.""" if root.xpath(f'//*[({_with_class("s_website_form_field")} or {_with_class("s_website_form_input")}) and not(ancestor::form)]'): raise ValueError( f"Action #{index}: the HTML contains form fields outside of a
" "element; they can never be submitted. Fetch a form snippet with " "\"Get Snippets\" and keep the fields inside its ." ) fields_by_model = {} actions_by_key = self._get_webform_actions() for form in root.xpath('//form'): is_webform = form.get('data-model_name') or form.xpath(f'.//*[{_with_class("s_website_form_input")}]') if not is_webform: continue # e.g. a search bar self._normalize_webform(index, form, actions_by_key, fields_by_model) if form.get('data-success-mode') == 'message': # The runtime looks the message up with # `form.parentNode.querySelector`, so anywhere else is invisible. message = form.getparent().xpath(f'.//*[{_with_class("s_website_form_end_message")}]') if not message or (len(message[0]) == 0 and not (message[0].text or '').strip()): raise ValueError( f"Action #{index}: the form uses data-success-mode=\"message\" but " "the div.s_website_form_end_message to show after submission is " "missing or empty. Include it, with real themed content, as a " "SIBLING right after the form in the SAME action (widen the " "selector if it already exists on the page outside the replaced " "element)." ) @api.model def _normalize_webform(self, index, form, actions_by_key, fields_by_model): """Normalize one webform: check its action wiring, structure and fields, repairing what is purely mechanical and raising whenever the model must rewrite its HTML.""" model = form.get('data-model_name') if not model: raise ValueError( f"Action #{index}: the form has fields but no data-model_name, so " "submissions go nowhere. Wire the form to an action with the " "\"Set Form Action\" tool." ) if model not in {a['model'] for a in actions_by_key.values()}: raise ValueError( f"Action #{index}: the form targets the model '{model}' which is not " "enabled for website forms. Use the \"Get Webform Info\" tool to list " "the available form actions and their models." ) if model not in fields_by_model: fields_by_model[model] = self.env['ir.model'].get_authorized_fields(model, {}) authorized_fields = fields_by_model[model] rows = form.xpath(f'.//*[{_with_class("s_website_form_rows")}]') submit = form.xpath(f'.//*[{_with_class("s_website_form_submit")}]') if not rows or not submit: raise ValueError( f"Action #{index}: the form structure is incomplete (missing the " "s_website_form_rows container or the s_website_form_submit block). " "Fetch a form snippet with \"Get Snippets\" and keep its structure." ) if not submit[0].xpath(f'.//*[{_with_class("s_website_form_send")}]'): raise ValueError( f"Action #{index}: the form has no submit button " "(a.s_website_form_send inside the s_website_form_submit block)." ) # The runtime renders the submission status after this span; without it # every submit crashes in the visitor's browser. if not submit[0].xpath('.//span[@id="s_website_form_result"]'): span = etree.SubElement(submit[0], 'span') span.set('id', 's_website_form_result') send = submit[0].xpath(f'.//*[{_with_class("s_website_form_send")}]')[0] send.addprevious(span) if form.xpath('.//input[not(normalize-space(@name))] | .//select[not(normalize-space(@name))] | .//textarea[not(normalize-space(@name))]'): raise ValueError( f"Action #{index}: the form contains an input without a name; its " "value would be lost on submission. Name every input." ) invalid_types = { field_type for field_type in form.xpath(f'.//*[{_with_class("s_website_form_field")}]/@data-type') if field_type not in _FIELD_TYPES } if invalid_types: raise ValueError( f"Action #{index}: invalid field data-type(s) " f"{', '.join(sorted(invalid_types))} - the editor breaks on them. " "data-type is the ORM field type, never the HTML input type " f"(a numeric field is integer or float). Valid values: " f"{', '.join(sorted(_FIELD_TYPES))}." ) # One field without its structural label breaks the editing sidebar # for the whole form. if form.xpath(f'.//*[{_with_class("s_website_form_field")}' f' and not({_with_class("s_website_form_dnone")})' f' and not(.//label[{_with_class("s_website_form_label")}])]'): raise ValueError( f"Action #{index}: a field is missing its