Files
Odoo-Modules/fusion_repairs/models/repair_order.py
gsinghpal c506b53dec feat(fusion_repairs): Bundle 3 - reminders + upsells (X2 + X4 + M3)
X2 Day-before visit reminder email
- New cron 'Fusion Repairs: Day-before visit reminders' (daily at 08:00)
  walks repair.order records with at least one linked
  fusion.technician.task scheduled for tomorrow and not yet reminded.
- Sends mail.template email_template_visit_day_before to the client.
- New x_fc_day_before_reminder_sent flag (copy=False) so the cron
  never re-sends the same reminder.
- Template uses 4px blue accent, 600px max-width, shows the scheduled
  date + technician name + equipment, with a 'reply to reschedule' note.
- Verified: cron flagged the test repair x_fc_day_before_reminder_sent=True
  after running.

X4 Post-visit NPS / Google review email
- New cron 'Fusion Repairs: Send post-visit NPS emails' (hourly)
  finds repairs in state='done' with write_date >= 24h ago and no NPS
  email sent. Sends mail.template email_template_post_visit_nps.
- New x_fc_nps_email_sent flag so we never re-pester clients.
- Template uses 4px green accent + 'Leave a Google review' CTA button
  linking to res.company.x_fc_google_review_url (or a sensible Google
  search fallback when the company hasn't configured a review URL).

M3 Loaner auto-offer for long-running repairs
- Soft-bridges fusion_loaners_management without a hard dep -
  cron_offer_loaner_for_long_repairs returns immediately if the
  fusion.loaner.checkout model isn't installed.
- Walks repair.order records open longer than
  fusion_repairs.loaner_offer_threshold_days (ICP, default 3 days)
  with no existing loaner-offer activity.
- Posts a 'Repair: Offer Loaner' activity (new mail.activity.type)
  assigned to the repair responsible.
- New x_fc_loaner_offered flag to prevent daily re-posting.
- Manual 'Offer Loaner' button on repair header opens the
  fusion.loaner.checkout wizard pre-filled with partner + SO.
- Daily cron runs at 08:30.

Email + ICP + cron wiring:
- 2 new mail.template records (visit_day_before, post_visit_nps)
- 1 new mail.activity.type (loaner_offer)
- 3 new ir.cron records (day-before, NPS, loaner)
- 1 new ir.config_parameter (loaner_offer_threshold_days)
- 1 new header button (Offer Loaner) on repair.order

Verified end-to-end on local westin-v19:
  X2 setup repair: RO-202605-12 task: TASK-00045
     day-before flag after cron: True (expected True)
  M3 loaner model not installed - cron correctly no-op'd
  (no flag set, no activity posted, no error - the soft-dep guard works)

Bumped to 19.0.1.3.0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-20 23:59:40 -04:00

553 lines
21 KiB
Python

# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
INTAKE_SOURCES = [
('backend_wizard', 'Backend Wizard (CS)'),
('sales_rep_portal', 'Sales Rep Portal'),
('client_portal', 'Client Self-Service'),
('manual', 'Manual / Other'),
]
URGENCY_LEVELS = [
('normal', 'Normal'),
('urgent', 'Urgent'),
('safety', 'Safety Issue'),
]
class RepairOrder(models.Model):
"""Extend Odoo Repairs with intake context, dispatch link, warranty
determination, and pricing variance tracking for Fusion Repairs."""
_inherit = 'repair.order'
# ------------------------------------------------------------------
# CREATE - replace the picking-type default sequence with our
# date-based RO-YYYYMM-NN reference. We set vals['name'] BEFORE
# super() so Odoo's native create() (which only assigns the picking
# type sequence when name is empty or 'New') skips its own numbering.
# ------------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
Sequence = self.env['ir.sequence'].sudo()
for vals in vals_list:
if not vals.get('name') or vals.get('name') == 'New':
next_name = Sequence.next_by_code('fusion.repair.order.monthly')
if next_name:
vals['name'] = next_name
return super().create(vals_list)
# ------------------------------------------------------------------
# INTAKE METADATA
# ------------------------------------------------------------------
x_fc_intake_source = fields.Selection(
INTAKE_SOURCES,
string='Intake Source',
default='manual',
tracking=True,
help='Which intake surface created this repair (backend CS wizard, '
'sales rep portal, public client portal, or manual entry).',
)
x_fc_intake_user_id = fields.Many2one(
'res.users',
string='Intake By',
tracking=True,
index=True,
help='User who took the call / submitted the intake. For client portal, '
'this is the OdooBot or admin user.',
)
x_fc_intake_session_id = fields.Char(
string='Intake Session',
index=True,
copy=False,
help='Reference shared by multiple repair orders created during the same call.',
)
x_fc_intake_template_id = fields.Many2one(
'fusion.repair.intake.template',
string='Intake Template',
help='Question template used during intake.',
)
x_fc_intake_answer_ids = fields.One2many(
'fusion.repair.intake.answer',
'repair_id',
string='Intake Answers',
)
# Catalogue match (Phase 2)
x_fc_service_catalog_id = fields.Many2one(
'fusion.repair.service.catalog',
string='Service Catalogue Match',
index=True,
help='Auto-matched catalogue entry that pre-fills estimated cost and duration.',
)
# C6: quote-only flag (set when intake submitted in quote-only mode).
x_fc_is_quote_only = fields.Boolean(
string='Quote Only',
tracking=True,
index=True,
help='True when the intake was submitted in "Quote Only" mode - the '
'office has not yet authorised dispatching a technician.',
)
# ------------------------------------------------------------------
# ON-CALL PAGING (CL15)
# Set when a safety repair is paged to the on-call manager. Allows
# ack and the 15-minute escalation cron to roll forward to the next
# priority if not acknowledged.
# ------------------------------------------------------------------
x_fc_on_call_token = fields.Char(
string='On-Call Ack Token',
copy=False,
index=True,
)
x_fc_on_call_paged_user_id = fields.Many2one(
'res.users',
string='On-Call Paged User',
copy=False,
index=True,
)
x_fc_on_call_paged_at = fields.Datetime(
string='On-Call Paged At',
copy=False,
)
x_fc_on_call_acknowledged_user_ids = fields.Many2many(
'res.users',
'fusion_repair_on_call_ack_rel',
'repair_id', 'user_id',
string='On-Call Acknowledgements',
copy=False,
)
x_fc_on_call_acknowledged_at = fields.Datetime(
string='Acknowledged At',
copy=False,
)
_on_call_token_unique = models.Constraint(
'unique(x_fc_on_call_token)',
'On-call acknowledgement tokens must be unique.',
)
# ------------------------------------------------------------------
# X2 / X4 - reminder + NPS sent-at flags (so the cron doesn't re-send)
# ------------------------------------------------------------------
x_fc_day_before_reminder_sent = fields.Boolean(
string='Day-Before Reminder Sent',
copy=False,
)
x_fc_nps_email_sent = fields.Boolean(
string='NPS Email Sent',
copy=False,
)
# ------------------------------------------------------------------
# X2 / X4 / M3 - reminder + NPS crons + loaner offer
# ------------------------------------------------------------------
@api.model
def cron_send_day_before_reminders(self):
"""X2: email the client the day before a scheduled tech visit.
Walks repair.order records with a linked technician task scheduled
for tomorrow, sends one reminder per repair, marks
x_fc_day_before_reminder_sent=True so we never re-send.
"""
if not self._notifications_enabled():
return
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
# Find repairs with at least one task scheduled tomorrow that haven't
# been reminded yet.
repairs = self.search([
('x_fc_day_before_reminder_sent', '=', False),
('state', 'not in', ('done', 'cancel')),
('x_fc_technician_task_ids.scheduled_date', '=', tomorrow),
])
tpl = self.env.ref(
'fusion_repairs.email_template_visit_day_before',
raise_if_not_found=False,
)
if not tpl:
return
for r in repairs:
if not r.partner_id or not r.partner_id.email:
continue
try:
tpl.send_mail(r.id, force_send=False)
r.x_fc_day_before_reminder_sent = True
except Exception:
continue
@api.model
def cron_send_post_visit_nps(self):
"""X4: send NPS / Google review email 24h after a repair is done."""
if not self._notifications_enabled():
return
from datetime import datetime, timedelta
cutoff = datetime.now() - timedelta(hours=24)
repairs = self.search([
('state', '=', 'done'),
('x_fc_nps_email_sent', '=', False),
('write_date', '<=', cutoff),
])
tpl = self.env.ref(
'fusion_repairs.email_template_post_visit_nps',
raise_if_not_found=False,
)
if not tpl:
return
for r in repairs:
if not r.partner_id or not r.partner_id.email:
continue
try:
tpl.send_mail(r.id, force_send=False)
r.x_fc_nps_email_sent = True
except Exception:
continue
@api.model
def cron_offer_loaner_for_long_repairs(self):
"""M3: post an Offer-Loaner activity when an open repair has been
sitting longer than fusion_repairs.loaner_offer_threshold_days
AND has no linked loaner checkout yet.
Soft-depends on fusion_loaners_management - silently no-ops when
the loaner model isn't installed.
"""
if not self.env.get('fusion.loaner.checkout'):
return
ICP = self.env['ir.config_parameter'].sudo()
try:
threshold = int(ICP.get_param(
'fusion_repairs.loaner_offer_threshold_days', '3'
))
except (ValueError, TypeError):
threshold = 3
from datetime import datetime, timedelta
cutoff = datetime.now() - timedelta(days=threshold)
repairs = self.search([
('state', 'not in', ('done', 'cancel')),
('create_date', '<=', cutoff),
('x_fc_loaner_offered', '=', False),
])
activity_type = self.env.ref(
'fusion_repairs.mail_activity_type_loaner_offer',
raise_if_not_found=False,
)
for r in repairs:
try:
r.activity_schedule(
activity_type_id=activity_type.id if activity_type else False,
summary='Offer a loaner unit',
note=(
'This repair has been open for more than %s days. '
'Consider offering the client a loaner unit while we '
'complete the repair.'
) % threshold,
user_id=r.user_id.id or self.env.uid,
)
r.x_fc_loaner_offered = True
except Exception:
continue
x_fc_loaner_offered = fields.Boolean(
string='Loaner Offered',
copy=False,
help='True once a loaner-offer activity has been posted for this '
'long-running repair (M3). Avoids re-posting daily.',
)
@api.model
def _notifications_enabled(self):
ICP = self.env['ir.config_parameter'].sudo()
return ICP.get_param(
'fusion_repairs.enable_email_notifications', 'True'
) == 'True'
def action_offer_loaner(self):
"""Open the fusion_loaners_management checkout wizard pre-filled
with this repair's partner. Soft-link - raises if the module is
not installed."""
self.ensure_one()
Checkout = self.env.get('fusion.loaner.checkout')
if not Checkout:
raise UserError(_(
'Loaner management is not installed. Install '
'fusion_loaners_management to enable this feature.'
))
return {
'type': 'ir.actions.act_window',
'name': _('Offer Loaner'),
'res_model': 'fusion.loaner.checkout',
'view_mode': 'form',
'target': 'new',
'context': {
'default_partner_id': self.partner_id.id,
'default_sale_order_id': self.sale_order_id.id or False,
},
}
# Maintenance contract back-link (Phase 3)
x_fc_maintenance_contract_id = fields.Many2one(
'fusion.repair.maintenance.contract',
string='Maintenance Contract',
index=True,
help='Set when this repair was spawned from a maintenance reminder booking. '
'Completing the related technician task rolls the contract to its next cycle.',
)
x_fc_intake_answer_count = fields.Integer(
compute='_compute_intake_answer_count',
)
# ------------------------------------------------------------------
# EQUIPMENT / WARRANTY
# ------------------------------------------------------------------
x_fc_repair_category_id = fields.Many2one(
'fusion.repair.product.category',
string='Equipment Category',
tracking=True,
index=True,
help='Medical equipment category - drives intake template and tech skills filter.',
)
x_fc_third_party_equipment = fields.Boolean(
string='Third-Party Equipment',
tracking=True,
help='True if the equipment was not sold by us. Forces under_warranty=False '
'and typically triggers a service call-out fee.',
)
x_fc_original_sale_order_id = fields.Many2one(
'sale.order',
string='Original Purchase SO',
tracking=True,
index=True,
help='Sale order through which the customer originally purchased this unit. '
'Auto-matched on intake by partner + lot/serial.',
)
x_fc_warranty_override_reason = fields.Char(
string='Warranty Override Reason',
help='Required when CS overrides the auto-detected warranty status.',
)
# ------------------------------------------------------------------
# TRIAGE / URGENCY
# ------------------------------------------------------------------
x_fc_urgency = fields.Selection(
URGENCY_LEVELS,
string='Urgency',
default='normal',
tracking=True,
index=True,
)
x_fc_issue_category = fields.Char(
string='Issue Category',
help='Symptom classification (e.g. "battery", "motor", "remote"). Used by '
'service catalogue matcher and AI prompt context.',
)
# ------------------------------------------------------------------
# PHOTOS
# ------------------------------------------------------------------
x_fc_photo_ids = fields.Many2many(
'ir.attachment',
'fusion_repair_order_photo_rel',
'repair_id',
'attachment_id',
string='Intake Photos / Videos',
help='Photos and videos uploaded during intake.',
)
x_fc_photo_count = fields.Integer(
compute='_compute_photo_count',
)
# ------------------------------------------------------------------
# PRICING (estimate vs actual - Phase 2 reconciliation)
# ------------------------------------------------------------------
x_fc_estimated_duration = fields.Float(
string='Estimated Duration (h)',
help='Estimated visit duration from service catalogue, used to size technician slot.',
)
x_fc_estimated_cost = fields.Monetary(
string='Estimated Cost',
currency_field='company_currency_id',
help='Estimated total from catalogue match at intake (pre-visit).',
)
x_fc_actual_cost = fields.Monetary(
string='Actual Cost',
currency_field='company_currency_id',
help='Actual total recorded from the visit report (post-visit).',
)
x_fc_cost_variance_pct = fields.Float(
string='Cost Variance %',
compute='_compute_cost_variance',
store=True,
help='(actual - estimated) / estimated * 100',
)
x_fc_requires_requote = fields.Boolean(
string='Requires Re-Quote',
help='Set when actual cost exceeds estimate beyond the configured threshold; '
'blocks automatic invoicing until manager approves or client re-confirms.',
)
company_currency_id = fields.Many2one(
'res.currency',
related='company_id.currency_id',
readonly=True,
)
# ------------------------------------------------------------------
# FIELD SERVICE LINK
# ------------------------------------------------------------------
x_fc_technician_task_ids = fields.One2many(
'fusion.technician.task',
'x_fc_repair_order_id',
string='Technician Tasks',
)
x_fc_technician_task_count = fields.Integer(
compute='_compute_technician_task_count',
)
# ------------------------------------------------------------------
# AI SUMMARY (Phase 2)
# ------------------------------------------------------------------
x_fc_ai_summary = fields.Text(
string='AI Pre-Visit Brief',
help='AI-generated short brief for the technician based on intake answers. '
'Optional - never blocks intake submit.',
)
# ------------------------------------------------------------------
# COMPUTES
# ------------------------------------------------------------------
@api.depends('x_fc_intake_answer_ids')
def _compute_intake_answer_count(self):
for repair in self:
repair.x_fc_intake_answer_count = len(repair.x_fc_intake_answer_ids)
@api.depends('x_fc_photo_ids')
def _compute_photo_count(self):
for repair in self:
repair.x_fc_photo_count = len(repair.x_fc_photo_ids)
@api.depends('x_fc_technician_task_ids')
def _compute_technician_task_count(self):
for repair in self:
repair.x_fc_technician_task_count = len(repair.x_fc_technician_task_ids)
@api.depends('x_fc_estimated_cost', 'x_fc_actual_cost')
def _compute_cost_variance(self):
for repair in self:
if repair.x_fc_estimated_cost:
repair.x_fc_cost_variance_pct = (
(repair.x_fc_actual_cost - repair.x_fc_estimated_cost)
/ repair.x_fc_estimated_cost * 100
)
else:
repair.x_fc_cost_variance_pct = 0.0
# ------------------------------------------------------------------
# WARRANTY DETERMINATION
# ------------------------------------------------------------------
def _fc_compute_warranty_status(self):
"""Auto-detect warranty: not third-party AND within warranty window."""
self.ensure_one()
if self.x_fc_third_party_equipment:
return False
if not self.x_fc_original_sale_order_id:
return False
original = self.x_fc_original_sale_order_id
delivery_date = original.commitment_date or original.date_order
if not delivery_date:
return False
warranty_months = (
self.product_id.product_tmpl_id.x_fc_warranty_months
if self.product_id else 0
)
if not warranty_months:
return False
# relativedelta handles month boundaries correctly (28/29/30/31).
cutoff = fields.Datetime.from_string(str(delivery_date)) + relativedelta(months=warranty_months)
return fields.Datetime.now() <= cutoff
# ------------------------------------------------------------------
# SMART BUTTONS
# ------------------------------------------------------------------
def action_view_intake_answers(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _('Intake Answers'),
'res_model': 'fusion.repair.intake.answer',
'view_mode': 'list,form',
'domain': [('repair_id', '=', self.id)],
'context': {'default_repair_id': self.id},
}
def action_view_technician_tasks(self):
self.ensure_one()
if len(self.x_fc_technician_task_ids) == 1:
return {
'type': 'ir.actions.act_window',
'name': self.x_fc_technician_task_ids.name,
'res_model': 'fusion.technician.task',
'view_mode': 'form',
'res_id': self.x_fc_technician_task_ids.id,
}
return {
'type': 'ir.actions.act_window',
'name': _('Technician Tasks'),
'res_model': 'fusion.technician.task',
'view_mode': 'list,form',
'domain': [('x_fc_repair_order_id', '=', self.id)],
'context': {'default_x_fc_repair_order_id': self.id},
}
def action_view_original_sale_order(self):
self.ensure_one()
if not self.x_fc_original_sale_order_id:
return False
return {
'type': 'ir.actions.act_window',
'name': self.x_fc_original_sale_order_id.name,
'res_model': 'sale.order',
'view_mode': 'form',
'res_id': self.x_fc_original_sale_order_id.id,
}
# ------------------------------------------------------------------
# WIZARDS / PAYMENT
# ------------------------------------------------------------------
def action_open_visit_report(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _('Visit Report'),
'res_model': 'fusion.repair.visit.report.wizard',
'view_mode': 'form',
'target': 'new',
'context': {
'default_repair_id': self.id,
'default_labour_hours': self.x_fc_estimated_duration or 1.0,
},
}
def action_collect_payment(self):
"""Open the Poynt payment wizard for the linked posted invoice."""
self.ensure_one()
# Resolve the linked invoice via the standard repair -> SO -> invoice chain.
if not self.sale_order_id:
raise UserError(_('Confirm a sale order from this repair first.'))
invoice = self.sale_order_id.invoice_ids.filtered(
lambda m: m.state == 'posted' and m.payment_state in ('not_paid', 'partial')
)[:1]
if not invoice:
raise UserError(_('No posted, unpaid invoice was found for this repair.'))
if hasattr(invoice, 'action_open_poynt_payment_wizard'):
return invoice.action_open_poynt_payment_wizard()
raise UserError(_('Poynt payment is not available - install or configure fusion_poynt.'))