social/mail_tracking/models/mail_bounced_mixin.py

44 lines
1.7 KiB
Python
Raw Normal View History

2018-11-05 17:26:01 +01:00
# Copyright 2018 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
2019-11-18 11:46:59 +01:00
from odoo import fields, models
2018-11-05 17:26:01 +01:00
class MailBouncedMixin(models.AbstractModel):
"""A mixin class to use if you want to add is_bounced flag on a model.
2018-11-05 17:26:01 +01:00
The field '_primary_email' must be overridden in the model that inherit
the mixin and must contain the email field of the model.
"""
2019-11-18 11:46:59 +01:00
_name = "mail.bounced.mixin"
_description = "Mail bounced mixin"
2019-11-18 11:34:02 +01:00
_primary_email = "email"
2018-11-05 17:26:01 +01:00
email_bounced = fields.Boolean(index=True)
def email_bounced_set(self, tracking_emails, reason, event=None):
"""Inherit this method to make any other actions to the model that
inherit the mixin"""
2019-11-18 11:46:59 +01:00
if self.env.context.get("write_loop"):
# We avoid with the context an infinite recursion calling write
# method from other write method.
return True
2018-11-05 17:26:01 +01:00
partners = self.filtered(lambda r: not r.email_bounced)
2019-11-18 11:46:59 +01:00
return partners.write({"email_bounced": True})
2018-11-05 17:26:01 +01:00
def write(self, vals):
2019-11-18 11:34:02 +01:00
email_field = self._primary_email
2018-11-05 17:26:01 +01:00
if email_field not in vals:
return super().write(vals)
2018-11-05 17:26:01 +01:00
email = vals[email_field].lower() if vals[email_field] else False
2019-11-18 11:46:59 +01:00
mte_obj = self.env["mail.tracking.email"]
vals["email_bounced"] = mte_obj.email_is_bounced(email)
if vals["email_bounced"]:
res = mte_obj._email_last_tracking_state(email)
2019-11-18 11:46:59 +01:00
tracking = mte_obj.browse(res[0].get("id"))
event = tracking.tracking_event_ids[:1]
2019-11-18 11:46:59 +01:00
self.with_context(write_loop=True).email_bounced_set(
tracking, event.error_details, event
)
return super().write(vals)