helpdesk_team.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import json
  4. import logging
  5. from lxml import etree, html
  6. from odoo import api, fields, models, Command, _
  7. from odoo.osv import expression
  8. _logger = logging.getLogger(__name__)
  9. class HelpdeskTeamExtras(models.Model):
  10. _inherit = "helpdesk.team"
  11. collaborator_ids = fields.One2many(
  12. "helpdesk.team.collaborator",
  13. "team_id",
  14. string="Collaborators",
  15. copy=False,
  16. export_string_translation=False,
  17. help="Partners with access to this helpdesk team",
  18. )
  19. template_id = fields.Many2one(
  20. 'helpdesk.template',
  21. string='Template',
  22. help="Template to use for tickets in this team. If set, template fields will be shown in ticket form."
  23. )
  24. workflow_template_id = fields.Many2one(
  25. 'helpdesk.workflow.template',
  26. string='Workflow Template',
  27. help="Workflow template with stages and SLA policies. Use 'Apply Template' button to create stages and SLAs."
  28. )
  29. @api.model_create_multi
  30. def create(self, vals_list):
  31. """Override create to regenerate form XML if template is set"""
  32. teams = super().create(vals_list)
  33. # After create, if template is set and form view exists, regenerate
  34. # This handles the case when team is created with template_id already set
  35. for team in teams.filtered(lambda t: t.use_website_helpdesk_form and t.template_id and t.website_form_view_id):
  36. team._regenerate_form_from_template()
  37. return teams
  38. def _ensure_submit_form_view(self):
  39. """Override to regenerate form from template after creating view"""
  40. result = super()._ensure_submit_form_view()
  41. # After view is created, if template is set, regenerate form
  42. # Note: super() may have created views, so we need to refresh to get updated website_form_view_id
  43. for team in self.filtered(lambda t: t.use_website_helpdesk_form and t.template_id):
  44. # Refresh to get updated website_form_view_id after super() created it
  45. team.invalidate_recordset(['website_form_view_id'])
  46. if team.website_form_view_id:
  47. team._regenerate_form_from_template()
  48. return result
  49. def write(self, vals):
  50. """Override write to regenerate form XML when template changes"""
  51. result = super().write(vals)
  52. if 'template_id' in vals:
  53. # Regenerate form XML when template is assigned/changed
  54. # After super().write(), refresh teams to get updated values
  55. teams_to_process = self.browse(self.ids).filtered('use_website_helpdesk_form')
  56. for team in teams_to_process:
  57. # Ensure website_form_view_id exists before regenerating
  58. # This handles the case when template is assigned but view doesn't exist yet
  59. if not team.website_form_view_id:
  60. # Call _ensure_submit_form_view which will create the view if needed
  61. # This method already handles template regeneration if template_id is set
  62. team._ensure_submit_form_view()
  63. else:
  64. # View exists, regenerate or restore form based on template
  65. if team.template_id:
  66. team._regenerate_form_from_template()
  67. else:
  68. # If template is removed, restore default form
  69. team._restore_default_form()
  70. return result
  71. # New computed fields for hours stats in backend view
  72. hours_total_available = fields.Float(
  73. compute="_compute_hours_stats",
  74. string="Total Available Hours",
  75. store=False
  76. )
  77. hours_total_used = fields.Float(
  78. compute="_compute_hours_stats",
  79. string="Total Used Hours",
  80. store=False
  81. )
  82. hours_percentage_used = fields.Float(
  83. compute="_compute_hours_stats",
  84. string="Percentage Used Hours",
  85. store=False
  86. )
  87. has_hours_stats = fields.Boolean(
  88. compute="_compute_hours_stats",
  89. string="Has Hours Stats",
  90. store=False
  91. )
  92. def _compute_hours_stats(self):
  93. """Compute hours stats for the team based on collaborators"""
  94. # Check if sale_timesheet is installed
  95. has_sale_timesheet = "sale_timesheet" in self.env.registry._init_modules
  96. # Get UoM hour reference once for all teams
  97. try:
  98. uom_hour = self.env.ref("uom.product_uom_hour")
  99. except Exception:
  100. uom_hour = False
  101. if not uom_hour:
  102. for team in self:
  103. team.hours_total_available = 0.0
  104. team.hours_total_used = 0.0
  105. team.hours_percentage_used = 0.0
  106. team.has_hours_stats = False
  107. return
  108. SaleOrderLine = self.env["sale.order.line"].sudo()
  109. for team in self:
  110. # Default values
  111. total_available = 0.0
  112. total_used = 0.0
  113. has_stats = False
  114. # If team has collaborators, calculate their hours
  115. if not team.collaborator_ids:
  116. team.hours_total_available = 0.0
  117. team.hours_total_used = 0.0
  118. team.hours_percentage_used = 0.0
  119. team.has_hours_stats = False
  120. continue
  121. # Get unique commercial partners (optimize: avoid duplicates)
  122. partners = team.collaborator_ids.partner_id.commercial_partner_id
  123. unique_partners = partners.filtered(lambda p: p.active).ids
  124. if not unique_partners:
  125. team.hours_total_available = 0.0
  126. team.hours_total_used = 0.0
  127. team.hours_percentage_used = 0.0
  128. team.has_hours_stats = False
  129. continue
  130. # Build service domain once (reused for both queries)
  131. base_service_domain = []
  132. if has_sale_timesheet:
  133. try:
  134. base_service_domain = SaleOrderLine._domain_sale_line_service(
  135. check_state=False
  136. )
  137. except Exception:
  138. base_service_domain = [
  139. ("product_id.type", "=", "service"),
  140. ("product_id.service_policy", "=", "ordered_prepaid"),
  141. ("remaining_hours_available", "=", True),
  142. ]
  143. # Optimize: Get all prepaid lines for all partners in one query
  144. prepaid_domain = expression.AND([
  145. [
  146. ("company_id", "=", team.company_id.id),
  147. ("order_partner_id", "child_of", unique_partners),
  148. ("state", "in", ["sale", "done"]),
  149. ("remaining_hours", ">", 0),
  150. ],
  151. base_service_domain,
  152. ])
  153. all_prepaid_lines = SaleOrderLine.search(prepaid_domain)
  154. # Optimize: Get all lines for hours used calculation in one query
  155. hours_used_domain = expression.AND([
  156. [
  157. ("company_id", "=", team.company_id.id),
  158. ("order_partner_id", "child_of", unique_partners),
  159. ("state", "in", ["sale", "done"]),
  160. ],
  161. base_service_domain,
  162. ])
  163. all_lines = SaleOrderLine.search(hours_used_domain)
  164. # Cache order payment status to avoid multiple checks
  165. order_paid_cache = {}
  166. orders_to_check = (all_prepaid_lines | all_lines).mapped("order_id")
  167. for order in orders_to_check:
  168. order_paid_cache[order.id] = self._is_order_paid(order)
  169. # Group lines by commercial partner for calculation
  170. partner_lines = {}
  171. for line in all_prepaid_lines:
  172. partner_id = line.order_partner_id.commercial_partner_id.id
  173. if partner_id not in partner_lines:
  174. partner_lines[partner_id] = {"prepaid": [], "all": []}
  175. partner_lines[partner_id]["prepaid"].append(line)
  176. for line in all_lines:
  177. partner_id = line.order_partner_id.commercial_partner_id.id
  178. if partner_id not in partner_lines:
  179. partner_lines[partner_id] = {"prepaid": [], "all": []}
  180. partner_lines[partner_id]["all"].append(line)
  181. # Calculate stats per partner
  182. for partner_id, lines_dict in partner_lines.items():
  183. partner = self.env["res.partner"].browse(partner_id)
  184. if not partner.exists():
  185. continue
  186. prepaid_lines = lines_dict["prepaid"]
  187. all_partner_lines = lines_dict["all"]
  188. # 1. Calculate prepaid hours and highest price
  189. highest_price = 0.0
  190. prepaid_hours = 0.0
  191. for line in prepaid_lines:
  192. order_id = line.order_id.id
  193. if order_paid_cache.get(order_id, False):
  194. prepaid_hours += max(0.0, line.remaining_hours or 0.0)
  195. # Track highest price from all lines (for credit calculation)
  196. if line.price_unit > highest_price:
  197. highest_price = line.price_unit
  198. # 2. Calculate credit hours
  199. credit_hours = 0.0
  200. if (
  201. team.company_id.account_use_credit_limit
  202. and partner.credit_limit > 0
  203. ):
  204. credit_used = partner.credit or 0.0
  205. credit_avail = max(0.0, partner.credit_limit - credit_used)
  206. if highest_price > 0:
  207. credit_hours = credit_avail / highest_price
  208. total_available += prepaid_hours + credit_hours
  209. # 3. Calculate hours used
  210. for line in all_partner_lines:
  211. order_id = line.order_id.id
  212. if order_paid_cache.get(order_id, False):
  213. qty_delivered = line.qty_delivered or 0.0
  214. if qty_delivered > 0:
  215. qty_hours = (
  216. line.product_uom._compute_quantity(
  217. qty_delivered, uom_hour, raise_if_failure=False
  218. )
  219. or 0.0
  220. )
  221. total_used += qty_hours
  222. has_stats = total_available > 0 or total_used > 0
  223. team.hours_total_available = total_available
  224. team.hours_total_used = total_used
  225. team.has_hours_stats = has_stats
  226. # Calculate percentage
  227. if has_stats:
  228. grand_total = total_used + total_available
  229. if grand_total > 0:
  230. team.hours_percentage_used = (total_used / grand_total) * 100
  231. else:
  232. team.hours_percentage_used = 0.0
  233. else:
  234. team.hours_percentage_used = 0.0
  235. def _check_helpdesk_team_sharing_access(self):
  236. """Check if current user has access to this helpdesk team through sharing"""
  237. self.ensure_one()
  238. if self.env.user._is_portal():
  239. collaborator = self.env["helpdesk.team.collaborator"].search(
  240. [
  241. ("team_id", "=", self.id),
  242. ("partner_id", "=", self.env.user.partner_id.id),
  243. ],
  244. limit=1,
  245. )
  246. return collaborator
  247. return self.env.user._is_internal()
  248. def _get_new_collaborators(self, partners):
  249. """Get new collaborators that can be added to the team"""
  250. self.ensure_one()
  251. return partners.filtered(
  252. lambda partner: partner not in self.collaborator_ids.partner_id
  253. and partner.partner_share
  254. )
  255. def _add_collaborators(self, partners, access_mode="user_own"):
  256. """Add collaborators to the team"""
  257. self.ensure_one()
  258. new_collaborators = self._get_new_collaborators(partners)
  259. if not new_collaborators:
  260. return
  261. self.write(
  262. {
  263. "collaborator_ids": [
  264. Command.create(
  265. {
  266. "partner_id": collaborator.id,
  267. "access_mode": access_mode,
  268. }
  269. )
  270. for collaborator in new_collaborators
  271. ]
  272. }
  273. )
  274. # Subscribe partners as followers
  275. self.message_subscribe(partner_ids=new_collaborators.ids)
  276. def action_open_share_team_wizard(self):
  277. """Open the share team wizard"""
  278. self.ensure_one()
  279. action = self.env["ir.actions.actions"]._for_xml_id(
  280. "helpdesk_extras.helpdesk_team_share_wizard_action"
  281. )
  282. action["context"] = {
  283. "active_id": self.id,
  284. "active_model": "helpdesk.team",
  285. "default_res_model": "helpdesk.team",
  286. "default_res_id": self.id,
  287. }
  288. return action
  289. @api.model
  290. def _is_order_paid(self, order):
  291. """
  292. Check if a sale order has received payment through its invoices.
  293. Only considers orders with at least one invoice that is posted and fully paid.
  294. This method can be used both in frontend and backend.
  295. Args:
  296. order: sale.order record
  297. Returns:
  298. bool: True if order has at least one paid invoice, False otherwise
  299. """
  300. if not order:
  301. return False
  302. # Use sudo to ensure access to invoice fields
  303. order_sudo = order.sudo()
  304. # Check if order has invoices
  305. if not order_sudo.invoice_ids:
  306. return False
  307. # Check if at least one invoice is fully paid
  308. # payment_state values: 'not_paid', 'partial', 'paid', 'in_payment', 'reversed', 'invoicing_legacy'
  309. # We only consider invoices that are:
  310. # - posted (state = 'posted')
  311. # - fully paid (payment_state = 'paid')
  312. paid_invoices = order_sudo.invoice_ids.filtered(
  313. lambda inv: inv.state == "posted" and inv.payment_state == "paid"
  314. )
  315. # Debug: Log invoice states for troubleshooting
  316. if order_sudo.invoice_ids:
  317. invoice_states = []
  318. for inv in order_sudo.invoice_ids:
  319. try:
  320. invoice_states.append(
  321. f"Invoice {inv.id}: state={inv.state}, payment_state={getattr(inv, 'payment_state', 'N/A')}"
  322. )
  323. except Exception:
  324. invoice_states.append(f"Invoice {inv.id}: error reading state")
  325. # self.env['ir.logging'].sudo().create({
  326. # 'name': 'helpdesk_extras',
  327. # 'type': 'server',
  328. # 'level': 'info',
  329. # 'message': f'Order {order.id} - Invoice states: {"; ".join(invoice_states)} - Paid: {bool(paid_invoices)}',
  330. # 'path': 'helpdesk.team',
  331. # 'func': '_is_order_paid',
  332. # 'line': '1',
  333. # })
  334. # Return True ONLY if at least one invoice is fully paid
  335. # This is critical: we must have at least one invoice with payment_state == 'paid'
  336. result = bool(paid_invoices)
  337. # Extra verification: ensure we're really getting paid invoices
  338. if result:
  339. # Double-check that we have at least one invoice that is actually paid
  340. verified_paid = any(
  341. inv.state == "posted" and getattr(inv, "payment_state", "") == "paid"
  342. for inv in order_sudo.invoice_ids
  343. )
  344. if not verified_paid:
  345. result = False
  346. return result
  347. def _regenerate_form_from_template(self):
  348. """Regenerate the website form XML based on the template"""
  349. self.ensure_one()
  350. if not self.template_id or not self.website_form_view_id:
  351. return
  352. # Get base form structure (from default template)
  353. # We use the default template arch to ensure we start with a clean base
  354. default_form = self.env.ref('website_helpdesk.ticket_submit_form', raise_if_not_found=False)
  355. if not default_form:
  356. return
  357. # Get website language for translations
  358. # Try to get current website, fallback to default website or system language
  359. website = self.env['website'].get_current_website()
  360. if website:
  361. lang = website.default_lang_id.code if website.default_lang_id else 'en_US'
  362. else:
  363. # Fallback: try to get default website
  364. try:
  365. default_website = self.env.ref('website.default_website', raise_if_not_found=False)
  366. if default_website and default_website.default_lang_id:
  367. lang = default_website.default_lang_id.code
  368. else:
  369. lang = self.env.context.get('lang', 'en_US')
  370. except Exception:
  371. lang = self.env.context.get('lang', 'en_US')
  372. # Create environment with website language for translations
  373. env_lang = self.env(context=dict(self.env.context, lang=lang))
  374. # Get template fields sorted by sequence
  375. template_fields = self.template_id.field_ids.sorted('sequence')
  376. # Log template fields for debugging
  377. _logger.info(f"Regenerating form for team {self.id}, template {self.template_id.id} with {len(template_fields)} fields")
  378. for tf in template_fields:
  379. _logger.info(f" - Field: {tf.field_id.name if tf.field_id else 'None'} (type: {tf.field_id.ttype if tf.field_id else 'None'})")
  380. # Whitelistear campos del template antes de construir el formulario
  381. field_names = [tf.field_id.name for tf in template_fields
  382. if tf.field_id and not tf.field_id.website_form_blacklisted]
  383. if field_names:
  384. try:
  385. self.env['ir.model.fields'].formbuilder_whitelist('helpdesk.ticket', field_names)
  386. _logger.info(f"Whitelisted fields: {field_names}")
  387. except Exception as e:
  388. _logger.warning(f"Could not whitelist fields {field_names}: {e}")
  389. # Parse current arch to get existing description, team_id and submit button
  390. root = etree.fromstring(self.website_form_view_id.arch.encode('utf-8'))
  391. rows_el = root.xpath('.//div[contains(@class, "s_website_form_rows")]')
  392. if not rows_el:
  393. _logger.error(f"Could not find s_website_form_rows container in view {self.website_form_view_id.id}")
  394. return
  395. rows_el = rows_el[0]
  396. # Get template field names to know which ones are already in template
  397. template_field_names = set(tf.field_id.name for tf in template_fields if tf.field_id)
  398. # Get existing description, team_id and submit button HTML (to preserve them)
  399. # BUT: only preserve description if it's NOT in the template
  400. description_html = None
  401. team_id_html = None
  402. submit_button_html = None
  403. for child in list(rows_el):
  404. classes = child.get('class', '')
  405. if 's_website_form_submit' in classes:
  406. submit_button_html = etree.tostring(child, encoding='unicode', pretty_print=True)
  407. continue
  408. if 's_website_form_field' not in classes:
  409. continue
  410. field_input = child.xpath('.//input[@name] | .//textarea[@name] | .//select[@name]')
  411. if not field_input:
  412. continue
  413. field_name = field_input[0].get('name')
  414. if field_name == 'description':
  415. # Only preserve description if it's NOT in the template
  416. if 'description' not in template_field_names:
  417. description_html = etree.tostring(child, encoding='unicode', pretty_print=True)
  418. elif field_name == 'team_id':
  419. # Always preserve team_id (it's always needed, hidden)
  420. team_id_html = etree.tostring(child, encoding='unicode', pretty_print=True)
  421. # Build HTML for template fields
  422. field_id_counter = 0
  423. template_fields_html = []
  424. for tf in template_fields:
  425. try:
  426. field_html, field_id_counter = self._build_template_field_html(tf, field_id_counter, env_lang=env_lang)
  427. if field_html:
  428. template_fields_html.append(field_html)
  429. _logger.info(f"Built HTML for field {tf.field_id.name if tf.field_id else 'Unknown'}")
  430. except Exception as e:
  431. _logger.error(f"Error building HTML for field {tf.field_id.name if tf.field_id else 'Unknown'}: {e}", exc_info=True)
  432. # Build complete rows container HTML
  433. # Order: template fields -> description (if not in template) -> team_id -> submit button
  434. rows_html_parts = []
  435. # Add template fields first (this includes description if it's in the template)
  436. rows_html_parts.extend(template_fields_html)
  437. # Add description only if it exists AND is NOT in template
  438. if description_html:
  439. rows_html_parts.append(description_html)
  440. # Add team_id (always needed, hidden)
  441. if team_id_html:
  442. rows_html_parts.append(team_id_html)
  443. # Add submit button (if exists)
  444. if submit_button_html:
  445. rows_html_parts.append(submit_button_html)
  446. # Join all parts - each field HTML already has proper formatting
  447. # We need to indent each field to match Odoo's formatting (32 spaces)
  448. indented_parts = []
  449. for part in rows_html_parts:
  450. # Split by lines and indent each line
  451. lines = part.split('\n')
  452. indented_lines = []
  453. for line in lines:
  454. if line.strip(): # Only indent non-empty lines
  455. indented_lines.append(' ' + line)
  456. else:
  457. indented_lines.append('')
  458. indented_parts.append('\n'.join(indented_lines))
  459. rows_html = '\n'.join(indented_parts)
  460. # Wrap in the rows container div
  461. rows_container_html = f'''<div class="s_website_form_rows row s_col_no_bgcolor">
  462. {rows_html}
  463. </div>'''
  464. # Use the same save method as form builder
  465. try:
  466. self.website_form_view_id.sudo().save(
  467. rows_container_html,
  468. xpath='.//div[contains(@class, "s_website_form_rows")]'
  469. )
  470. _logger.info(f"Successfully saved form using view.save() for team {self.id}, view {self.website_form_view_id.id}")
  471. except Exception as e:
  472. _logger.error(f"Error saving form with view.save(): {e}", exc_info=True)
  473. raise
  474. def _restore_default_form(self):
  475. """Restore the default form when template is removed"""
  476. self.ensure_one()
  477. if not self.website_form_view_id:
  478. return
  479. # Get default form structure
  480. default_form = self.env.ref('website_helpdesk.ticket_submit_form', raise_if_not_found=False)
  481. if not default_form:
  482. return
  483. # Restore default arch
  484. self.website_form_view_id.sudo().arch = default_form.arch
  485. def _build_template_field_html(self, template_field, field_id_counter=0, env_lang=None):
  486. """Build HTML string for a template field exactly as Odoo's form builder does
  487. Args:
  488. template_field: helpdesk.template.field record
  489. field_id_counter: int, counter for generating unique field IDs (incremented and returned)
  490. env_lang: Environment with language context for translations
  491. Returns:
  492. tuple: (html_string, updated_counter)
  493. """
  494. # Build the XML element first using existing method
  495. field_el, field_id_counter = self._build_template_field_xml(template_field, field_id_counter, env_lang=env_lang)
  496. if field_el is None:
  497. return None, field_id_counter
  498. # Convert to HTML string with proper formatting
  499. html_str = etree.tostring(field_el, encoding='unicode', pretty_print=True)
  500. return html_str, field_id_counter
  501. def _get_relation_domain(self, relation_model, env):
  502. """Get domain for relation model, filtering by active=True if the model has an active field
  503. Args:
  504. relation_model: Model name (string)
  505. env: Environment
  506. Returns:
  507. list: Domain list, e.g. [] or [('active', '=', True)]
  508. """
  509. if not relation_model:
  510. return []
  511. try:
  512. model = env[relation_model]
  513. # Check if model has an 'active' field
  514. if 'active' in model._fields:
  515. return [('active', '=', True)]
  516. except (KeyError, AttributeError):
  517. pass
  518. return []
  519. def _build_template_field_xml(self, template_field, field_id_counter=0, env_lang=None):
  520. """Build XML element for a template field exactly as Odoo's form builder does
  521. Args:
  522. template_field: helpdesk.template.field record
  523. field_id_counter: int, counter for generating unique field IDs (incremented and returned)
  524. env_lang: Environment with language context for translations
  525. Returns:
  526. tuple: (field_element, updated_counter)
  527. """
  528. field = template_field.field_id
  529. field_name = field.name
  530. field_type = field.ttype
  531. # Use environment with language context if provided, otherwise use self.env
  532. env = env_lang if env_lang else self.env
  533. # Use custom label if provided, otherwise use field's default label with language context
  534. if template_field.label_custom:
  535. field_label = template_field.label_custom
  536. else:
  537. # Get field description in the correct language using the model's field
  538. model_name = field.model_id.model
  539. try:
  540. model = env[model_name]
  541. model_field = model._fields.get(field_name)
  542. if model_field:
  543. # Use get_description() method which returns translated string
  544. # This method respects the language context
  545. field_desc = model_field.get_description(env)
  546. field_label = field_desc.get('string', '') if isinstance(field_desc, dict) else (field_desc or field.field_description or field.name)
  547. if not field_label:
  548. field_label = field.field_description or field.name
  549. else:
  550. field_label = field.field_description or field.name
  551. except Exception:
  552. # Fallback to field description or name
  553. field_label = field.field_description or field.name
  554. required = template_field.required
  555. sequence = template_field.sequence
  556. # Generate unique ID - use counter to avoid collisions
  557. field_id_counter += 1
  558. field_id = f'helpdesk_{field_id_counter}_{abs(hash(field_name)) % 10000}'
  559. # Build classes (exactly as form builder does) - CORREGIDO: mb-3 en lugar de mb-0 py-2
  560. classes = ['mb-3', 's_website_form_field', 'col-12']
  561. if required:
  562. classes.append('s_website_form_required')
  563. # Add visibility classes if configured (form builder uses these)
  564. visibility_classes = []
  565. if template_field.visibility_dependency:
  566. visibility_classes.append('s_website_form_field_hidden_if')
  567. visibility_classes.append('d-none')
  568. # Create field container div (exactly as form builder does)
  569. all_classes = classes + visibility_classes
  570. field_div = etree.Element('div', {
  571. 'class': ' '.join(all_classes),
  572. 'data-type': field_type,
  573. 'data-name': 'Field'
  574. })
  575. # Add visibility attributes if configured (form builder uses these)
  576. if template_field.visibility_dependency:
  577. field_div.set('data-visibility-dependency', template_field.visibility_dependency.name)
  578. if template_field.visibility_condition:
  579. field_div.set('data-visibility-condition', template_field.visibility_condition)
  580. if template_field.visibility_comparator:
  581. field_div.set('data-visibility-comparator', template_field.visibility_comparator)
  582. # Add visibility_between for range comparators (between/!between)
  583. if template_field.visibility_comparator in ['between', '!between'] and template_field.visibility_between:
  584. field_div.set('data-visibility-between', template_field.visibility_between)
  585. # Create inner row (exactly as form builder does)
  586. row_div = etree.SubElement(field_div, 'div', {
  587. 'class': 'row s_col_no_resize s_col_no_bgcolor'
  588. })
  589. # Create label (exactly as form builder does)
  590. label = etree.SubElement(row_div, 'label', {
  591. 'class': 'col-form-label col-sm-auto s_website_form_label',
  592. 'style': 'width: 200px',
  593. 'for': field_id
  594. })
  595. label_content = etree.SubElement(label, 'span', {
  596. 'class': 's_website_form_label_content'
  597. })
  598. label_content.text = field_label
  599. if required:
  600. mark = etree.SubElement(label, 'span', {
  601. 'class': 's_website_form_mark'
  602. })
  603. mark.text = ' *'
  604. # Create input container
  605. input_div = etree.SubElement(row_div, 'div', {
  606. 'class': 'col-sm'
  607. })
  608. # Build input based on field type
  609. input_el = None
  610. if field_type == 'boolean':
  611. # Checkbox - CORREGIDO: value debe ser 'Yes' no '1'
  612. form_check = etree.SubElement(input_div, 'div', {
  613. 'class': 'form-check'
  614. })
  615. input_el = etree.SubElement(form_check, 'input', {
  616. 'type': 'checkbox',
  617. 'class': 's_website_form_input form-check-input',
  618. 'name': field_name,
  619. 'id': field_id,
  620. 'value': 'Yes'
  621. })
  622. if required:
  623. input_el.set('required', '1')
  624. # Set checked if default_value is 'Yes' or '1' or 'True'
  625. if template_field.default_value and template_field.default_value.lower() in ('yes', '1', 'true'):
  626. input_el.set('checked', 'checked')
  627. elif field_type in ('text', 'html'):
  628. # Textarea - Use rows from template_field (default 3, same as Odoo formbuilder)
  629. rows_value = str(template_field.rows) if template_field.rows else '3'
  630. input_el = etree.SubElement(input_div, 'textarea', {
  631. 'class': 'form-control s_website_form_input',
  632. 'name': field_name,
  633. 'id': field_id,
  634. 'rows': rows_value
  635. })
  636. if template_field.placeholder:
  637. input_el.set('placeholder', template_field.placeholder)
  638. if required:
  639. input_el.set('required', '1')
  640. # Set default value as text content
  641. if template_field.default_value:
  642. input_el.text = template_field.default_value
  643. elif field_type == 'binary':
  644. # File upload
  645. input_el = etree.SubElement(input_div, 'input', {
  646. 'type': 'file',
  647. 'class': 'form-control s_website_form_input',
  648. 'name': field_name,
  649. 'id': field_id
  650. })
  651. if required:
  652. input_el.set('required', '1')
  653. elif field_type == 'one2many' and field.relation == 'ir.attachment':
  654. # Multiple file upload for attachment_ids
  655. input_el = etree.SubElement(input_div, 'input', {
  656. 'type': 'file',
  657. 'class': 'form-control s_website_form_input',
  658. 'name': field_name,
  659. 'id': field_id,
  660. 'multiple': 'true'
  661. })
  662. if required:
  663. input_el.set('required', '1')
  664. elif field_type == 'selection':
  665. # Check if custom selection options are provided (for non-relation selection fields)
  666. selection_options = None
  667. if template_field.selection_options and not field.relation:
  668. try:
  669. selection_options = json.loads(template_field.selection_options)
  670. if not isinstance(selection_options, list):
  671. selection_options = None
  672. except (json.JSONDecodeError, ValueError):
  673. _logger.warning(f"Invalid JSON in selection_options for field {field_name}: {template_field.selection_options}")
  674. selection_options = None
  675. # Determine selection type (dropdown or radio) - same as Odoo formbuilder
  676. selection_type = template_field.selection_type if template_field.selection_type else 'dropdown'
  677. # Check if this is a relation field (many2one stored as selection)
  678. is_relation = bool(field.relation)
  679. if selection_type == 'radio' and not is_relation:
  680. # Radio buttons for selection (non-relation)
  681. radio_wrapper = etree.SubElement(input_div, 'div', {
  682. 'class': 'row s_col_no_resize s_col_no_bgcolor s_website_form_multiple',
  683. 'data-name': field_name,
  684. 'data-display': 'horizontal'
  685. })
  686. # Get selection options
  687. if selection_options:
  688. options_list = selection_options
  689. else:
  690. # Get from model field definition with language context
  691. model_name = field.model_id.model
  692. model = env[model_name]
  693. options_list = []
  694. if hasattr(model, field_name):
  695. model_field = model._fields.get(field_name)
  696. if model_field and hasattr(model_field, 'selection'):
  697. # Use _description_selection method which handles translation correctly
  698. try:
  699. if hasattr(model_field, '_description_selection'):
  700. # This method returns translated options when env has lang context
  701. selection = model_field._description_selection(env)
  702. if isinstance(selection, (list, tuple)):
  703. options_list = selection
  704. else:
  705. # Fallback: use get_field_selection from ir.model.fields
  706. options_list = env['ir.model.fields'].get_field_selection(model_name, field_name)
  707. except Exception:
  708. # Fallback: get selection directly
  709. selection = model_field.selection
  710. if callable(selection):
  711. selection = selection(model)
  712. if isinstance(selection, (list, tuple)):
  713. options_list = selection
  714. elif field.selection:
  715. try:
  716. # Evaluate selection string if it's stored as string
  717. selection = eval(field.selection) if isinstance(field.selection, str) else field.selection
  718. if isinstance(selection, (list, tuple)):
  719. options_list = selection
  720. except Exception:
  721. pass
  722. # Create radio buttons
  723. for option_value, option_label in options_list:
  724. radio_div = etree.SubElement(radio_wrapper, 'div', {
  725. 'class': 'radio col-12 col-lg-4 col-md-6'
  726. })
  727. form_check = etree.SubElement(radio_div, 'div', {
  728. 'class': 'form-check'
  729. })
  730. radio_input = etree.SubElement(form_check, 'input', {
  731. 'type': 'radio',
  732. 'class': 's_website_form_input form-check-input',
  733. 'name': field_name,
  734. 'id': f'{field_id}_{abs(hash(str(option_value))) % 10000}',
  735. 'value': str(option_value)
  736. })
  737. if required:
  738. radio_input.set('required', '1')
  739. if template_field.default_value and str(template_field.default_value) == str(option_value):
  740. radio_input.set('checked', 'checked')
  741. radio_label = etree.SubElement(form_check, 'label', {
  742. 'class': 'form-check-label',
  743. 'for': radio_input.get('id')
  744. })
  745. radio_label.text = option_label
  746. input_el = radio_wrapper # For consistency, but not used
  747. elif template_field.widget == 'checkbox' and not is_relation:
  748. # Checkboxes for selection (non-relation) - multiple selection
  749. checkbox_wrapper = etree.SubElement(input_div, 'div', {
  750. 'class': 'row s_col_no_resize s_col_no_bgcolor s_website_form_multiple',
  751. 'data-name': field_name,
  752. 'data-display': 'horizontal'
  753. })
  754. # Get selection options (same as radio) with language context
  755. if selection_options:
  756. options_list = selection_options
  757. else:
  758. model_name = field.model_id.model
  759. model = env[model_name]
  760. options_list = []
  761. if hasattr(model, field_name):
  762. model_field = model._fields.get(field_name)
  763. if model_field and hasattr(model_field, 'selection'):
  764. selection = model_field.selection
  765. if callable(selection):
  766. selection = selection(model)
  767. if isinstance(selection, (list, tuple)):
  768. options_list = selection
  769. elif field.selection:
  770. try:
  771. selection = eval(field.selection) if isinstance(field.selection, str) else field.selection
  772. if isinstance(selection, (list, tuple)):
  773. options_list = selection
  774. except Exception:
  775. pass
  776. # Create checkboxes
  777. default_values = template_field.default_value.split(',') if template_field.default_value else []
  778. for option_value, option_label in options_list:
  779. checkbox_div = etree.SubElement(checkbox_wrapper, 'div', {
  780. 'class': 'checkbox col-12 col-lg-4 col-md-6'
  781. })
  782. form_check = etree.SubElement(checkbox_div, 'div', {
  783. 'class': 'form-check'
  784. })
  785. checkbox_input = etree.SubElement(form_check, 'input', {
  786. 'type': 'checkbox',
  787. 'class': 's_website_form_input form-check-input',
  788. 'name': field_name,
  789. 'id': f'{field_id}_{abs(hash(str(option_value))) % 10000}',
  790. 'value': str(option_value)
  791. })
  792. if required:
  793. checkbox_input.set('required', '1')
  794. if str(option_value) in [v.strip() for v in default_values]:
  795. checkbox_input.set('checked', 'checked')
  796. checkbox_label = etree.SubElement(form_check, 'label', {
  797. 'class': 'form-check-label s_website_form_check_label',
  798. 'for': checkbox_input.get('id')
  799. })
  800. checkbox_label.text = option_label
  801. input_el = checkbox_wrapper # For consistency, but not used
  802. else:
  803. # Default: Select dropdown
  804. input_el = etree.SubElement(input_div, 'select', {
  805. 'class': 'form-select s_website_form_input',
  806. 'name': field_name,
  807. 'id': field_id
  808. })
  809. if template_field.placeholder:
  810. input_el.set('placeholder', template_field.placeholder)
  811. if required:
  812. input_el.set('required', '1')
  813. # Add default option - translate using website language context
  814. default_option = etree.SubElement(input_el, 'option', {
  815. 'value': ''
  816. })
  817. # Get translation using the environment's language context
  818. # Load translations explicitly and get translated text
  819. lang = env.lang or 'en_US'
  820. try:
  821. from odoo.tools.translate import get_translation, code_translations
  822. # Force load translations by accessing them (this triggers _load_python_translations)
  823. translations = code_translations.get_python_translations('helpdesk_extras', lang)
  824. translated_text = get_translation('helpdesk_extras', lang, '-- Select --', ())
  825. # If translation is the same as source, it means translation not found or not loaded
  826. if translated_text == '-- Select --' and lang != 'en_US':
  827. # Check if translation exists in loaded translations
  828. translated_text = translations.get('-- Select --', '-- Select --')
  829. default_option.text = translated_text
  830. except Exception:
  831. # Fallback: use direct translation mapping based on language
  832. translations_map = {
  833. 'es_MX': '-- Seleccionar --',
  834. 'es_ES': '-- Seleccionar --',
  835. 'es': '-- Seleccionar --',
  836. }
  837. default_option.text = translations_map.get(lang, '-- Select --')
  838. # Populate selection options
  839. if selection_options:
  840. # Use custom selection options
  841. for option_value, option_label in selection_options:
  842. option = etree.SubElement(input_el, 'option', {
  843. 'value': str(option_value)
  844. })
  845. option.text = option_label
  846. if template_field.default_value and str(template_field.default_value) == str(option_value):
  847. option.set('selected', 'selected')
  848. else:
  849. # Get from model field definition with language context
  850. model_name = field.model_id.model
  851. model = env[model_name]
  852. if hasattr(model, field_name):
  853. model_field = model._fields.get(field_name)
  854. if model_field and hasattr(model_field, 'selection'):
  855. # Use _description_selection method which handles translation correctly
  856. try:
  857. if hasattr(model_field, '_description_selection'):
  858. # This method returns translated options when env has lang context
  859. selection = model_field._description_selection(env)
  860. if isinstance(selection, (list, tuple)):
  861. for option_value, option_label in selection:
  862. option = etree.SubElement(input_el, 'option', {
  863. 'value': str(option_value)
  864. })
  865. option.text = option_label
  866. if template_field.default_value and str(template_field.default_value) == str(option_value):
  867. option.set('selected', 'selected')
  868. else:
  869. # Fallback: use get_field_selection from ir.model.fields
  870. selection = env['ir.model.fields'].get_field_selection(model_name, field_name)
  871. if isinstance(selection, (list, tuple)):
  872. for option_value, option_label in selection:
  873. option = etree.SubElement(input_el, 'option', {
  874. 'value': str(option_value)
  875. })
  876. option.text = option_label
  877. if template_field.default_value and str(template_field.default_value) == str(option_value):
  878. option.set('selected', 'selected')
  879. except Exception:
  880. # Fallback: get selection directly
  881. selection = model_field.selection
  882. if callable(selection):
  883. selection = selection(model)
  884. if isinstance(selection, (list, tuple)):
  885. for option_value, option_label in selection:
  886. option = etree.SubElement(input_el, 'option', {
  887. 'value': str(option_value)
  888. })
  889. option.text = option_label
  890. if template_field.default_value and str(template_field.default_value) == str(option_value):
  891. option.set('selected', 'selected')
  892. elif field.selection:
  893. try:
  894. # Evaluate selection string if it's stored as string
  895. selection = eval(field.selection) if isinstance(field.selection, str) else field.selection
  896. if isinstance(selection, (list, tuple)):
  897. for option_value, option_label in selection:
  898. option = etree.SubElement(input_el, 'option', {
  899. 'value': str(option_value)
  900. })
  901. option.text = option_label
  902. if template_field.default_value and str(template_field.default_value) == str(option_value):
  903. option.set('selected', 'selected')
  904. except Exception:
  905. pass # If selection can't be evaluated, just leave default option
  906. elif field_type in ('integer', 'float'):
  907. # Number input (exactly as form builder does)
  908. input_type = 'number'
  909. input_el = etree.SubElement(input_div, 'input', {
  910. 'type': input_type,
  911. 'class': 'form-control s_website_form_input',
  912. 'name': field_name,
  913. 'id': field_id
  914. })
  915. if template_field.placeholder:
  916. input_el.set('placeholder', template_field.placeholder)
  917. if template_field.default_value:
  918. input_el.set('value', template_field.default_value)
  919. if field_type == 'integer':
  920. input_el.set('step', '1')
  921. else:
  922. input_el.set('step', 'any')
  923. if required:
  924. input_el.set('required', '1')
  925. elif field_type == 'many2one':
  926. # Determine selection type (dropdown or radio) - same as Odoo formbuilder
  927. selection_type = template_field.selection_type if template_field.selection_type else 'dropdown'
  928. if selection_type == 'radio':
  929. # Radio buttons for many2one
  930. radio_wrapper = etree.SubElement(input_div, 'div', {
  931. 'class': 'row s_col_no_resize s_col_no_bgcolor s_website_form_multiple',
  932. 'data-name': field_name,
  933. 'data-display': 'horizontal'
  934. })
  935. # Load records from relation with language context
  936. relation = field.relation
  937. if relation and relation != 'ir.attachment':
  938. try:
  939. domain = self._get_relation_domain(relation, env)
  940. records = env[relation].sudo().search_read(
  941. domain, ['display_name'], limit=1000
  942. )
  943. for record in records:
  944. radio_div = etree.SubElement(radio_wrapper, 'div', {
  945. 'class': 'radio col-12 col-lg-4 col-md-6'
  946. })
  947. form_check = etree.SubElement(radio_div, 'div', {
  948. 'class': 'form-check'
  949. })
  950. radio_input = etree.SubElement(form_check, 'input', {
  951. 'type': 'radio',
  952. 'class': 's_website_form_input form-check-input',
  953. 'name': field_name,
  954. 'id': f'{field_id}_{record["id"]}',
  955. 'value': str(record['id'])
  956. })
  957. if required:
  958. radio_input.set('required', '1')
  959. if template_field.default_value and str(template_field.default_value) == str(record['id']):
  960. radio_input.set('checked', 'checked')
  961. radio_label = etree.SubElement(form_check, 'label', {
  962. 'class': 'form-check-label',
  963. 'for': radio_input.get('id')
  964. })
  965. radio_label.text = record['display_name']
  966. except Exception:
  967. pass
  968. input_el = radio_wrapper
  969. else:
  970. # Default: Select dropdown for many2one
  971. input_el = etree.SubElement(input_div, 'select', {
  972. 'class': 'form-select s_website_form_input',
  973. 'name': field_name,
  974. 'id': field_id
  975. })
  976. if template_field.placeholder:
  977. input_el.set('placeholder', template_field.placeholder)
  978. if required:
  979. input_el.set('required', '1')
  980. # Add default option - translate using website language context
  981. default_option = etree.SubElement(input_el, 'option', {'value': ''})
  982. # Get translation using the environment's language context
  983. # Load translations explicitly and get translated text
  984. lang = env.lang or 'en_US'
  985. try:
  986. from odoo.tools.translate import get_translation, code_translations
  987. # Force load translations by accessing them (this triggers _load_python_translations)
  988. translations = code_translations.get_python_translations('helpdesk_extras', lang)
  989. translated_text = get_translation('helpdesk_extras', lang, '-- Select --', ())
  990. # If translation is the same as source, it means translation not found or not loaded
  991. if translated_text == '-- Select --' and lang != 'en_US':
  992. # Check if translation exists in loaded translations
  993. translated_text = translations.get('-- Select --', '-- Select --')
  994. default_option.text = translated_text
  995. except Exception:
  996. # Fallback: use direct translation mapping based on language
  997. translations_map = {
  998. 'es_MX': '-- Seleccionar --',
  999. 'es_ES': '-- Seleccionar --',
  1000. 'es': '-- Seleccionar --',
  1001. }
  1002. default_option.text = translations_map.get(lang, '-- Select --')
  1003. # Load records dynamically from relation with language context
  1004. relation = field.relation
  1005. if relation and relation != 'ir.attachment':
  1006. try:
  1007. # Try to get records from the relation model with language context
  1008. domain = self._get_relation_domain(relation, env)
  1009. records = env[relation].sudo().search_read(
  1010. domain, ['display_name'], limit=1000
  1011. )
  1012. for record in records:
  1013. option = etree.SubElement(input_el, 'option', {
  1014. 'value': str(record['id'])
  1015. })
  1016. option.text = record['display_name']
  1017. if template_field.default_value and str(template_field.default_value) == str(record['id']):
  1018. option.set('selected', 'selected')
  1019. except Exception:
  1020. # If relation doesn't exist or access denied, try specific cases with language context
  1021. if field_name == 'request_type_id':
  1022. request_types = env['helpdesk.request.type'].sudo().search([('active', '=', True)])
  1023. for req_type in request_types:
  1024. option = etree.SubElement(input_el, 'option', {
  1025. 'value': str(req_type.id)
  1026. })
  1027. option.text = req_type.name
  1028. elif field_name == 'affected_module_id':
  1029. modules = env['helpdesk.affected.module'].sudo().search([
  1030. ('active', '=', True)
  1031. ], order='name')
  1032. for module in modules:
  1033. option = etree.SubElement(input_el, 'option', {
  1034. 'value': str(module.id)
  1035. })
  1036. option.text = module.name
  1037. elif field_type in ('date', 'datetime'):
  1038. # Date/Datetime field - NUEVO: soporte para fechas
  1039. date_wrapper = etree.SubElement(input_div, 'div', {
  1040. 'class': f's_website_form_{field_type} input-group date'
  1041. })
  1042. input_el = etree.SubElement(date_wrapper, 'input', {
  1043. 'type': 'text',
  1044. 'class': 'form-control datetimepicker-input s_website_form_input',
  1045. 'name': field_name,
  1046. 'id': field_id
  1047. })
  1048. if template_field.placeholder:
  1049. input_el.set('placeholder', template_field.placeholder)
  1050. if template_field.default_value:
  1051. input_el.set('value', template_field.default_value)
  1052. if required:
  1053. input_el.set('required', '1')
  1054. # Add calendar icon
  1055. icon_div = etree.SubElement(date_wrapper, 'div', {
  1056. 'class': 'input-group-text o_input_group_date_icon'
  1057. })
  1058. icon = etree.SubElement(icon_div, 'i', {'class': 'fa fa-calendar'})
  1059. elif field_type == 'binary':
  1060. # Binary field (file upload) - NUEVO: soporte para archivos
  1061. input_el = etree.SubElement(input_div, 'input', {
  1062. 'type': 'file',
  1063. 'class': 'form-control s_website_form_input',
  1064. 'name': field_name,
  1065. 'id': field_id
  1066. })
  1067. if required:
  1068. input_el.set('required', '1')
  1069. elif field_type in ('one2many', 'many2many'):
  1070. # One2many/Many2many fields - NUEVO: soporte para checkboxes múltiples
  1071. if field.relation == 'ir.attachment':
  1072. # Binary one2many (file upload multiple)
  1073. input_el = etree.SubElement(input_div, 'input', {
  1074. 'type': 'file',
  1075. 'class': 'form-control s_website_form_input',
  1076. 'name': field_name,
  1077. 'id': field_id,
  1078. 'multiple': ''
  1079. })
  1080. if required:
  1081. input_el.set('required', '1')
  1082. else:
  1083. # Generic one2many/many2many as checkboxes
  1084. multiple_div = etree.SubElement(input_div, 'div', {
  1085. 'class': 'row s_col_no_resize s_col_no_bgcolor s_website_form_multiple',
  1086. 'data-name': field_name,
  1087. 'data-display': 'horizontal'
  1088. })
  1089. # Try to load records from relation with language context
  1090. relation = field.relation
  1091. if relation:
  1092. try:
  1093. domain = self._get_relation_domain(relation, env)
  1094. records = env[relation].sudo().search_read(
  1095. domain, ['display_name'], limit=100
  1096. )
  1097. for record in records:
  1098. checkbox_div = etree.SubElement(multiple_div, 'div', {
  1099. 'class': 'checkbox col-12 col-lg-4 col-md-6'
  1100. })
  1101. form_check = etree.SubElement(checkbox_div, 'div', {
  1102. 'class': 'form-check'
  1103. })
  1104. checkbox_input = etree.SubElement(form_check, 'input', {
  1105. 'type': 'checkbox',
  1106. 'class': 's_website_form_input form-check-input',
  1107. 'name': field_name,
  1108. 'id': f'{field_id}_{record["id"]}',
  1109. 'value': str(record['id'])
  1110. })
  1111. checkbox_label = etree.SubElement(form_check, 'label', {
  1112. 'class': 'form-check-label s_website_form_check_label',
  1113. 'for': f'{field_id}_{record["id"]}'
  1114. })
  1115. checkbox_label.text = record['display_name']
  1116. except Exception:
  1117. pass # If relation doesn't exist or access denied
  1118. elif field_type == 'monetary':
  1119. # Monetary field - NUEVO: soporte para montos
  1120. input_el = etree.SubElement(input_div, 'input', {
  1121. 'type': 'number',
  1122. 'class': 'form-control s_website_form_input',
  1123. 'name': field_name,
  1124. 'id': field_id,
  1125. 'step': 'any'
  1126. })
  1127. if required:
  1128. input_el.set('required', '1')
  1129. else:
  1130. # Default: text input (char) - Use input_type from template_field (default 'text', same as Odoo formbuilder)
  1131. input_type_value = template_field.input_type if template_field.input_type else 'text'
  1132. input_el = etree.SubElement(input_div, 'input', {
  1133. 'type': input_type_value,
  1134. 'class': 'form-control s_website_form_input',
  1135. 'name': field_name,
  1136. 'id': field_id
  1137. })
  1138. if template_field.placeholder:
  1139. input_el.set('placeholder', template_field.placeholder)
  1140. if template_field.default_value:
  1141. input_el.set('value', template_field.default_value)
  1142. if required:
  1143. input_el.set('required', '1')
  1144. # Add help text description if provided (exactly as form builder does)
  1145. if template_field.help_text:
  1146. help_text_div = etree.SubElement(input_div, 'div', {
  1147. 'class': 's_website_form_field_description small form-text text-muted'
  1148. })
  1149. # Parse HTML help text and add as content
  1150. try:
  1151. # html.fromstring may wrap content in <html><body>, so we need to handle that
  1152. help_html = html.fragment_fromstring(template_field.help_text, create_parent='div')
  1153. # Copy all children and text from the parsed HTML
  1154. if help_html is not None:
  1155. # If fragment_fromstring created a wrapper div, get its children
  1156. if len(help_html) > 0:
  1157. for child in help_html:
  1158. help_text_div.append(child)
  1159. elif help_html.text:
  1160. help_text_div.text = help_html.text
  1161. else:
  1162. # Fallback: use text content
  1163. help_text_div.text = help_html.text_content() or template_field.help_text
  1164. else:
  1165. help_text_div.text = template_field.help_text
  1166. except Exception as e:
  1167. # Fallback: use plain text or raw HTML
  1168. _logger.warning(f"Error parsing help_text HTML for field {field_name}: {e}")
  1169. # Try to set as raw HTML (Odoo's HTML fields are sanitized, so this should be safe)
  1170. try:
  1171. # Use etree to parse and append raw HTML
  1172. raw_html = etree.fromstring(f'<div>{template_field.help_text}</div>')
  1173. for child in raw_html:
  1174. help_text_div.append(child)
  1175. if not len(help_text_div):
  1176. help_text_div.text = template_field.help_text
  1177. except Exception:
  1178. # Final fallback: plain text
  1179. help_text_div.text = template_field.help_text
  1180. return field_div, field_id_counter
  1181. def apply_workflow_template(self):
  1182. """Apply workflow template to create stages and SLAs for this team
  1183. This method creates real helpdesk.stage and helpdesk.sla records
  1184. based on the workflow template configuration.
  1185. """
  1186. self.ensure_one()
  1187. if not self.workflow_template_id:
  1188. raise ValueError(_("No workflow template selected"))
  1189. template = self.workflow_template_id
  1190. if not template.active:
  1191. raise ValueError(_("The selected workflow template is not active"))
  1192. # Mapping: stage_template_id -> real_stage_id
  1193. stage_mapping = {}
  1194. # 1. Create real stages from template stages
  1195. for stage_template in template.stage_template_ids.sorted('sequence'):
  1196. stage_vals = {
  1197. 'name': stage_template.name,
  1198. 'sequence': stage_template.sequence,
  1199. 'fold': stage_template.fold,
  1200. 'description': stage_template.description or False,
  1201. 'template_id': stage_template.template_id_email.id if stage_template.template_id_email else False,
  1202. 'legend_blocked': stage_template.legend_blocked,
  1203. 'legend_done': stage_template.legend_done,
  1204. 'legend_normal': stage_template.legend_normal,
  1205. 'team_ids': [(4, self.id)],
  1206. }
  1207. real_stage = self.env['helpdesk.stage'].create(stage_vals)
  1208. stage_mapping[stage_template.id] = real_stage.id
  1209. # 2. Create real SLAs from template SLAs
  1210. for sla_template in template.sla_template_ids.sorted('sequence'):
  1211. # Get real stage ID from mapping
  1212. real_stage_id = stage_mapping.get(sla_template.stage_template_id.id)
  1213. if not real_stage_id:
  1214. _logger.warning(
  1215. f"Skipping SLA template '{sla_template.name}': "
  1216. f"stage template {sla_template.stage_template_id.id} not found in mapping"
  1217. )
  1218. continue
  1219. # Get real exclude stage IDs - map template stages to real stages
  1220. exclude_stage_ids = []
  1221. for exclude_template_stage in sla_template.exclude_stage_template_ids:
  1222. if exclude_template_stage.id in stage_mapping:
  1223. exclude_stage_ids.append(stage_mapping[exclude_template_stage.id])
  1224. else:
  1225. _logger.warning(
  1226. f"SLA template '{sla_template.name}': "
  1227. f"exclude stage template {exclude_template_stage.id} ({exclude_template_stage.name}) "
  1228. f"not found in stage mapping. Skipping."
  1229. )
  1230. sla_vals = {
  1231. 'name': sla_template.name,
  1232. 'description': sla_template.description or False,
  1233. 'team_id': self.id,
  1234. 'stage_id': real_stage_id,
  1235. 'time': sla_template.time,
  1236. 'priority': sla_template.priority,
  1237. 'tag_ids': [(6, 0, sla_template.tag_ids.ids)],
  1238. 'exclude_stage_ids': [(6, 0, exclude_stage_ids)],
  1239. 'active': True,
  1240. }
  1241. created_sla = self.env['helpdesk.sla'].create(sla_vals)
  1242. _logger.info(
  1243. f"Created SLA '{created_sla.name}' with {len(exclude_stage_ids)} excluded stage(s): "
  1244. f"{[self.env['helpdesk.stage'].browse(sid).name for sid in exclude_stage_ids]}"
  1245. )
  1246. # 3. Ensure team has use_sla enabled if template has SLAs
  1247. if template.sla_template_ids and not self.use_sla:
  1248. self.use_sla = True
  1249. return {
  1250. 'type': 'ir.actions.client',
  1251. 'tag': 'display_notification',
  1252. 'params': {
  1253. 'title': _('Workflow Template Applied'),
  1254. 'message': _(
  1255. 'Successfully created %d stage(s) and %d SLA policy(ies) from template "%s".',
  1256. len(stage_mapping),
  1257. len(template.sla_template_ids),
  1258. template.name
  1259. ),
  1260. 'type': 'success',
  1261. 'sticky': False,
  1262. }
  1263. }