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.

59 lines
2.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Tecnativa - Jairo Llopis
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  4. from odoo import fields, models
  5. from odoo.tools import safe_eval
  6. class MassMailingList(models.Model):
  7. _inherit = "mail.mass_mailing.list"
  8. dynamic = fields.Boolean(
  9. help="Set this list as dynamic, to make it autosynchronized with "
  10. "partners from a given criteria.",
  11. )
  12. sync_method = fields.Selection(
  13. [
  14. ("add", "Only add new records"),
  15. ("full", "Add and remove records as needed"),
  16. ],
  17. default="add",
  18. required=True,
  19. help="Choose the syncronization method for this list if you want to "
  20. "make it dynamic",
  21. )
  22. sync_domain = fields.Char(
  23. string="Synchronization critera",
  24. default="[('opt_out', '=', False), ('email', '!=', False)]",
  25. required=True,
  26. help="Filter partners to sync in this list",
  27. )
  28. def action_sync(self):
  29. """Sync contacts in dynamic lists."""
  30. Contact = self.env["mail.mass_mailing.contact"].with_context(
  31. syncing=True,
  32. )
  33. Partner = self.env["res.partner"]
  34. # Skip non-dynamic lists
  35. dynamic = self.filtered("dynamic")
  36. for one in dynamic:
  37. sync_domain = safe_eval(one.sync_domain) + [("email", "!=", False)]
  38. desired_partners = Partner.search(sync_domain)
  39. # Remove undesired contacts when synchronization is full
  40. if one.sync_method == "full":
  41. Contact.search([
  42. ("list_id", "=", one.id),
  43. ("partner_id", "not in", desired_partners.ids),
  44. ]).unlink()
  45. current_contacts = Contact.search([("list_id", "=", one.id)])
  46. current_partners = current_contacts.mapped("partner_id")
  47. # Add new contacts
  48. for partner in desired_partners - current_partners:
  49. Contact.create({
  50. "list_id": one.id,
  51. "partner_id": partner.id,
  52. })
  53. # Invalidate cached contact count
  54. self.invalidate_cache(["contact_nbr"], dynamic.ids)