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.

61 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_invoice, journal=None):
  30. invoice_vals = super(ContractContract, self)._prepare_invoice(
  31. date_invoice, journal)
  32. if self.mandate_id:
  33. invoice_vals['mandate_id'] = self.mandate_id.id
  34. elif self.payment_mode_id.payment_method_id.mandate_required:
  35. mandate = self.env['account.banking.mandate'].search([
  36. ('partner_id', '=', self.partner_id.commercial_partner_id.id),
  37. ('state', '=', 'valid'),
  38. ], limit=1)
  39. invoice_vals['mandate_id'] = mandate.id
  40. return invoice_vals
  41. @api.model
  42. def _finalize_invoice_creation(self, invoices):
  43. """
  44. This override preserves the contract when calling the partner's
  45. onchange.
  46. """
  47. mandates_by_invoice = {}
  48. for invoice in invoices:
  49. mandates_by_invoice[invoice] = invoice.mandate_id
  50. res = super(ContractContract, self)._finalize_invoice_creation(
  51. invoices)
  52. for invoice in invoices:
  53. invoice.mandate_id = mandates_by_invoice.get(invoice)
  54. return res