hr_expense_account_split/models/account_payment.py

68 lines
3.1 KiB
Python

from odoo import fields, models, api, _
from odoo.exceptions import UserError
class AccountPayment(models.Model):
_inherit = 'account.payment'
realization_id = fields.Many2one('hr.expense.realization', string='Originating Realization', readonly=True)
def action_post(self):
"""
Overriding to bypass hr_expense restriction and ensure deductions are synced.
We temporarily clear the link in the DB to avoid the 'Invalid Operation' error.
"""
for payment in self:
if payment.expense_sheet_id and payment.state == 'draft':
sheet_id = payment.expense_sheet_id.id
# 1. Clear the link in DB and Cache (Skip sync to avoid recursion)
payment.with_context(skip_account_move_synchronization=True).write({'expense_sheet_id': False})
try:
# 2. Force Sync Deductions while 'unlinked'
payment._synchronize_to_moves({'amount', 'deduction_line_ids', 'amount_substract'})
# 3. Call standard post
res = super(AccountPayment, payment).action_post()
finally:
# 4. Restore the link
payment.with_context(skip_account_move_synchronization=True).write({'expense_sheet_id': sheet_id})
else:
super(AccountPayment, payment).action_post()
return True
def _synchronize_to_moves(self, changed_fields):
# Trigger deduction sync if needed
if 'deduction_line_ids' in changed_fields or 'amount_substract' in changed_fields:
if 'amount' not in changed_fields:
changed_fields = set(changed_fields) | {'amount'}
# Bypass for manual edits
for payment in self:
if payment.expense_sheet_id and payment.state == 'draft':
sheet_id = payment.expense_sheet_id.id
payment.with_context(skip_account_move_synchronization=True).write({'expense_sheet_id': False})
try:
return super(AccountPayment, payment)._synchronize_to_moves(changed_fields)
finally:
payment.with_context(skip_account_move_synchronization=True).write({'expense_sheet_id': sheet_id})
return super()._synchronize_to_moves(changed_fields)
def action_cancel(self):
res = super().action_cancel()
for payment in self:
if payment.expense_sheet_id:
payment.expense_sheet_id.invalidate_recordset(['state'])
if payment.realization_id and payment.realization_id.expense_sheet_id:
payment.realization_id.expense_sheet_id.invalidate_recordset(['state'])
return res
def action_draft(self):
res = super().action_draft()
for payment in self:
if payment.expense_sheet_id:
payment.expense_sheet_id.invalidate_recordset(['state'])
if payment.realization_id and payment.realization_id.expense_sheet_id:
payment.realization_id.expense_sheet_id.invalidate_recordset(['state'])
return res