Initial squashed commit

This commit is contained in:
hoangvv
2026-05-12 18:58:14 +07:00
commit 0b5c2ce91a
54896 changed files with 28050323 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import iap_account
from . import ir_actions_server
from . import ir_model
from . import mail_followers
from . import mail_message
from . import mail_notification
from . import mail_thread
from . import models
from . import res_company
from . import res_partner
from . import sms_sms
from . import sms_template
from . import sms_tracker
+35
View File
@@ -0,0 +1,35 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
class IapAccount(models.Model):
_inherit = 'iap.account'
sender_name = fields.Char(help="This is the name that will be displayed as the sender of the SMS.", readonly=True)
def action_open_registration_wizard(self):
return {
'type': 'ir.actions.act_window',
'target': 'new',
'name': _('Register Account'),
'view_mode': 'form',
'res_model': 'sms.account.phone',
'context': {'default_account_id': self.id},
}
def action_open_sender_name_wizard(self):
return {
'type': 'ir.actions.act_window',
'target': 'new',
'name': _('Choose your sender name'),
'view_mode': 'form',
'res_model': 'sms.account.sender',
'context': {'default_account_id': self.id},
}
def _get_account_info(self, account_id, balance, information):
res = super()._get_account_info(account_id, balance, information)
if account_id.service_name == 'sms':
res['sender_name'] = information.get('sender_name')
return res
+89
View File
@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ServerActions(models.Model):
""" Add SMS option in server actions. """
_name = 'ir.actions.server'
_inherit = ['ir.actions.server']
state = fields.Selection(selection_add=[
('sms', 'Send SMS'), ('followers',),
], ondelete={'sms': 'cascade'})
# SMS
sms_template_id = fields.Many2one(
'sms.template', 'SMS Template',
compute='_compute_sms_template_id',
ondelete='set null', readonly=False, store=True,
domain="[('model_id', '=', model_id)]",
)
sms_method = fields.Selection(
selection=[('sms', 'SMS (without note)'), ('comment', 'SMS (with note)'), ('note', 'Note only')],
string='Send SMS As',
compute='_compute_sms_method',
readonly=False, store=True)
@api.depends('state')
def _compute_available_model_ids(self):
mail_thread_based = self.filtered(lambda action: action.state == 'sms')
if mail_thread_based:
mail_models = self.env['ir.model'].search([('is_mail_thread', '=', True), ('transient', '=', False)])
for action in mail_thread_based:
action.available_model_ids = mail_models.ids
super(ServerActions, self - mail_thread_based)._compute_available_model_ids()
@api.depends('model_id', 'state')
def _compute_sms_template_id(self):
to_reset = self.filtered(
lambda act: act.state != 'sms' or \
(act.model_id != act.sms_template_id.model_id)
)
if to_reset:
to_reset.sms_template_id = False
@api.depends('state')
def _compute_sms_method(self):
to_reset = self.filtered(lambda act: act.state != 'sms')
if to_reset:
to_reset.sms_method = False
other = self - to_reset
if other:
other.sms_method = 'sms'
@api.constrains('state', 'model_id')
def _check_sms_model_coherency(self):
for action in self:
if action.state == 'sms' and (action.model_id.transient or not action.model_id.is_mail_thread):
raise ValidationError(_("Sending SMS can only be done on a not transient mail.thread model"))
@api.constrains('model_id', 'template_id')
def _check_sms_template_model(self):
for action in self.filtered(lambda action: action.state == 'sms'):
if action.sms_template_id and action.sms_template_id.model_id != action.model_id:
raise ValidationError(
_('SMS template model of %(action_name)s does not match action model.',
action_name=action.name
)
)
def _run_action_sms_multi(self, eval_context=None):
# TDE CLEANME: when going to new api with server action, remove action
if not self.sms_template_id or self._is_recompute():
return False
records = eval_context.get('records') or eval_context.get('record')
if not records:
return False
composer = self.env['sms.composer'].with_context(
default_res_model=records._name,
default_res_ids=records.ids,
default_composition_mode='comment' if self.sms_method == 'comment' else 'mass',
default_template_id=self.sms_template_id.id,
default_mass_keep_log=self.sms_method == 'note',
).create({})
composer.action_send_sms()
return False
+41
View File
@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrModel(models.Model):
_inherit = 'ir.model'
is_mail_thread_sms = fields.Boolean(
string="Mail Thread SMS", default=False,
store=False, compute='_compute_is_mail_thread_sms', search='_search_is_mail_thread_sms',
help="Whether this model supports messages and notifications through SMS",
)
@api.depends('is_mail_thread')
def _compute_is_mail_thread_sms(self):
for model in self:
if model.is_mail_thread:
ModelObject = self.env[model.model]
potential_fields = ModelObject._phone_get_number_fields() + ModelObject._mail_get_partner_fields()
if any(fname in ModelObject._fields for fname in potential_fields):
model.is_mail_thread_sms = True
continue
model.is_mail_thread_sms = False
def _search_is_mail_thread_sms(self, operator, value):
thread_models = self.search([('is_mail_thread', '=', True)])
valid_models = self.env['ir.model']
for model in thread_models:
if model.model not in self.env:
continue
ModelObject = self.env[model.model]
potential_fields = ModelObject._phone_get_number_fields() + ModelObject._mail_get_partner_fields()
if any(fname in ModelObject._fields for fname in potential_fields):
valid_models |= model
search_sms = (operator == '=' and value) or (operator == '!=' and not value)
if search_sms:
return [('id', 'in', valid_models.ids)]
return [('id', 'not in', valid_models.ids)]
+29
View File
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Followers(models.Model):
_inherit = ['mail.followers']
def _get_recipient_data(self, records, message_type, subtype_id, pids=None):
recipients_data = super()._get_recipient_data(records, message_type, subtype_id, pids=pids)
if message_type != 'sms' or not (pids or records):
return recipients_data
if pids is None and records:
records_pids = dict(
(rec_id, partners.ids)
for rec_id, partners in records._mail_get_partners().items()
)
elif pids and records:
records_pids = dict((record.id, pids) for record in records)
else:
records_pids = {0: pids if pids else []}
for rid, rdata in recipients_data.items():
sms_pids = records_pids.get(rid) or []
for pid, pdata in rdata.items():
if pid in sms_pids:
pdata['notif'] = 'sms'
return recipients_data
+29
View File
@@ -0,0 +1,29 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class MailMessage(models.Model):
""" Override MailMessage class in order to add a new type: SMS messages.
Those messages comes with their own notification method, using SMS
gateway. """
_inherit = 'mail.message'
message_type = fields.Selection(
selection_add=[('sms', 'SMS')],
ondelete={'sms': lambda recs: recs.write({'message_type': 'comment'})})
has_sms_error = fields.Boolean(
'Has SMS error', compute='_compute_has_sms_error', search='_search_has_sms_error')
def _compute_has_sms_error(self):
sms_error_from_notification = self.env['mail.notification'].sudo().search([
('notification_type', '=', 'sms'),
('mail_message_id', 'in', self.ids),
('notification_status', '=', 'exception')]).mapped('mail_message_id')
for message in self:
message.has_sms_error = message in sms_error_from_notification
def _search_has_sms_error(self, operator, operand):
if operator == '=' and operand:
return ['&', ('notification_ids.notification_status', '=', 'exception'), ('notification_ids.notification_type', '=', 'sms')]
raise NotImplementedError()
+44
View File
@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class MailNotification(models.Model):
_inherit = 'mail.notification'
notification_type = fields.Selection(selection_add=[
('sms', 'SMS')
], ondelete={'sms': 'cascade'})
sms_id_int = fields.Integer('SMS ID', index='btree_not_null')
# Used to give links on form view without foreign key. In most cases, you'd want to use sms_id_int or sms_tracker_ids.sms_uuid.
sms_id = fields.Many2one('sms.sms', string='SMS', store=False, compute='_compute_sms_id')
sms_tracker_ids = fields.One2many('sms.tracker', 'mail_notification_id', string="SMS Trackers")
sms_number = fields.Char('SMS Number', groups='base.group_user')
failure_type = fields.Selection(selection_add=[
('sms_number_missing', 'Missing Number'),
('sms_number_format', 'Wrong Number Format'),
('sms_credit', 'Insufficient Credit'),
('sms_country_not_supported', 'Country Not Supported'),
('sms_registration_needed', 'Country-specific Registration Required'),
('sms_server', 'Server Error'),
('sms_acc', 'Unregistered Account'),
# delivery report errors
('sms_expired', 'Expired'),
('sms_invalid_destination', 'Invalid Destination'),
('sms_not_allowed', 'Not Allowed'),
('sms_not_delivered', 'Not Delivered'),
('sms_rejected', 'Rejected'),
])
@api.depends('sms_id_int', 'notification_type')
def _compute_sms_id(self):
self.sms_id = False
sms_notifications = self.filtered(lambda n: n.notification_type == 'sms' and bool(n.sms_id_int))
if not sms_notifications:
return
existing_sms_ids = self.env['sms.sms'].sudo().search([
('id', 'in', sms_notifications.mapped('sms_id_int')), ('to_delete', '!=', True)
]).ids
for sms_notification in sms_notifications.filtered(lambda n: n.sms_id_int in set(existing_sms_ids)):
sms_notification.sms_id = sms_notification.sms_id_int
+281
View File
@@ -0,0 +1,281 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, Command, models, fields
from odoo.addons.sms.tools.sms_tools import sms_content_to_rendered_html
from odoo.tools import html2plaintext
_logger = logging.getLogger(__name__)
class MailThread(models.AbstractModel):
_inherit = 'mail.thread'
message_has_sms_error = fields.Boolean(
'SMS Delivery error', compute='_compute_message_has_sms_error', search='_search_message_has_sms_error',
help="If checked, some messages have a delivery error.")
def _compute_message_has_sms_error(self):
res = {}
if self.ids:
self.env.cr.execute("""
SELECT msg.res_id, COUNT(msg.res_id)
FROM mail_message msg
INNER JOIN mail_notification notif
ON notif.mail_message_id = msg.id
WHERE notif.notification_type = 'sms'
AND notif.notification_status = 'exception'
AND notif.author_id = %(author_id)s
AND msg.model = %(model_name)s
AND msg.res_id in %(res_ids)s
AND msg.message_type != 'user_notification'
GROUP BY msg.res_id
""", {'author_id': self.env.user.partner_id.id, 'model_name': self._name, 'res_ids': tuple(self.ids)})
res.update(self._cr.fetchall())
for record in self:
record.message_has_sms_error = bool(res.get(record._origin.id, 0))
@api.model
def _search_message_has_sms_error(self, operator, operand):
return ['&', ('message_ids.has_sms_error', operator, operand), ('message_ids.author_id', '=', self.env.user.partner_id.id)]
@api.returns('mail.message', lambda value: value.id)
def message_post(self, *args, body='', message_type='notification', **kwargs):
# When posting an 'SMS' `message_type`, make sure that the body is used as-is in the sms,
# and reformat the message body for the notification (mainly making URLs clickable).
if message_type == 'sms':
kwargs['sms_content'] = body
body = sms_content_to_rendered_html(body)
return super().message_post(*args, body=body, message_type=message_type, **kwargs)
def _message_sms_schedule_mass(self, body='', template=False, **composer_values):
""" Shortcut method to schedule a mass sms sending on a recordset.
:param template: an optional sms.template record;
"""
composer_context = {
'default_res_model': self._name,
'default_composition_mode': 'mass',
'default_template_id': template.id if template else False,
'default_res_ids': self.ids,
}
if body and not template:
composer_context['default_body'] = body
create_vals = {
'mass_force_send': False,
'mass_keep_log': True,
}
if composer_values:
create_vals.update(composer_values)
composer = self.env['sms.composer'].with_context(**composer_context).create(create_vals)
return composer._action_send_sms()
def _message_sms_with_template(self, template=False, template_xmlid=False, template_fallback='', partner_ids=False, **kwargs):
""" Shortcut method to perform a _message_sms with an sms.template.
:param template: a valid sms.template record;
:param template_xmlid: XML ID of an sms.template (if no template given);
:param template_fallback: plaintext (inline_template-enabled) in case template
and template xml id are falsy (for example due to deleted data);
"""
self.ensure_one()
if not template and template_xmlid:
template = self.env.ref(template_xmlid, raise_if_not_found=False)
if template:
body = template._render_field('body', self.ids, compute_lang=True)[self.id]
else:
body = self.env['sms.template']._render_template(template_fallback, self._name, self.ids)[self.id]
return self._message_sms(body, partner_ids=partner_ids, **kwargs)
def _message_sms(self, body, subtype_id=False, partner_ids=False, number_field=False,
sms_numbers=None, sms_pid_to_number=None, **kwargs):
""" Main method to post a message on a record using SMS-based notification
method.
:param body: content of SMS;
:param subtype_id: mail.message.subtype used in mail.message associated
to the sms notification process;
:param partner_ids: if set is a record set of partners to notify;
:param number_field: if set is a name of field to use on current record
to compute a number to notify;
:param sms_numbers: see ``_notify_thread_by_sms``;
:param sms_pid_to_number: see ``_notify_thread_by_sms``;
"""
self.ensure_one()
sms_pid_to_number = sms_pid_to_number if sms_pid_to_number is not None else {}
if number_field or (partner_ids is False and sms_numbers is None):
info = self._sms_get_recipients_info(force_field=number_field)[self.id]
info_partner_ids = info['partner'].ids if info['partner'] else False
info_number = info['sanitized'] if info['sanitized'] else info['number']
if info_partner_ids and info_number:
sms_pid_to_number[info_partner_ids[0]] = info_number
if info_partner_ids:
partner_ids = info_partner_ids + (partner_ids or [])
if not info_partner_ids:
if info_number:
sms_numbers = [info_number] + (sms_numbers or [])
# will send a falsy notification allowing to fix it through SMS wizards
elif not sms_numbers:
sms_numbers = [False]
if subtype_id is False:
subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note')
return self.message_post(
body=body, partner_ids=partner_ids or [], # TDE FIXME: temp fix otherwise crash mail_thread.py
message_type='sms', subtype_id=subtype_id,
sms_numbers=sms_numbers, sms_pid_to_number=sms_pid_to_number,
**kwargs
)
def _notify_thread(self, message, msg_vals=False, **kwargs):
scheduled_date = self._is_notification_scheduled(kwargs.get('scheduled_date'))
recipients_data = super(MailThread, self)._notify_thread(message, msg_vals=msg_vals, **kwargs)
if not scheduled_date:
self._notify_thread_by_sms(message, recipients_data, msg_vals=msg_vals, **kwargs)
return recipients_data
def _notify_thread_by_sms(self, message, recipients_data, msg_vals=False,
sms_content=None, sms_numbers=None, sms_pid_to_number=None,
resend_existing=False, put_in_queue=False, **kwargs):
""" Notification method: by SMS.
:param message: ``mail.message`` record to notify;
:param recipients_data: list of recipients information (based on res.partner
records), formatted like
[{'active': partner.active;
'id': id of the res.partner being recipient to notify;
'groups': res.group IDs if linked to a user;
'notif': 'inbox', 'email', 'sms' (SMS App);
'share': partner.partner_share;
'type': 'customer', 'portal', 'user;'
}, {...}].
See ``MailThread._notify_get_recipients``;
:param msg_vals: dictionary of values used to create the message. If given it
may be used to access values related to ``message`` without accessing it
directly. It lessens query count in some optimized use cases by avoiding
access message content in db;
:param sms_content: plaintext version of body, mainly to avoid
conversion glitches by splitting html and plain text content formatting
(e.g.: links, styling.).
If not given, `msg_vals`'s `body` is used and converted from html to plaintext;
:param sms_numbers: additional numbers to notify in addition to partners
and classic recipients;
:param pid_to_number: force a number to notify for a given partner ID
instead of taking its mobile / phone number;
:param resend_existing: check for existing notifications to update based on
mailed recipient, otherwise create new notifications;
:param put_in_queue: use cron to send queued SMS instead of sending them
directly;
"""
sms_pid_to_number = sms_pid_to_number if sms_pid_to_number is not None else {}
sms_numbers = sms_numbers if sms_numbers is not None else []
sms_create_vals = []
sms_all = self.env['sms.sms'].sudo()
# pre-compute SMS data
body = sms_content or html2plaintext(msg_vals['body'] if msg_vals and 'body' in msg_vals else message.body)
sms_base_vals = {
'body': body,
'mail_message_id': message.id,
'state': 'outgoing',
}
# notify from computed recipients_data (followers, specific recipients)
partners_data = [r for r in recipients_data if r['notif'] == 'sms']
partner_ids = [r['id'] for r in partners_data]
if partner_ids:
for partner in self.env['res.partner'].sudo().browse(partner_ids):
number = sms_pid_to_number.get(partner.id) or partner.mobile or partner.phone
sms_create_vals.append(dict(
sms_base_vals,
partner_id=partner.id,
number=partner._phone_format(number=number) or number,
))
# notify from additional numbers
if sms_numbers:
tocreate_numbers = [
self._phone_format(number=sms_number) or sms_number
for sms_number in sms_numbers
]
existing_partners_numbers = {vals_dict['number'] for vals_dict in sms_create_vals}
sms_create_vals += [dict(
sms_base_vals,
partner_id=False,
number=n,
state='outgoing' if n else 'error',
failure_type='' if n else 'sms_number_missing',
) for n in tocreate_numbers if n not in existing_partners_numbers]
# create sms and notification
existing_pids, existing_numbers = [], []
if sms_create_vals:
sms_all |= self.env['sms.sms'].sudo().create(sms_create_vals)
if resend_existing:
existing = self.env['mail.notification'].sudo().search([
'|', ('res_partner_id', 'in', partner_ids),
'&', ('res_partner_id', '=', False), ('sms_number', 'in', sms_numbers),
('notification_type', '=', 'sms'),
('mail_message_id', 'in', message.ids),
])
for n in existing:
if n.res_partner_id.id in partner_ids and n.mail_message_id == message:
existing_pids.append(n.res_partner_id.id)
if not n.res_partner_id and n.sms_number in sms_numbers and n.mail_message_id == message:
existing_numbers.append(n.sms_number)
notif_create_values = [{
'author_id': message.author_id.id,
'mail_message_id': message.id,
'res_partner_id': sms.partner_id.id,
'sms_number': sms.number,
'notification_type': 'sms',
'sms_id_int': sms.id,
'sms_tracker_ids': [Command.create({'sms_uuid': sms.uuid})] if sms.state == 'outgoing' else False,
'is_read': True, # discard Inbox notification
'notification_status': 'ready' if sms.state == 'outgoing' else 'exception',
'failure_type': '' if sms.state == 'outgoing' else sms.failure_type,
} for sms in sms_all if (sms.partner_id and sms.partner_id.id not in existing_pids) or (not sms.partner_id and sms.number not in existing_numbers)]
if notif_create_values:
self.env['mail.notification'].sudo().create(notif_create_values)
if existing_pids or existing_numbers:
for sms in sms_all:
notif = next((n for n in existing if
(n.res_partner_id.id in existing_pids and n.res_partner_id.id == sms.partner_id.id) or
(not n.res_partner_id and n.sms_number in existing_numbers and n.sms_number == sms.number)), False)
if notif:
notif.write({
'notification_type': 'sms',
'notification_status': 'ready',
'sms_id_int': sms.id,
'sms_tracker_ids': [Command.create({'sms_uuid': sms.uuid})],
'sms_number': sms.number,
})
if sms_all and not put_in_queue:
sms_all.filtered(lambda sms: sms.state == 'outgoing').send(auto_commit=False, raise_exception=False)
return True
def _get_notify_valid_parameters(self):
return super()._get_notify_valid_parameters() | {
'put_in_queue', 'sms_numbers', 'sms_pid_to_number', 'sms_content',
}
@api.model
def notify_cancel_by_type(self, notification_type):
super().notify_cancel_by_type(notification_type)
if notification_type == 'sms':
# TDE CHECK: delete pending SMS
self._notify_cancel_by_type_generic('sms')
return True
+89
View File
@@ -0,0 +1,89 @@
from odoo import models
from odoo.addons.phone_validation.tools import phone_validation
class BaseModel(models.AbstractModel):
_inherit = 'base'
def _sms_get_recipients_info(self, force_field=False, partner_fallback=True):
"""" Get SMS recipient information on current record set. This method
checks for numbers and sanitation in order to centralize computation.
Example of use cases
* click on a field -> number is actually forced from field, find customer
linked to record, force its number to field or fallback on customer fields;
* contact -> find numbers from all possible phone fields on record, find
customer, force its number to found field number or fallback on customer fields;
:param force_field: either give a specific field to find phone number, either
generic heuristic is used to find one based on ``_phone_get_number_fields``;
:param partner_fallback: if no value found in the record, check its customer
values based on ``_mail_get_partners``;
:return dict: record.id: {
'partner': a res.partner recordset that is the customer (void or singleton)
linked to the recipient. See ``_mail_get_partners``;
'sanitized': sanitized number to use (coming from record's field or partner's
phone fields). Set to False is number impossible to parse and format;
'number': original number before sanitation;
'partner_store': whether the number comes from the customer phone fields. If
False it means number comes from the record itself, even if linked to a
customer;
'field_store': field in which the number has been found (generally mobile or
phone, see ``_phone_get_number_fields``);
} for each record in self
"""
result = dict.fromkeys(self.ids, False)
tocheck_fields = [force_field] if force_field else self._phone_get_number_fields()
for record in self:
all_numbers = [record[fname] for fname in tocheck_fields if fname in record]
all_partners = record._mail_get_partners()[record.id]
valid_number, fname = False, False
for fname in [f for f in tocheck_fields if f in record]:
valid_number = record._phone_format(fname=fname)
if valid_number:
break
if valid_number:
result[record.id] = {
'partner': all_partners[0] if all_partners else self.env['res.partner'],
'sanitized': valid_number,
'number': record[fname],
'partner_store': False,
'field_store': fname,
}
elif all_partners and partner_fallback:
partner = self.env['res.partner']
for partner in all_partners:
for fname in self.env['res.partner']._phone_get_number_fields():
valid_number = partner._phone_format(fname=fname)
if valid_number:
break
if not valid_number:
fname = 'mobile' if partner.mobile else ('phone' if partner.phone else 'mobile')
result[record.id] = {
'partner': partner,
'sanitized': valid_number if valid_number else False,
'number': partner[fname],
'partner_store': True,
'field_store': fname,
}
else:
# did not find any sanitized number -> take first set value as fallback;
# if none, just assign False to the first available number field
value, fname = next(
((value, fname) for value, fname in zip(all_numbers, tocheck_fields) if value),
(False, tocheck_fields[0] if tocheck_fields else False)
)
result[record.id] = {
'partner': self.env['res.partner'],
'sanitized': False,
'number': value,
'partner_store': False,
'field_store': fname
}
return result
+11
View File
@@ -0,0 +1,11 @@
from odoo import models
from odoo.addons.sms.tools.sms_api import SmsApi
class ResCompany(models.Model):
_inherit = 'res.company'
def _get_sms_api_class(self):
self.ensure_one()
return SmsApi
+9
View File
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ResPartner(models.Model):
_name = 'res.partner'
_inherit = ['mail.thread.phone', 'res.partner']
+250
View File
@@ -0,0 +1,250 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import threading
from uuid import uuid4
from werkzeug.urls import url_join
from odoo import api, fields, models, tools, _
from odoo.addons.sms.tools.sms_api import SmsApi
_logger = logging.getLogger(__name__)
class SmsSms(models.Model):
_name = 'sms.sms'
_description = 'Outgoing SMS'
_rec_name = 'number'
_order = 'id DESC'
IAP_TO_SMS_STATE_SUCCESS = {
'processing': 'process',
'success': 'pending',
# These below are not returned in responses from IAP API in _send but are received via webhook events.
'sent': 'pending',
'delivered': 'sent',
}
IAP_TO_SMS_FAILURE_TYPE = { # TODO RIGR remove me in master
'insufficient_credit': 'sms_credit',
'wrong_number_format': 'sms_number_format',
'country_not_supported': 'sms_country_not_supported',
'server_error': 'sms_server',
'unregistered': 'sms_acc'
}
BOUNCE_DELIVERY_ERRORS = {'sms_invalid_destination', 'sms_not_allowed', 'sms_rejected'}
DELIVERY_ERRORS = {'sms_expired', 'sms_not_delivered', *BOUNCE_DELIVERY_ERRORS}
uuid = fields.Char('UUID', copy=False, readonly=True, default=lambda self: uuid4().hex,
help='Alternate way to identify a SMS record, used for delivery reports')
number = fields.Char('Number')
body = fields.Text()
partner_id = fields.Many2one('res.partner', 'Customer')
mail_message_id = fields.Many2one('mail.message', index=True)
state = fields.Selection([
('outgoing', 'In Queue'),
('process', 'Processing'),
('pending', 'Sent'),
('sent', 'Delivered'), # As for notifications and traces
('error', 'Error'),
('canceled', 'Cancelled')
], 'SMS Status', readonly=True, copy=False, default='outgoing', required=True)
failure_type = fields.Selection([
("unknown", "Unknown error"),
('sms_number_missing', 'Missing Number'),
('sms_number_format', 'Wrong Number Format'),
('sms_country_not_supported', 'Country Not Supported'),
('sms_registration_needed', 'Country-specific Registration Required'),
('sms_credit', 'Insufficient Credit'),
('sms_server', 'Server Error'),
('sms_acc', 'Unregistered Account'),
# mass mode specific codes, generated internally, not returned by IAP.
('sms_blacklist', 'Blacklisted'),
('sms_duplicate', 'Duplicate'),
('sms_optout', 'Opted Out'),
], copy=False)
sms_tracker_id = fields.Many2one('sms.tracker', string='SMS trackers', compute='_compute_sms_tracker_id')
to_delete = fields.Boolean(
'Marked for deletion', default=False,
help='Will automatically be deleted, while notifications will not be deleted in any case.'
)
_sql_constraints = [
('uuid_unique', 'unique(uuid)', 'UUID must be unique'),
]
@api.depends('uuid')
def _compute_sms_tracker_id(self):
self.sms_tracker_id = False
existing_trackers = self.env['sms.tracker'].search([('sms_uuid', 'in', self.filtered('uuid').mapped('uuid'))])
tracker_ids_by_sms_uuid = {tracker.sms_uuid: tracker.id for tracker in existing_trackers}
for sms in self.filtered(lambda s: s.uuid in tracker_ids_by_sms_uuid):
sms.sms_tracker_id = tracker_ids_by_sms_uuid[sms.uuid]
def action_set_canceled(self):
self._update_sms_state_and_trackers('canceled')
def action_set_error(self, failure_type):
self._update_sms_state_and_trackers('error', failure_type=failure_type)
def action_set_outgoing(self):
self._update_sms_state_and_trackers('outgoing', failure_type=False)
def send(self, unlink_failed=False, unlink_sent=True, auto_commit=False, raise_exception=False):
""" Main API method to send SMS.
:param unlink_failed: unlink failed SMS after IAP feedback;
:param unlink_sent: unlink sent SMS after IAP feedback;
:param auto_commit: commit after each batch of SMS;
:param raise_exception: raise if there is an issue contacting IAP;
"""
to_send = self.filtered(lambda sms: sms.state == 'outgoing' and not sms.to_delete)
for sms_api, sms in to_send._split_by_api():
for batch_ids in sms._split_batch():
self.env['sms.sms'].browse(batch_ids).with_context(sms_api=sms_api)._send(
unlink_failed=unlink_failed,
unlink_sent=unlink_sent,
raise_exception=raise_exception,
)
# auto-commit if asked except in testing mode
if auto_commit is True and not getattr(threading.current_thread(), 'testing', False):
self._cr.commit()
def _split_by_api(self):
yield SmsApi(self.env), self
def resend_failed(self):
sms_to_send = self.filtered(lambda sms: sms.state == 'error' and not sms.to_delete)
sms_to_send.state = 'outgoing'
notification_title = _('Warning')
notification_type = 'danger'
if sms_to_send:
sms_to_send.send()
success_sms = len(sms_to_send) - len(sms_to_send.exists())
if success_sms > 0:
notification_title = _('Success')
notification_type = 'success'
notification_message = _('%(count)s out of the %(total)s selected SMS Text Messages have successfully been resent.', count=success_sms, total=len(self))
else:
notification_message = _('The SMS Text Messages could not be resent.')
else:
notification_message = _('There are no SMS Text Messages to resend.')
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': notification_title,
'message': notification_message,
'type': notification_type,
}
}
@api.model
def _process_queue(self, ids=None):
""" Send immediately queued messages, committing after each message is sent.
This is not transactional and should not be called during another transaction!
:param list ids: optional list of emails ids to send. If passed no search
is performed, and these ids are used instead.
"""
domain = [('state', '=', 'outgoing'), ('to_delete', '!=', True)]
filtered_ids = self.search(domain, limit=10000).ids # TDE note: arbitrary limit we might have to update
if ids:
ids = list(set(filtered_ids) & set(ids))
else:
ids = filtered_ids
ids.sort()
res = None
try:
# auto-commit except in testing mode
auto_commit = not getattr(threading.current_thread(), 'testing', False)
res = self.browse(ids).send(unlink_failed=False, unlink_sent=True, auto_commit=auto_commit, raise_exception=False)
except Exception:
_logger.exception("Failed processing SMS queue")
return res
def _get_sms_company(self):
return self.mail_message_id.record_company_id or self.env.company
def _get_batch_size(self):
return int(self.env['ir.config_parameter'].sudo().get_param('sms.session.batch.size', 500))
def _split_batch(self):
batch_size = self._get_batch_size()
for sms_batch in tools.split_every(batch_size, self.ids):
yield sms_batch
def _send(self, unlink_failed=False, unlink_sent=True, raise_exception=False):
"""Send SMS after checking the number (presence and formatting)."""
sms_api = self.env.context.get('sms_api')
if not sms_api:
company = self._get_sms_company()
company.ensure_one() # This should always be the case since the grouping is done in `send`
sms_api = company._get_sms_api_class()(self.env)
return self._send_with_api(
sms_api,
unlink_failed=unlink_failed,
unlink_sent=unlink_sent,
raise_exception=raise_exception,
)
def _send_with_api(self, sms_api, unlink_failed=False, unlink_sent=True, raise_exception=False):
"""Send SMS after checking the number (presence and formatting)."""
messages = [{
'content': body,
'numbers': [{'number': sms.number, 'uuid': sms.uuid} for sms in body_sms_records],
} for body, body_sms_records in self.grouped('body').items()]
delivery_reports_url = url_join(self[0].get_base_url(), '/sms/status')
try:
results = sms_api._send_sms_batch(messages, delivery_reports_url=delivery_reports_url)
except Exception as e:
_logger.info('Sent batch %s SMS: %s: failed with exception %s', len(self.ids), self.ids, e)
if raise_exception:
raise
results = [{'uuid': sms.uuid, 'state': 'server_error'} for sms in self]
else:
_logger.info('Send batch %s SMS: %s: gave %s', len(self.ids), self.ids, results)
results_uuids = [result['uuid'] for result in results]
all_sms_sudo = self.env['sms.sms'].sudo().search([('uuid', 'in', results_uuids)]).with_context(sms_skip_msg_notification=True)
for (iap_state, failure_reason), results_group in tools.groupby(results, key=lambda result: (result['state'], result.get('failure_reason'))):
sms_sudo = all_sms_sudo.filtered(lambda s: s.uuid in {result['uuid'] for result in results_group})
if success_state := self.IAP_TO_SMS_STATE_SUCCESS.get(iap_state):
sms_sudo.sms_tracker_id._action_update_from_sms_state(success_state)
to_delete = {'to_delete': True} if unlink_sent else {}
sms_sudo.write({'state': success_state, 'failure_type': False, **to_delete})
else:
failure_type = sms_api.PROVIDER_TO_SMS_FAILURE_TYPE.get(iap_state, 'unknown')
if failure_type != 'unknown':
sms_sudo.sms_tracker_id._action_update_from_sms_state('error', failure_type=failure_type, failure_reason=failure_reason)
else:
sms_sudo.sms_tracker_id.with_context(sms_known_failure_reason=failure_reason)._action_update_from_provider_error(iap_state)
to_delete = {'to_delete': True} if unlink_failed else {}
sms_sudo.write({'state': 'error', 'failure_type': failure_type, **to_delete})
all_sms_sudo._handle_call_result_hook(results)
all_sms_sudo.mail_message_id._notify_message_notification_update()
def _update_sms_state_and_trackers(self, new_state, failure_type=None):
"""Update sms state update and related tracking records (notifications, traces)."""
self.write({'state': new_state, 'failure_type': failure_type})
# Use sudo on mail.notification to allow writing other users' notifications; rights are already checked by sms write
self.sms_tracker_id.sudo()._action_update_from_sms_state(new_state, failure_type=failure_type)
def _handle_call_result_hook(self, results):
"""Further process SMS sending API results."""
pass
@api.autovacuum
def _gc_device(self):
self._cr.execute("DELETE FROM sms_sms WHERE to_delete = TRUE")
_logger.info("GC'd %d sms marked for deletion", self._cr.rowcount)
+76
View File
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class SMSTemplate(models.Model):
"Templates for sending SMS"
_name = "sms.template"
_inherit = ['mail.render.mixin', 'template.reset.mixin']
_description = 'SMS Templates'
_unrestricted_rendering = True
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if 'model_id' in fields and not res.get('model_id') and res.get('model'):
res['model_id'] = self.env['ir.model']._get(res['model']).id
return res
name = fields.Char('Name', translate=True)
model_id = fields.Many2one(
'ir.model', string='Applies to', required=True,
domain=['&', ('is_mail_thread_sms', '=', True), ('transient', '=', False)],
help="The type of document this template can be used with", ondelete='cascade')
model = fields.Char('Related Document Model', related='model_id.model', index=True, store=True, readonly=True)
body = fields.Char('Body', translate=True, required=True)
# Use to create contextual action (same as for email template)
sidebar_action_id = fields.Many2one('ir.actions.act_window', 'Sidebar action', readonly=True, copy=False,
help="Sidebar action to make this template available on records "
"of the related document model")
# Overrides of mail.render.mixin
@api.depends('model')
def _compute_render_model(self):
for template in self:
template.render_model = template.model
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
def copy_data(self, default=None):
vals_list = super().copy_data(default=default)
return [dict(vals, name=self.env._("%s (copy)", template.name)) for template, vals in zip(self, vals_list)]
def unlink(self):
self.sudo().mapped('sidebar_action_id').unlink()
return super(SMSTemplate, self).unlink()
def action_create_sidebar_action(self):
ActWindow = self.env['ir.actions.act_window']
view = self.env.ref('sms.sms_composer_view_form')
for template in self:
button_name = _('Send SMS (%s)', template.name)
action = ActWindow.create({
'name': button_name,
'type': 'ir.actions.act_window',
'res_model': 'sms.composer',
# Add default_composition_mode to guess to determine if need to use mass or comment composer
'context': "{'default_template_id' : %d, 'sms_composition_mode': 'guess', 'default_res_ids': active_ids, 'default_res_id': active_id}" % (template.id),
'view_mode': 'form',
'view_id': view.id,
'target': 'new',
'binding_model_id': template.model_id.id,
})
template.write({'sidebar_action_id': action.id})
return True
def action_unlink_sidebar_action(self):
for template in self:
if template.sidebar_action_id:
template.sidebar_action_id.unlink()
return True
+82
View File
@@ -0,0 +1,82 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class SmsTracker(models.Model):
"""Relationship between a sent SMS and tracking records such as notifications and traces.
This model acts as an extension of a `mail.notification` or a `mailing.trace` and allows to
update those based on the SMS provider responses both at sending and when later receiving
sent/delivery reports (see `SmsController`).
SMS trackers are supposed to be created manually when necessary, and tied to their related
SMS through the SMS UUID field. (They are not tied to the SMS records directly as those can
be deleted when sent).
Note: Only admins/system user should need to access (a fortiori modify) these technical
records so no "sudo" is used nor should be required here.
"""
_name = 'sms.tracker'
_description = "Link SMS to mailing/sms tracking models"
SMS_STATE_TO_NOTIFICATION_STATUS = {
'canceled': 'canceled',
'process': 'process',
'error': 'exception',
'outgoing': 'ready',
'sent': 'sent',
'pending': 'pending',
}
sms_uuid = fields.Char('SMS uuid', required=True)
mail_notification_id = fields.Many2one('mail.notification', ondelete='cascade')
_sql_constraints = [
('sms_uuid_unique', 'unique(sms_uuid)', 'A record for this UUID already exists'),
]
def _action_update_from_provider_error(self, provider_error):
"""
:param str provider_error: value returned by SMS service provider (IAP) or any string.
If provided, notification values will be derived from it.
(see ``_get_tracker_values_from_provider_error``)
"""
failure_reason = self.env.context.get("sms_known_failure_reason") # TODO RIGR in master: pass as param instead of context
failure_type = f'sms_{provider_error}'
error_status = None
if failure_type not in self.env['sms.sms'].DELIVERY_ERRORS:
failure_type = 'unknown'
failure_reason = failure_reason or provider_error
elif failure_type in self.env['sms.sms'].BOUNCE_DELIVERY_ERRORS:
error_status = "bounce"
self._update_sms_notifications(error_status or 'exception', failure_type=failure_type, failure_reason=failure_reason)
return error_status, failure_type, failure_reason
def _action_update_from_sms_state(self, sms_state, failure_type=False, failure_reason=False):
notification_status = self.SMS_STATE_TO_NOTIFICATION_STATUS[sms_state]
self._update_sms_notifications(notification_status, failure_type=failure_type, failure_reason=failure_reason)
def _update_sms_notifications(self, notification_status, failure_type=False, failure_reason=False):
# canceled is a state which means that the SMS sending order should not be sent to the SMS service.
# `process`, `pending` are sent to IAP which is not revertible (as `sent` which means "delivered").
notifications_statuses_to_ignore = {
'canceled': ['canceled', 'process', 'pending', 'sent'],
'ready': ['ready', 'process', 'pending', 'sent'],
'process': ['process', 'pending', 'sent'],
'pending': ['pending', 'sent'],
'bounce': ['bounce', 'sent'],
'sent': ['sent'],
'exception': ['exception'],
}[notification_status]
notifications = self.mail_notification_id.filtered(
lambda n: n.notification_status not in notifications_statuses_to_ignore
)
if notifications:
notifications.write({
'notification_status': notification_status,
'failure_type': failure_type,
'failure_reason': failure_reason,
})
if not self.env.context.get('sms_skip_msg_notification'):
notifications.mail_message_id._notify_message_notification_update()