I want to notify all Maintenance Team members when a new request is created inside that particular team.
At the moment I have this functionality handled by an automated action like this:
Python code:
body_html = """
...
""" + record.name + """
...
"""
num_of_members = len(record.maintenance_team_id.member_ids)
if num_of_members:
members_emails = []
for i in range(num_of_members):
members_emails.append(record.maintenance_team_id.member_ids[i].email)
email_to = ",".join(members_emails)
mail_pool = env['mail.mail']
values={}
values.update({'subject': 'New maintenance request - ' + record.company_id.name})
values.update({'email_to': email_to})
values.update({'body_html': body_html})
msg_id = mail_pool.create(values)
if msg_id:
mail_pool.send([msg_id])
But now I would like to convert this solution to a custom module. What is the correct way to do this?
Should I inherit maintenance.request
, override the create method and send my email somehow (how exactly?) with hardcoded email body?
class MaintenanceRequest(models.Model):
_inherit = 'maintenance.request'
@api.model
def create(self, vals):
req = super(MaintenanceRequest, self).create(vals)
body_html = """
...
""" + req.name + """
...
"""
# ...
if msg_id:
mail_pool.send([msg_id])
return req
Or there is a way to hook myself to a premade function for sending notification and just tell it to run also for the team members? I don't want to add all of them as followers (because they would get spammed with unnecessary updates about the request) - only to notify them about the new request and then they can follow it if they needed to.
I would create a mail.template
in the custom module and set the members email list dynamically in it. There are already some simple mail template examples in Odoo to look into.
In Code you just have to send the mail by using this template.
<record id="my_mail_template" model="mail.template">
<field name="name">My Mail Template</field>
<field name="partner_to">${",".join(map(str, object.maintenance_team_id.member_ids.mapped('partner_id').ids))}</field>
<!-- add all other required fields -->
</record>
@api.model
def create(self, values):
record = super().create(values)
template_id = self.env.ref('my_module.my_mail_template').id
if template_id:
record.message_post_with_template(template_id)
return record