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.

66 lines
2.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 Akretion - Benoît Guillot
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from odoo import fields, models, api, exceptions, _
  5. import hashlib
  6. from collections import OrderedDict
  7. class ResPartner(models.Model):
  8. _inherit = "res.partner"
  9. version_hash = fields.Char(readonly=True, copy=False)
  10. date_version = fields.Datetime(string='Date version', readonly=True)
  11. @api.multi
  12. def get_address_version(self):
  13. """
  14. Get a versioned partner corresponding to the partner fields.
  15. If no versioned partner exists, create a new one.
  16. """
  17. self.ensure_one()
  18. version_hash = self.get_version_hash()
  19. versioned_partner = self.with_context(active_test=False).search(
  20. [('version_hash', '=', version_hash)])
  21. if versioned_partner:
  22. return versioned_partner
  23. default = {
  24. 'active': False,
  25. 'version_hash': version_hash,
  26. 'parent_id': self.parent_id and self.parent_id.id or self.id,
  27. 'date_version': fields.Datetime.now(),
  28. }
  29. versioned_partner = self.copy(default=default)
  30. return versioned_partner
  31. def get_version_fields(self):
  32. return [
  33. 'name', 'street', 'street2', 'zip', 'city', 'country_id',
  34. 'parent_id'
  35. ]
  36. def get_version_hash(self):
  37. version_fields = self.get_version_fields()
  38. version = OrderedDict()
  39. for field in version_fields:
  40. if field == 'parent_id':
  41. parent_id = self.parent_id and self.parent_id.id or self.id
  42. version[field] = parent_id
  43. elif self[field]:
  44. version[field] = self[field]
  45. version_hash = hashlib.md5(str(version)).hexdigest()
  46. return version_hash
  47. @api.multi
  48. def write(self, vals):
  49. version_fields = self.get_version_fields()
  50. has_written_versioned_fields = any(
  51. (f in version_fields) for f in vals.keys()
  52. )
  53. for partner in self:
  54. if partner.version_hash and has_written_versioned_fields:
  55. raise exceptions.UserError(_(
  56. "You can't modify a versioned field %s on the versioned "
  57. "partner %s.") % (version_fields, partner.name))
  58. return super(ResPartner, self).write(vals)