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.

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