You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.1 KiB

  1. # Copyright 2017 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import api, fields, models
  4. class ContractContract(models.Model):
  5. _inherit = 'contract.contract'
  6. mandate_id = fields.Many2one(
  7. comodel_name='account.banking.mandate',
  8. ondelete='restrict',
  9. string='Direct Debit Mandate',
  10. help="If mandate required in payment method and not set mandate, "
  11. "invoice takes the first valid mandate",
  12. index=True,
  13. )
  14. mandate_required = fields.Boolean(
  15. related='payment_mode_id.payment_method_id.mandate_required',
  16. readonly=True)
  17. commercial_partner_id = fields.Many2one(
  18. related='partner_id.commercial_partner_id',
  19. readonly=True,
  20. string='Commercial Entity',
  21. )
  22. @api.multi
  23. @api.onchange('payment_mode_id')
  24. def _onchange_payment_mode_id(self):
  25. self.ensure_one()
  26. if not self.mandate_required:
  27. self.mandate_id = False
  28. @api.multi
  29. def _prepare_invoice(self, date_ref=False):
  30. invoice_vals = super(ContractContract, self)._prepare_invoice(date_ref)
  31. if self.mandate_id:
  32. invoice_vals['mandate_id'] = self.mandate_id.id
  33. elif self.payment_mode_id.payment_method_id.mandate_required:
  34. mandate = self.env['account.banking.mandate'].search([
  35. ('partner_id', '=', self.partner_id.commercial_partner_id.id),
  36. ('state', '=', 'valid'),
  37. ], limit=1)
  38. invoice_vals['mandate_id'] = mandate.id
  39. return invoice_vals
  40. @api.model
  41. def _finalize_invoice_creation(self, invoices):
  42. """
  43. This override preserves the contract when calling the partner's
  44. onchange.
  45. """
  46. mandates_by_invoice = {}
  47. for invoice in invoices:
  48. mandates_by_invoice[invoice] = invoice.mandate_id
  49. res = super(ContractContract, self)._finalize_invoice_creation(
  50. invoices)
  51. for invoice in invoices:
  52. invoice.mandate_id = mandates_by_invoice.get(invoice)
  53. return res