Files
Odoo-Modules/fusion_plating/fusion_plating_invoicing/models/sale_order.py
gsinghpal 11837ed4f5 fix(plating): Manager Desk premature-advance + 6 workflow enforcement gates
**1. Manager Desk: WO no longer jumps to "In Progress" on partial setup**

User-reported bug: when the manager picked a worker, the WO immediately
left the "Unassigned" column even though the bath/tank (or oven, rack,
masking material) wasn't set yet. Worker would see a half-set job in
their queue and couldn't start it.

Fix:
- New compute `mrp.workorder.x_fc_is_release_ready` — True only when
  every field button_start would block on is filled in.
- Companion `x_fc_missing_for_release` — comma-list of what's still
  missing (used by the UI as a hint chip).
- Manager controller swaps the column filter from
  `assigned_user_id == False` to `is_release_ready == False`.
- A WO stays in "Setup Pending" (formerly Unassigned) until BOTH
  worker + per-kind equipment are set; only then does it move to
  "In Progress".

**Manager Desk template + SCSS**

The user also said "the manager doesn't know what task they're
assigning". WO row now shows:
  • Colour-coded WO-kind badge (wet=blue, bake=red, mask=yellow,
    rack=grey, inspect=green)
  • Required-role icon + name
  • Bath / oven / rack / masking-material chips (whatever's set)
  • Yellow "Needs: ..." chip listing what's still missing
  • Tank picker only shows for wet WOs (no point on a mask WO)
  • Open-WO button to drill into the form for advanced edits

**2. Six enforcement gates patched (without breaking the workflow)**

Each gate fires AFTER the manager sets up the WO and the operator
hits Start/Finish — never on create — so the manager → worker → run
flow stays intact.

| # | Gate | Where |
|---|---|---|
| a | SO confirm requires `client_order_ref` (or x_fc_po_number) | sale_order.action_confirm |
| b | Cert issue requires thickness readings (when partner.x_fc_strict_thickness_required) | fp_certificate.action_issue |
| c | Delivery start_route requires assigned_driver_id | fp_delivery.action_start_route |
| d | Bath log create/save requires line_ids (no empty logs) | fp_bath_log create + @api.constrains |
| e | Quality hold: hold_reason + description now `required=True` | fp_quality_hold field schema |
| f | Receiving accept blocks qty mismatch (manager override allowed + logged) | fp_receiving.action_accept |

New partner flag `x_fc_strict_thickness_required` so commercial
customers don't get blocked but aerospace customers do.

**Verified** via `scripts/fp_enforcement_audit.py`: 18/22 ENFORCED
(2 "GAPS" + 2 "ERRs" are all test artifacts — admin bypass + NOT NULL
fires before my custom check; real gates are correct).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 12:54:00 -04:00

203 lines
8.4 KiB
Python

# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
# Part of the Fusion Plating product family.
import logging
from odoo import api, fields, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.onchange('partner_id')
def _onchange_partner_id_invoice_strategy(self):
"""Auto-fill invoice strategy from customer defaults."""
if self.partner_id:
default = self.env['fp.invoice.strategy.default'].search(
[('partner_id', '=', self.partner_id.id)], limit=1,
)
if default:
self.x_fc_invoice_strategy = default.default_strategy
self.x_fc_deposit_percent = default.default_deposit_percent
if default.payment_term_id:
self.payment_term_id = default.payment_term_id
def action_confirm(self):
"""Override to check account hold + customer PO# and trigger
the invoice strategy."""
for order in self:
# --- Customer PO# required ---
# Aerospace AP teams reject invoices without their PO#
# quoted back. Catching this at SO confirm prevents the
# whole downstream chain (CoC, BoL, invoice) from going
# out unreferenced. The PO# is on `client_order_ref`
# (Odoo standard) AND mirrored to `x_fc_po_number`
# (FP-specific) — accept either as filled.
po_set = bool(order.client_order_ref) or bool(
getattr(order, 'x_fc_po_number', False)
)
if not po_set:
raise UserError(_(
'Cannot confirm SO "%(so)s" — Customer PO# is required.\n\n'
'Set the customer\'s purchase order number in the '
'"Customer Reference" field (or x_fc_po_number) before '
'confirming. Aerospace customers\' AP teams reject '
'invoices that don\'t quote their PO# back.'
) % {'so': order.name})
# --- Account hold check ---
if order.partner_id.x_fc_account_hold:
is_manager = self.env.user.has_group(
'fusion_plating.group_fusion_plating_manager'
)
if not is_manager:
raise UserError(_(
'Cannot confirm — customer "%s" is on account hold.\n'
'Reason: %s\n\n'
'Contact a manager to override.'
) % (order.partner_id.name,
order.partner_id.x_fc_account_hold_reason or 'No reason specified'))
else:
order.message_post(
body=_(
'Warning: Customer "%s" is on account hold (reason: %s). '
'Order confirmed by manager override.'
) % (order.partner_id.name,
order.partner_id.x_fc_account_hold_reason or 'N/A'),
)
res = super().action_confirm()
# --- Invoice strategy automation (on confirm) ---
for order in self:
strategy = order.x_fc_invoice_strategy
if not strategy:
continue
if strategy == 'deposit' and order.x_fc_deposit_percent:
order._create_deposit_invoice()
elif strategy == 'cod_prepay':
order._create_full_invoice()
elif strategy == 'progress' and order.x_fc_progress_initial_percent:
order._create_progress_initial_invoice()
# 'net_terms' — no action on confirm; invoiced when delivery is marked delivered
return res
# ------------------------------------------------------------------
# Strategy implementations
# ------------------------------------------------------------------
def _create_deposit_invoice(self):
"""Deposit strategy: down-payment invoice for the deposit %."""
self.ensure_one()
percent = self.x_fc_deposit_percent
if not percent or percent <= 0:
return
try:
# The wizard's sale_order_ids default reads active_ids AT CREATE
# time — context must be set on .with_context(), not on the
# subsequent create_invoices() call.
wizard = self.env['sale.advance.payment.inv'].with_context(
active_ids=self.ids,
active_model='sale.order',
active_id=self.id,
).create({
'advance_payment_method': 'percentage',
'amount': percent,
})
wizard.create_invoices()
self.message_post(
body=_('Deposit invoice (%.0f%%) created — strategy: Deposit.') % percent,
)
except Exception as e:
_logger.warning('Failed to create deposit invoice for SO %s: %s', self.name, e)
self.message_post(
body=_('Failed to auto-create deposit invoice: %s. Create manually.') % str(e),
)
def _create_full_invoice(self):
"""COD / Prepay: invoice the entire order immediately."""
self.ensure_one()
try:
invoices = self._create_invoices()
if invoices:
self.message_post(
body=_('Full invoice created — strategy: COD / Prepay.'),
)
except Exception as e:
_logger.warning('Failed to create COD invoice for SO %s: %s', self.name, e)
self.message_post(
body=_('Failed to auto-create invoice: %s. Create manually.') % str(e),
)
def _create_progress_initial_invoice(self):
"""Progress Billing — first invoice at SO confirm.
Uses Odoo's down-payment mechanism to bill the initial percentage.
The remainder is billed on delivery via `_create_final_balance_invoice`.
"""
self.ensure_one()
percent = self.x_fc_progress_initial_percent
if not percent or percent <= 0:
return
try:
wizard = self.env['sale.advance.payment.inv'].with_context(
active_ids=self.ids,
active_model='sale.order',
active_id=self.id,
).create({
'advance_payment_method': 'percentage',
'amount': percent,
})
wizard.create_invoices()
self.message_post(
body=_(
'Progress invoice — initial %.0f%% created — strategy: Progress Billing. '
'Final balance will be invoiced on delivery.'
) % percent,
)
except Exception as e:
_logger.warning('Failed progress-initial invoice for SO %s: %s', self.name, e)
self.message_post(
body=_('Failed to auto-create progress invoice: %s') % str(e),
)
def _create_final_balance_invoice(self):
"""Create the closing invoice for Progress Billing / Net Terms.
Called when delivery is marked delivered. Uses the standard
`_create_invoices()` method which bills the remainder (net of any
previously-posted down payments).
"""
self.ensure_one()
if self.x_fc_final_invoice_id:
return self.x_fc_final_invoice_id # Already invoiced — don't double
if self.invoice_status == 'invoiced':
return False # Nothing more to bill
try:
invoices = self._create_invoices(final=True)
if invoices:
self.x_fc_final_invoice_id = invoices[:1].id
strategy_label = dict(
self._fields['x_fc_invoice_strategy'].selection
).get(self.x_fc_invoice_strategy, self.x_fc_invoice_strategy)
self.message_post(
body=_(
'Final invoice created on delivery — strategy: %s.'
) % strategy_label,
)
return invoices
except Exception as e:
_logger.warning('Failed final invoice for SO %s: %s', self.name, e)
self.message_post(
body=_(
'Failed to auto-create final invoice: %s. '
'Create manually from the SO.'
) % str(e),
)
return False