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.

76 lines
2.5 KiB

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