Files
Odoo-Modules/fusion_repairs/models/technician_task.py
gsinghpal ef0c096e48 fix(fusion_repairs): Bundle 3 code-review fixes (H1-H5 + M1-M6 + L1)
HIGH
H1 X2 reminder flag was per-repair - multi-visit repairs missed reminders
  Moved x_fc_day_before_reminder_sent off repair.order onto
  fusion.technician.task so each scheduled visit is tracked separately.
  Cron now walks tasks directly with state-narrowed repair filter
  (confirmed/under_repair only, drops L1's draft inclusion).

H2 X4 NPS cron used write_date - moved on every chatter/invoice write
  Added x_fc_done_at Datetime on repair.order, stamped on the first
  transition to state=done via write() override. Cron filters on
  ('x_fc_done_at', '<=', cutoff) instead of write_date.

H3 X2 template's [:1] slice picked an arbitrary task, not tomorrow's
  Cron now passes the specific task via with_context(reminder_task_id=...).
  Template fetches that task by id; falls back to [:1] only for manual
  sends so chatter Send Email composer still works.

H4 NPS Google-Search fallback URL not URL-encoded - breaks on &/spaces
  Template now uses url_encode({'q': company_name}) so "Westin & Sons"
  produces a working URL instead of truncating at the ampersand.

H5 + L1 Loaner cron fired on drafts and used create_date instead of schedule_date
  Domain rewritten to: state in ('confirmed','under_repair'), exclude
  quote-only repairs, and EITHER schedule_date <= cutoff OR (schedule_date
  is False AND create_date <= cutoff). Added limit=200 ordered by
  create_date desc (M6).

MEDIUM
M1 Function-level datetime imports moved to module top
  date, datetime, timedelta imported once at the top of repair_order.py,
  removed from cron_send_day_before_reminders, cron_send_post_visit_nps,
  cron_offer_loaner_for_long_repairs.

M2 _notifications_enabled duplicated - promoted to single source
  repair_order._notifications_enabled now delegates to
  fusion.repair.intake.service._notifications_enabled() (with a fallback
  ICP read if the service AbstractModel isn't available).

M3 self.env.get('model') -> 'model' in self.env (Odoo standard idiom)
  Two call sites in repair_order.py converted.

M4 + M5 Bare 'except: continue' + missing logger - operational blindness
  Added import logging + _logger to repair_order.py. All three crons now
  log exceptions with _logger.exception(). Activity-type ref check now
  warns + returns early if the xml id is missing (instead of passing
  activity_type_id=False which raises). For X2 and X4 the flag is set
  regardless of send-success so we don't retry indefinitely on
  permanently-misconfigured partners.

M6 Loaner cron has limit=200 + order='create_date desc'
  Caps blast radius if 5000 stale draft repairs ever accumulate.

L1 X2 state filter tightened: was ('not in', ('done','cancel')), now
  ('in', ('confirmed','under_repair')) so drafts and quote-only don't
  email "your tech is coming tomorrow".

Verified - upgrade clean, no errors. Bumped to 19.0.1.3.1.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 00:07:41 -04:00

111 lines
4.2 KiB
Python

# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
from urllib.parse import quote_plus
from markupsafe import Markup
from odoo import _, fields, models
from odoo.exceptions import UserError
class FusionTechnicianTaskRepairs(models.Model):
"""Adds the back-link from fusion.technician.task to repair.order so
repairs and tasks share one timeline. Also hooks task completion to
roll a linked maintenance contract to its next cycle.
"""
_inherit = 'fusion.technician.task'
x_fc_repair_order_id = fields.Many2one(
'repair.order',
string='Repair Order',
ondelete='set null',
index=True,
tracking=True,
help='Repair order this task fulfils. Set automatically when the intake '
'wizard auto-creates a draft task for urgent / safety calls.',
)
x_fc_repair_intake_session_id = fields.Char(
related='x_fc_repair_order_id.x_fc_intake_session_id',
string='Intake Session',
store=True,
index=True,
)
# X2: per-task day-before reminder flag. Per-task (not per-repair) so
# a repair with multiple visits gets a separate reminder for each one.
x_fc_day_before_reminder_sent = fields.Boolean(
string='Day-Before Reminder Sent',
copy=False,
)
def write(self, vals):
"""When a maintenance task transitions to 'completed', roll the
linked contract to its next cycle. Failure to roll never blocks
the underlying task write.
"""
res = super().write(vals)
if vals.get('status') == 'completed':
for task in self:
if task.task_type != 'maintenance':
continue
repair = task.x_fc_repair_order_id
contract = repair.x_fc_maintenance_contract_id if repair else False
if not contract:
continue
try:
contract.last_service_date = fields.Date.context_today(task)
contract.roll_next_due_date()
contract.message_post(body=Markup(
'Rolled forward after maintenance task '
'<b>%s</b> completed. Next due %s.'
) % (task.name or '', str(contract.next_due_date or '')))
except Exception:
# Never let a contract roll failure block the task write.
pass
return res
def action_view_repair_order(self):
self.ensure_one()
if not self.x_fc_repair_order_id:
return False
return {
'type': 'ir.actions.act_window',
'name': self.x_fc_repair_order_id.name,
'res_model': 'repair.order',
'view_mode': 'form',
'res_id': self.x_fc_repair_order_id.id,
}
# ------------------------------------------------------------------
# T1: Open in Maps - returns an act_url action that opens the device's
# default maps app (Apple Maps on iOS, Google Maps on Android, browser
# otherwise). Address is built from the task's address fields with the
# partner address as a fallback.
# ------------------------------------------------------------------
def action_open_in_maps(self):
self.ensure_one()
# Prefer fusion_tasks.address_display because in real data address_street
# often contains the full Google-Places-formatted address; concatenating
# the other address_* fields would duplicate city/zip.
addr = (getattr(self, 'address_display', '') or '').strip()
if not addr and self.partner_id:
p = self.partner_id
parts = [
p.street, p.street2, p.city,
p.state_id.name if p.state_id else False,
p.zip,
p.country_id.name if p.country_id else False,
]
addr = ', '.join(str(x) for x in parts if x)
if not addr:
raise UserError(_('No address on this task or its client.'))
return {
'type': 'ir.actions.act_url',
'url': f'https://www.google.com/maps?q={quote_plus(addr)}',
'target': 'new',
}