1 # -*- coding: utf-8 -*-
3 from datetime import datetime
4 from dateutil import relativedelta
8 from openerp import tools
9 from openerp.exceptions import Warning
10 from openerp.tools.safe_eval import safe_eval as eval
11 from openerp.tools.translate import _
12 from openerp.osv import osv, fields
15 class MassMailingCategory(osv.Model):
16 """Model of categories of mass mailing, i.e. marketing, newsletter, ... """
17 _name = 'mail.mass_mailing.category'
18 _description = 'Mass Mailing Category'
22 'name': fields.char('Name', required=True),
26 class MassMailingContact(osv.Model):
27 """Model of a contact. This model is different from the partner model
28 because it holds only some basic information: name, email. The purpose is to
29 be able to deal with large contact list to email without bloating the partner
31 _name = 'mail.mass_mailing.contact'
32 _description = 'Mass Mailing Contact'
37 'name': fields.char('Name'),
38 'email': fields.char('Email', required=True),
39 'create_date': fields.datetime('Create Date'),
40 'list_id': fields.many2one(
41 'mail.mass_mailing.list', string='Mailing List',
42 ondelete='cascade', required=True,
44 'opt_out': fields.boolean('Opt Out', help='The contact has chosen not to receive mails anymore from this list'),
47 def _get_latest_list(self, cr, uid, context={}):
48 lid = self.pool.get('mail.mass_mailing.list').search(cr, uid, [], limit=1, order='id desc', context=context)
49 return lid and lid[0] or False
52 'list_id': _get_latest_list
55 def get_name_email(self, name, context):
56 name, email = self.pool['res.partner']._parse_partner_name(name, context=context)
57 if name and not email:
59 if email and not name:
63 def name_create(self, cr, uid, name, context=None):
64 name, email = self.get_name_email(name, context=context)
65 rec_id = self.create(cr, uid, {'name': name, 'email': email}, context=context)
66 return self.name_get(cr, uid, [rec_id], context)[0]
68 def add_to_list(self, cr, uid, name, list_id, context=None):
69 name, email = self.get_name_email(name, context=context)
70 rec_id = self.create(cr, uid, {'name': name, 'email': email, 'list_id': list_id}, context=context)
71 return self.name_get(cr, uid, [rec_id], context)[0]
73 def message_get_default_recipients(self, cr, uid, ids, context=None):
75 for record in self.browse(cr, uid, ids, context=context):
76 res[record.id] = {'partner_ids': [], 'email_to': record.email, 'email_cc': False}
80 class MassMailingList(osv.Model):
81 """Model of a contact list. """
82 _name = 'mail.mass_mailing.list'
84 _description = 'Mailing List'
86 def _get_contact_nbr(self, cr, uid, ids, name, arg, context=None):
87 result = dict.fromkeys(ids, 0)
88 Contacts = self.pool.get('mail.mass_mailing.contact')
89 for group in Contacts.read_group(cr, uid, [('list_id', 'in', ids), ('opt_out', '!=', True)], ['list_id'], ['list_id'], context=context):
90 result[group['list_id'][0]] = group['list_id_count']
94 'name': fields.char('Mailing List', required=True),
95 'contact_nbr': fields.function(
96 _get_contact_nbr, type='integer',
97 string='Number of Contacts',
102 class MassMailingStage(osv.Model):
103 """Stage for mass mailing campaigns. """
104 _name = 'mail.mass_mailing.stage'
105 _description = 'Mass Mailing Campaign Stage'
109 'name': fields.char('Name', required=True, translate=True),
110 'sequence': fields.integer('Sequence'),
118 class MassMailingCampaign(osv.Model):
119 """Model of mass mailing campaigns. """
120 _name = "mail.mass_mailing.campaign"
121 _description = 'Mass Mailing Campaign'
123 def _get_statistics(self, cr, uid, ids, name, arg, context=None):
124 """ Compute statistics of the mass mailing campaign """
129 COUNT(s.id) AS total,
130 COUNT(CASE WHEN s.sent is not null THEN 1 ELSE null END) AS sent,
131 COUNT(CASE WHEN s.scheduled is not null AND s.sent is null AND s.exception is null THEN 1 ELSE null END) AS scheduled,
132 COUNT(CASE WHEN s.scheduled is not null AND s.sent is null AND s.exception is not null THEN 1 ELSE null END) AS failed,
133 COUNT(CASE WHEN s.id is not null AND s.bounced is null THEN 1 ELSE null END) AS delivered,
134 COUNT(CASE WHEN s.opened is not null THEN 1 ELSE null END) AS opened,
135 COUNT(CASE WHEN s.replied is not null THEN 1 ELSE null END) AS replied ,
136 COUNT(CASE WHEN s.bounced is not null THEN 1 ELSE null END) AS bounced
138 mail_mail_statistics s
140 mail_mass_mailing_campaign c
141 ON (c.id = s.mass_mailing_campaign_id)
147 for row in cr.dictfetchall():
148 results[row.pop('campaign_id')] = row
149 total = row['total'] or 1
150 row['delivered'] = row['sent'] - row['bounced']
151 row['received_ratio'] = 100.0 * row['delivered'] / total
152 row['opened_ratio'] = 100.0 * row['opened'] / total
153 row['replied_ratio'] = 100.0 * row['replied'] / total
157 'name': fields.char('Name', required=True),
158 'stage_id': fields.many2one('mail.mass_mailing.stage', 'Stage', required=True),
159 'user_id': fields.many2one(
160 'res.users', 'Responsible',
163 'category_ids': fields.many2many(
164 'mail.mass_mailing.category', 'mail_mass_mailing_category_rel',
165 'category_id', 'campaign_id', string='Categories'),
166 'mass_mailing_ids': fields.one2many(
167 'mail.mass_mailing', 'mass_mailing_campaign_id',
170 'unique_ab_testing': fields.boolean(
172 help='If checked, recipients will be mailed only once, allowing to send'
173 'various mailings in a single campaign to test the effectiveness'
175 'color': fields.integer('Color Index'),
177 'total': fields.function(
178 _get_statistics, string='Total',
179 type='integer', multi='_get_statistics'
181 'scheduled': fields.function(
182 _get_statistics, string='Scheduled',
183 type='integer', multi='_get_statistics'
185 'failed': fields.function(
186 _get_statistics, string='Failed',
187 type='integer', multi='_get_statistics'
189 'sent': fields.function(
190 _get_statistics, string='Sent Emails',
191 type='integer', multi='_get_statistics'
193 'delivered': fields.function(
194 _get_statistics, string='Delivered',
195 type='integer', multi='_get_statistics',
197 'opened': fields.function(
198 _get_statistics, string='Opened',
199 type='integer', multi='_get_statistics',
201 'replied': fields.function(
202 _get_statistics, string='Replied',
203 type='integer', multi='_get_statistics'
205 'bounced': fields.function(
206 _get_statistics, string='Bounced',
207 type='integer', multi='_get_statistics'
209 'received_ratio': fields.function(
210 _get_statistics, string='Received Ratio',
211 type='integer', multi='_get_statistics',
213 'opened_ratio': fields.function(
214 _get_statistics, string='Opened Ratio',
215 type='integer', multi='_get_statistics',
217 'replied_ratio': fields.function(
218 _get_statistics, string='Replied Ratio',
219 type='integer', multi='_get_statistics',
223 def _get_default_stage_id(self, cr, uid, context=None):
224 stage_ids = self.pool['mail.mass_mailing.stage'].search(cr, uid, [], limit=1, context=context)
225 return stage_ids and stage_ids[0] or False
228 'user_id': lambda self, cr, uid, ctx=None: uid,
229 'stage_id': lambda self, *args: self._get_default_stage_id(*args),
232 def get_recipients(self, cr, uid, ids, model=None, context=None):
233 """Return the recipients of a mailing campaign. This is based on the statistics
234 build for each mailing. """
235 Statistics = self.pool['mail.mail.statistics']
236 res = dict.fromkeys(ids, False)
238 domain = [('mass_mailing_campaign_id', '=', cid)]
240 domain += [('model', '=', model)]
241 stat_ids = Statistics.search(cr, uid, domain, context=context)
242 res[cid] = set(stat.res_id for stat in Statistics.browse(cr, uid, stat_ids, context=context))
246 class MassMailing(osv.Model):
247 """ MassMailing models a wave of emails for a mass mailign campaign.
248 A mass mailing is an occurence of sending emails. """
250 _name = 'mail.mass_mailing'
251 _description = 'Mass Mailing'
252 # number of periods for tracking mail_mail statistics
254 _order = 'sent_date DESC'
256 def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, date_begin, context=None):
257 """ Generic method to generate data for bar chart values using SparklineBarWidget.
258 This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
260 :param obj: the target model (i.e. crm_lead)
261 :param domain: the domain applied to the read_group
262 :param list read_fields: the list of fields to read in the read_group
263 :param str value_field: the field used to compute the value of the bar slice
264 :param str groupby_field: the fields used to group
266 :return list section_result: a list of dicts: [
267 { 'value': (int) bar_column_value,
268 'tootip': (str) bar_column_tooltip,
272 date_begin = date_begin.date()
273 section_result = [{'value': 0,
274 'tooltip': (date_begin + relativedelta.relativedelta(days=i)).strftime('%d %B %Y'),
275 } for i in range(0, self._period_number)]
276 group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
277 field_col_info = obj._all_columns.get(groupby_field.split(':')[0])
278 pattern = tools.DEFAULT_SERVER_DATE_FORMAT if field_col_info.column._type == 'date' else tools.DEFAULT_SERVER_DATETIME_FORMAT
279 for group in group_obj:
280 group_begin_date = datetime.strptime(group['__domain'][0][2], pattern).date()
281 timedelta = relativedelta.relativedelta(group_begin_date, date_begin)
282 section_result[timedelta.days] = {'value': group.get(value_field, 0), 'tooltip': group.get(groupby_field)}
283 return section_result
285 def _get_daily_statistics(self, cr, uid, ids, field_name, arg, context=None):
286 """ Get the daily statistics of the mass mailing. This is done by a grouping
287 on opened and replied fields. Using custom format in context, we obtain
288 results for the next 6 days following the mass mailing date. """
289 obj = self.pool['mail.mail.statistics']
291 for mailing in self.browse(cr, uid, ids, context=context):
293 date = mailing.sent_date if mailing.sent_date else mailing.create_date
294 date_begin = datetime.strptime(date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
295 date_end = date_begin + relativedelta.relativedelta(days=self._period_number - 1)
296 date_begin_str = date_begin.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
297 date_end_str = date_end.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
298 domain = [('mass_mailing_id', '=', mailing.id), ('opened', '>=', date_begin_str), ('opened', '<=', date_end_str)]
299 res[mailing.id]['opened_daily'] = json.dumps(self.__get_bar_values(cr, uid, obj, domain, ['opened'], 'opened_count', 'opened:day', date_begin, context=context))
300 domain = [('mass_mailing_id', '=', mailing.id), ('replied', '>=', date_begin_str), ('replied', '<=', date_end_str)]
301 res[mailing.id]['replied_daily'] = json.dumps(self.__get_bar_values(cr, uid, obj, domain, ['replied'], 'replied_count', 'replied:day', date_begin, context=context))
304 def _get_statistics(self, cr, uid, ids, name, arg, context=None):
305 """ Compute statistics of the mass mailing campaign """
310 COUNT(s.id) AS total,
311 COUNT(CASE WHEN s.sent is not null THEN 1 ELSE null END) AS sent,
312 COUNT(CASE WHEN s.scheduled is not null AND s.sent is null AND s.exception is null THEN 1 ELSE null END) AS scheduled,
313 COUNT(CASE WHEN s.scheduled is not null AND s.sent is null AND s.exception is not null THEN 1 ELSE null END) AS failed,
314 COUNT(CASE WHEN s.id is not null AND s.bounced is null THEN 1 ELSE null END) AS delivered,
315 COUNT(CASE WHEN s.opened is not null THEN 1 ELSE null END) AS opened,
316 COUNT(CASE WHEN s.replied is not null THEN 1 ELSE null END) AS replied ,
317 COUNT(CASE WHEN s.bounced is not null THEN 1 ELSE null END) AS bounced
319 mail_mail_statistics s
322 ON (m.id = s.mass_mailing_id)
328 for row in cr.dictfetchall():
329 results[row.pop('mailing_id')] = row
330 total = row['total'] or 1
331 row['delivered'] = row['sent'] - row['bounced']
332 row['received_ratio'] = 100.0 * row['delivered'] / total
333 row['opened_ratio'] = 100.0 * row['opened'] / total
334 row['replied_ratio'] = 100.0 * row['replied'] / total
337 def _get_mailing_model(self, cr, uid, context=None):
339 for model_name in self.pool:
340 model = self.pool[model_name]
341 if hasattr(model, '_mail_mass_mailing') and getattr(model, '_mail_mass_mailing'):
342 res.append((model._name, getattr(model, '_mail_mass_mailing')))
343 res.append(('mail.mass_mailing.contact', _('Mailing List')))
346 # indirections for inheritance
347 _mailing_model = lambda self, *args, **kwargs: self._get_mailing_model(*args, **kwargs)
350 'name': fields.char('Subject', required=True),
351 'email_from': fields.char('From', required=True),
352 'create_date': fields.datetime('Creation Date'),
353 'sent_date': fields.datetime('Sent Date', oldname='date', copy=False),
354 'body_html': fields.html('Body'),
355 'attachment_ids': fields.many2many(
356 'ir.attachment', 'mass_mailing_ir_attachments_rel',
357 'mass_mailing_id', 'attachment_id', 'Attachments'
359 'mass_mailing_campaign_id': fields.many2one(
360 'mail.mass_mailing.campaign', 'Mass Mailing Campaign',
363 'state': fields.selection(
364 [('draft', 'Draft'), ('test', 'Tested'), ('done', 'Sent')],
365 string='Status', required=True, copy=False,
367 'color': fields.related(
368 'mass_mailing_campaign_id', 'color',
369 type='integer', string='Color Index',
372 'reply_to_mode': fields.selection(
373 [('thread', 'In Document'), ('email', 'Specified Email Address')],
374 string='Reply-To Mode', required=True,
376 'reply_to': fields.char('Reply To', help='Preferred Reply-To Address'),
378 'mailing_model': fields.selection(_mailing_model, string='Recipients Model', required=True),
379 'mailing_domain': fields.char('Domain', oldname='domain'),
380 'contact_list_ids': fields.many2many(
381 'mail.mass_mailing.list', 'mail_mass_mailing_list_rel',
382 string='Mailing Lists',
384 'contact_ab_pc': fields.integer(
385 'AB Testing percentage',
386 help='Percentage of the contacts that will be mailed. Recipients will be taken randomly.'
389 'statistics_ids': fields.one2many(
390 'mail.mail.statistics', 'mass_mailing_id',
393 'total': fields.function(
394 _get_statistics, string='Total',
395 type='integer', multi='_get_statistics',
397 'scheduled': fields.function(
398 _get_statistics, string='Scheduled',
399 type='integer', multi='_get_statistics',
401 'failed': fields.function(
402 _get_statistics, string='Failed',
403 type='integer', multi='_get_statistics',
405 'sent': fields.function(
406 _get_statistics, string='Sent',
407 type='integer', multi='_get_statistics',
409 'delivered': fields.function(
410 _get_statistics, string='Delivered',
411 type='integer', multi='_get_statistics',
413 'opened': fields.function(
414 _get_statistics, string='Opened',
415 type='integer', multi='_get_statistics',
417 'replied': fields.function(
418 _get_statistics, string='Replied',
419 type='integer', multi='_get_statistics',
421 'bounced': fields.function(
422 _get_statistics, string='Bounced',
423 type='integer', multi='_get_statistics',
425 'received_ratio': fields.function(
426 _get_statistics, string='Received Ratio',
427 type='integer', multi='_get_statistics',
429 'opened_ratio': fields.function(
430 _get_statistics, string='Opened Ratio',
431 type='integer', multi='_get_statistics',
433 'replied_ratio': fields.function(
434 _get_statistics, string='Replied Ratio',
435 type='integer', multi='_get_statistics',
438 'opened_daily': fields.function(
439 _get_daily_statistics, string='Opened',
440 type='char', multi='_get_daily_statistics',
442 'replied_daily': fields.function(
443 _get_daily_statistics, string='Replied',
444 type='char', multi='_get_daily_statistics',
448 def default_get(self, cr, uid, fields, context=None):
449 res = super(MassMailing, self).default_get(cr, uid, fields, context=context)
450 if 'reply_to_mode' in fields and not 'reply_to_mode' in res and res.get('mailing_model'):
451 if res['mailing_model'] in ['res.partner', 'mail.mass_mailing.contact']:
452 res['reply_to_mode'] = 'email'
454 res['reply_to_mode'] = 'thread'
459 'email_from': lambda self, cr, uid, ctx=None: self.pool['mail.message']._get_default_from(cr, uid, context=ctx),
460 'reply_to': lambda self, cr, uid, ctx=None: self.pool['mail.message']._get_default_from(cr, uid, context=ctx),
461 'mailing_model': 'mail.mass_mailing.contact',
462 'contact_ab_pc': 100,
465 #------------------------------------------------------
467 #------------------------------------------------------
469 def copy_data(self, cr, uid, id, default=None, context=None):
470 mailing = self.browse(cr, uid, id, context=context)
471 default = dict(default or {},
472 name=_('%s (copy)') % mailing.name)
473 return super(MassMailing, self).copy_data(cr, uid, id, default, context=context)
475 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
476 """ Override read_group to always display all states. """
477 if groupby and groupby[0] == "state":
478 # Default result structure
479 # states = self._get_state_list(cr, uid, context=context)
480 states = [('draft', 'Draft'), ('test', 'Tested'), ('done', 'Sent')]
481 read_group_all_states = [{
482 '__context': {'group_by': groupby[1:]},
483 '__domain': domain + [('state', '=', state_value)],
484 'state': state_value,
486 } for state_value, state_name in states]
487 # Get standard results
488 read_group_res = super(MassMailing, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
489 # Update standard results with default results
491 for state_value, state_name in states:
492 res = filter(lambda x: x['state'] == state_value, read_group_res)
494 res = filter(lambda x: x['state'] == state_value, read_group_all_states)
495 res[0]['state'] = [state_value, state_name]
496 result.append(res[0])
499 return super(MassMailing, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
501 #------------------------------------------------------
503 #------------------------------------------------------
505 def on_change_model_and_list(self, cr, uid, ids, mailing_model, list_ids, context=None):
507 if mailing_model == 'mail.mass_mailing.contact':
508 mailing_list_ids = set()
509 for item in list_ids:
510 if isinstance(item, (int, long)):
511 mailing_list_ids.add(item)
513 mailing_list_ids |= set(item[2])
515 value['mailing_domain'] = "[('list_id', 'in', %s)]" % list(mailing_list_ids)
517 value['mailing_domain'] = "[('list_id', '=', False)]"
519 value['mailing_domain'] = False
520 return {'value': value}
522 def action_duplicate(self, cr, uid, ids, context=None):
525 copy_id = self.copy(cr, uid, mid, context=context)
528 'type': 'ir.actions.act_window',
531 'res_model': 'mail.mass_mailing',
537 def action_test_mailing(self, cr, uid, ids, context=None):
538 ctx = dict(context, default_mass_mailing_id=ids[0])
540 'name': _('Test Mailing'),
541 'type': 'ir.actions.act_window',
543 'res_model': 'mail.mass_mailing.test',
548 def action_edit_html(self, cr, uid, ids, context=None):
549 if not len(ids) == 1:
550 raise ValueError('One and only one ID allowed for this action')
551 mail = self.browse(cr, uid, ids[0], context=context)
552 url = '/website_mail/email_designer?model=mail.mass_mailing&res_id=%d&template_model=%s&enable_editor=1' % (ids[0], mail.mailing_model)
554 'name': _('Open with Visual Editor'),
555 'type': 'ir.actions.act_url',
560 #------------------------------------------------------
562 #------------------------------------------------------
564 def get_recipients(self, cr, uid, mailing, context=None):
565 if mailing.mailing_domain:
566 domain = eval(mailing.mailing_domain)
567 res_ids = self.pool[mailing.mailing_model].search(cr, uid, domain, context=context)
570 domain = [('id', 'in', res_ids)]
572 # randomly choose a fragment
573 if mailing.contact_ab_pc < 100:
574 contact_nbr = self.pool[mailing.mailing_model].search(cr, uid, domain, count=True, context=context)
575 topick = int(contact_nbr / 100.0 * mailing.contact_ab_pc)
576 if mailing.mass_mailing_campaign_id and mailing.mass_mailing_campaign_id.unique_ab_testing:
577 already_mailed = self.pool['mail.mass_mailing.campaign'].get_recipients(cr, uid, [mailing.mass_mailing_campaign_id.id], context=context)[mailing.mass_mailing_campaign_id.id]
579 already_mailed = set([])
580 remaining = set(res_ids).difference(already_mailed)
581 if topick > len(remaining):
582 topick = len(remaining)
583 res_ids = random.sample(remaining, topick)
586 def send_mail(self, cr, uid, ids, context=None):
587 author_id = self.pool['res.users'].browse(cr, uid, uid, context=context).partner_id.id
588 for mailing in self.browse(cr, uid, ids, context=context):
589 # instantiate an email composer + send emails
590 res_ids = self.get_recipients(cr, uid, mailing, context=context)
592 raise Warning('Please select recipients.')
593 comp_ctx = dict(context, active_ids=res_ids)
595 'author_id': author_id,
596 'body': mailing.body_html,
597 'subject': mailing.name,
598 'model': mailing.mailing_model,
599 'email_from': mailing.email_from,
600 'record_name': False,
601 'composition_mode': 'mass_mail',
602 'mass_mailing_id': mailing.id,
603 'mailing_list_ids': [(4, l.id) for l in mailing.contact_list_ids],
604 'same_thread': mailing.reply_to_mode == 'thread',
606 if mailing.reply_to_mode == 'email':
607 composer_values['reply_to'] = mailing.reply_to
608 composer_id = self.pool['mail.compose.message'].create(cr, uid, composer_values, context=comp_ctx)
609 self.pool['mail.compose.message'].send_mail(cr, uid, [composer_id], context=comp_ctx)
610 self.write(cr, uid, [mailing.id], {'sent_date': fields.datetime.now(), 'state': 'done'}, context=context)