|
| 1 | +import logging |
| 2 | + |
| 3 | +from odoo import fields, models |
| 4 | +from odoo.tools.safe_eval import safe_eval |
| 5 | + |
| 6 | +_logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +class BaseNotificationRule(models.Model): |
| 10 | + _name = "base.notification.rule" |
| 11 | + _description = "Generic Notification Rule" |
| 12 | + _rec_name = "name" |
| 13 | + |
| 14 | + name = fields.Char(required=True) |
| 15 | + model_id = fields.Many2one( |
| 16 | + "ir.model", |
| 17 | + string="Model", |
| 18 | + required=True, |
| 19 | + ondelete="cascade", |
| 20 | + ) |
| 21 | + trigger = fields.Selection( |
| 22 | + [ |
| 23 | + ("on_create", "On Create"), |
| 24 | + ("on_write", "On Write"), |
| 25 | + ("on_unlink", "On Delete"), |
| 26 | + ("on_method_call", "On Method Call"), |
| 27 | + ], |
| 28 | + required=True, |
| 29 | + default="on_write", |
| 30 | + ) |
| 31 | + method_name = fields.Char() |
| 32 | + domain = fields.Char("Domain Filter", default="[]") |
| 33 | + active = fields.Boolean(default=True) |
| 34 | + notify_mode = fields.Selection( |
| 35 | + [ |
| 36 | + ("immediate", "Immediate"), |
| 37 | + ("queued", "Queued (if queue_job installed)"), |
| 38 | + ], |
| 39 | + default="immediate", |
| 40 | + ) |
| 41 | + partner_ids = fields.Many2many("res.partner", string="Recipients") |
| 42 | + template_id = fields.Many2one("mail.template", string="Mail Template") |
| 43 | + |
| 44 | + def _execute_notification(self, records): |
| 45 | + """Send the configured notification.""" |
| 46 | + if not self.active or not records: |
| 47 | + return |
| 48 | + |
| 49 | + if self.domain: |
| 50 | + try: |
| 51 | + domain = safe_eval(self.domain) |
| 52 | + records = records.filtered_domain(domain) |
| 53 | + except Exception as e: |
| 54 | + _logger.warning( |
| 55 | + f"Invalid domain in rule {self.name}: {self.domain} ({e})" |
| 56 | + ) |
| 57 | + |
| 58 | + for rec in records: |
| 59 | + if not rec.exists(): |
| 60 | + continue |
| 61 | + |
| 62 | + if self.template_id: |
| 63 | + self.template_id.send_mail(rec.id, force_send=True) |
| 64 | + else: |
| 65 | + rec.message_post( |
| 66 | + body=f"🔔 Notification: {self.name}", |
| 67 | + partner_ids=self.partner_ids.ids, |
| 68 | + ) |
| 69 | + |
| 70 | + def _apply_trigger(self, event_type, records): |
| 71 | + """Called by create/write/unlink hooks.""" |
| 72 | + rules = self.sudo().search( |
| 73 | + [ |
| 74 | + ("model_id.model", "=", records._name), |
| 75 | + ("trigger", "=", event_type), |
| 76 | + ("active", "=", True), |
| 77 | + ] |
| 78 | + ) |
| 79 | + for rule in rules: |
| 80 | + rule._execute_notification(records) |
0 commit comments