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.

57 lines
2.1 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"]
  31. Partner = self.env["res.partner"]
  32. # Skip non-dynamic lists
  33. dynamic = self.filtered("dynamic").with_context(syncing=True)
  34. for one in dynamic:
  35. sync_domain = safe_eval(one.sync_domain) + [("email", "!=", False)]
  36. desired_partners = Partner.search(sync_domain)
  37. # Remove undesired contacts when synchronization is full
  38. if one.sync_method == "full":
  39. Contact.search([
  40. ("list_id", "=", one.id),
  41. ("partner_id", "not in", desired_partners.ids),
  42. ]).unlink()
  43. current_contacts = Contact.search([("list_id", "=", one.id)])
  44. current_partners = current_contacts.mapped("partner_id")
  45. # Add new contacts
  46. for partner in desired_partners - current_partners:
  47. Contact.create({
  48. "list_id": one.id,
  49. "partner_id": partner.id,
  50. })
  51. # Invalidate cached contact count
  52. self.invalidate_cache(["contact_nbr"], dynamic.ids)