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. # -*- coding: utf-8 -*-
  2. # © 2017 Therp BV <http://therp.nl>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. from openerp import api, models
  5. class ResPartner(models.Model):
  6. _inherit = 'res.partner'
  7. def find_current_relation(self, left, type_relation, right):
  8. par_rel_mod = self.env['res.partner.relation']
  9. return par_rel_mod.search([
  10. ('left_partner_id', '=', left),
  11. ('type_id', '=', type_relation),
  12. ('right_partner_id', '=', right)
  13. ])
  14. # called without parameters only from the init hook
  15. def update_relations(self, old_parent_id=None, parent_id=None):
  16. par_rel_mod = self.env['res.partner.relation']
  17. type_relation = self.env.ref(
  18. 'partner_multi_relation_parent.parent_relation_type'
  19. ).id
  20. for this in self:
  21. if this.type != 'contact':
  22. continue
  23. if not parent_id:
  24. parent_id = this.parent_id.id
  25. if not old_parent_id:
  26. old_parent_id = this.parent_id.id
  27. # unlink previous relation
  28. if old_parent_id:
  29. previous = self.find_current_relation(
  30. this.id, type_relation, old_parent_id
  31. )
  32. previous.unlink()
  33. # create new relations only if all the needed partners are there
  34. # for example if on create it failed this.id will be false or if it
  35. # has no parent also would fail.
  36. if this.id and parent_id:
  37. par_rel_mod.create({
  38. 'left_partner_id': this.id,
  39. 'type_id': type_relation,
  40. 'right_partner_id': parent_id,
  41. })
  42. @api.model
  43. def create(self, vals):
  44. res = super(ResPartner, self).create(vals=vals)
  45. if "parent_id" in vals:
  46. res.update_relations(None, vals['parent_id'])
  47. return res
  48. @api.multi
  49. def write(self, vals):
  50. for this in self:
  51. if this.env.context.get('no_relation_update'):
  52. continue
  53. if vals.get('parent_id'):
  54. this.update_relations(this.parent_id.id, vals['parent_id'])
  55. res = super(ResPartner, self).write(vals=vals)
  56. return res