diff --git a/addons/base_calendar/base_calendar.py b/addons/base_calendar/base_calendar.py
index a9e5949a3ca..e89a52aa0e5 100644
--- a/addons/base_calendar/base_calendar.py
+++ b/addons/base_calendar/base_calendar.py
@@ -515,7 +515,7 @@ property or property parameter."),
sub,
body,
attachments=attach and {'invitation.ics': attach} or None,
- subtype='html',
+ content_subtype='html',
reply_to=email_from,
context=context
)
diff --git a/addons/crm/__openerp__.py b/addons/crm/__openerp__.py
index 22786998f96..bc0a9e6cf3d 100644
--- a/addons/crm/__openerp__.py
+++ b/addons/crm/__openerp__.py
@@ -85,7 +85,6 @@ Creates a dashboard for CRM that includes:
'wizard/crm_opportunity_to_phonecall_view.xml',
'wizard/crm_partner_to_opportunity_view.xml',
- 'wizard/crm_add_note_view.xml',
'wizard/crm_merge_opportunities_view.xml',
'crm_view.xml',
diff --git a/addons/crm/security/ir.model.access.csv b/addons/crm/security/ir.model.access.csv
index 5665839f365..91e5f1c1769 100644
--- a/addons/crm/security/ir.model.access.csv
+++ b/addons/crm/security/ir.model.access.csv
@@ -24,13 +24,11 @@ access_crm_phonecall_report_user,crm.phonecall.report.user,model_crm_phonecall_r
access_crm_phonecall_report_manager,crm.phonecall.report,model_crm_phonecall_report,base.group_sale_manager,1,1,1,1
access_res_partner_manager,res.partner.crm.manager,base.model_res_partner,base.group_sale_manager,1,0,0,0
access_res_partner_category_manager,res.partner.category.crm.manager,base.model_res_partner_category,base.group_sale_manager,1,0,0,0
-mail_mail_message_manager,mail.message.manager,mail.model_mail_message,base.group_sale_manager,1,0,0,0
access_calendar_attendee_crm_user,calendar.attendee.crm.user,model_calendar_attendee,base.group_sale_salesman,1,1,1,0
access_calendar_attendee_crm_manager,calendar.attendee.crm.manager,model_calendar_attendee,base.group_sale_manager,1,1,1,1
access_res_partner,res.partner.crm.user,base.model_res_partner,base.group_sale_salesman,1,1,1,0
access_res_partner_category,res.partner.category.crm.user,base.model_res_partner_category,base.group_sale_salesman,1,1,1,0
mail_mailgate_thread,mail.thread,mail.model_mail_thread,base.group_sale_salesman,1,1,1,1
-mail_gateway_mail_message_user,mail.message.user,mail.model_mail_message,base.group_sale_salesman,1,1,1,1
access_crm_case_categ_manager,crm.case.categ manager,model_crm_case_categ,base.group_sale_manager,1,1,1,1
access_base_action_rule_manager,base.action.rule manager,model_base_action_rule,base.group_sale_manager,1,1,1,1
access_crm_lead_report_user,crm.lead.report user,model_crm_lead_report,base.group_sale_salesman,1,1,1,1
diff --git a/addons/crm/test/process/lead2opportunity2win.yml b/addons/crm/test/process/lead2opportunity2win.yml
index 1c2cfdeb605..a3e7fac372a 100644
--- a/addons/crm/test/process/lead2opportunity2win.yml
+++ b/addons/crm/test/process/lead2opportunity2win.yml
@@ -54,10 +54,8 @@
-
After communicated with customer, I put some notes with contract details.
-
- !python {model: crm.add.note}: |
- context.update({'active_model': 'crm.lead', 'active_id': ref('crm_case_qrecorp0')})
- note_id = self.create(cr, uid, {'body': "ces détails envoyés par le client sur le FAX pour la qualité"})
- self.action_add(cr, uid, [note_id], context=context)
+ !python {model: crm.lead}: |
+ self.message_append_note(cr, uid, [ref('crm_case_qrecorp0')], subject='Test note', body='ces détails envoyés par le client sur le FAX pour la qualité')
-
I win this opportunity
-
diff --git a/addons/crm/wizard/__init__.py b/addons/crm/wizard/__init__.py
index 9d128492422..15ca8df670d 100644
--- a/addons/crm/wizard/__init__.py
+++ b/addons/crm/wizard/__init__.py
@@ -19,8 +19,6 @@
#
##############################################################################
-import crm_add_note
-
import crm_lead_to_partner
import crm_lead_to_opportunity
import crm_phonecall_to_phonecall
diff --git a/addons/crm/wizard/crm_add_note.py b/addons/crm/wizard/crm_add_note.py
deleted file mode 100644
index 02f592f0136..00000000000
--- a/addons/crm/wizard/crm_add_note.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from .. import crm
-from osv import fields, osv
-from tools.translate import _
-from mail.mail_message import truncate_text
-
-AVAILABLE_STATES = crm.AVAILABLE_STATES + [('unchanged', 'Unchanged')]
-
-class crm_add_note(osv.osv_memory):
- """Adds a new note to the case."""
- _name = 'crm.add.note'
- _description = "Add Internal Note"
-
- _columns = {
- 'body': fields.text('Note Body', required=True),
- 'state': fields.selection(AVAILABLE_STATES, string='Set New State To',
- required=True),
- }
-
- _defaults = {
- 'state': 'unchanged'
- }
-
- def action_add(self, cr, uid, ids, context=None):
- if context is None:
- context = {}
-
- if not context.get('active_model'):
- raise osv.except_osv(_('Error'), _('Can not add note!'))
-
- model = context.get('active_model')
- case_pool = self.pool.get(model)
-
- for obj in self.browse(cr, uid, ids, context=context):
- case_list = case_pool.browse(cr, uid, context['active_ids'],
- context=context)
- case = case_list[0]
- case_pool.message_append(cr, uid, [case], truncate_text(obj.body),
- body_text=obj.body)
- if obj.state == 'unchanged':
- pass
- elif obj.state == 'done':
- case_pool.case_close(cr, uid, [case.id])
- elif obj.state == 'draft':
- case_pool.case_reset(cr, uid, [case.id])
- elif obj.state in ['cancel', 'open', 'pending']:
- act = 'case_' + obj.state
- getattr(case_pool, act)(cr, uid, [case.id])
-
- return {'type': 'ir.actions.act_window_close'}
-
-crm_add_note()
-
-# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/crm/wizard/crm_add_note_view.xml b/addons/crm/wizard/crm_add_note_view.xml
deleted file mode 100644
index fc4b57f85dc..00000000000
--- a/addons/crm/wizard/crm_add_note_view.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
-
-
-
- crm.new.add.note.form
- crm.add.note
- form
-
-
-
-
-
-
-
-
- Add Note
- crm.add.note
- form
- form
-
- new
-
-
-
-
-
diff --git a/addons/email_template/email_template.py b/addons/email_template/email_template.py
index c4ed2eedb85..bf57342f14f 100644
--- a/addons/email_template/email_template.py
+++ b/addons/email_template/email_template.py
@@ -101,6 +101,11 @@ class email_template(osv.osv):
mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
return {'value':{'model': mod_name}}
+ def name_get(self, cr, uid, ids, context=None):
+ """ Override name_get of mail.message: return directly the template
+ name, and not the generated name from mail.message.common."""
+ return [(record.id, record.name) for record in self.browse(cr, uid, ids, context=context)]
+
_columns = {
'name': fields.char('Name', size=250),
'model_id': fields.many2one('ir.model', 'Related document model'),
@@ -311,7 +316,7 @@ class email_template(osv.osv):
'attachment_ids': False,
'message_id': False,
'state': 'outgoing',
- 'subtype': 'plain',
+ 'content_subtype': 'plain',
}
if not template_id:
return values
@@ -326,8 +331,15 @@ class email_template(osv.osv):
template.model, res_id, context=context) \
or False
+ # if email_to: find or create a partner
+ if values['email_to']:
+ partner_id = self.pool.get('mail.thread').message_partner_by_email(cr, uid, values['email_to'], context=context)['partner_id']
+ if not partner_id:
+ partner_id = self.pool.get('res.partner').name_create(cr, uid, values['email_to'], context=context)
+ values['partner_ids'] = [partner_id]
+
if values['body_html']:
- values.update(subtype='html')
+ values.update(content_subtype='html')
if template.user_signature:
signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
diff --git a/addons/email_template/static/src/img/email_template.png b/addons/email_template/static/src/img/email_template.png
new file mode 100644
index 00000000000..d679492bc19
Binary files /dev/null and b/addons/email_template/static/src/img/email_template.png differ
diff --git a/addons/email_template/static/src/img/email_template_save.png b/addons/email_template/static/src/img/email_template_save.png
new file mode 100644
index 00000000000..bf29f9ab4ad
Binary files /dev/null and b/addons/email_template/static/src/img/email_template_save.png differ
diff --git a/addons/email_template/wizard/email_compose_message_view.xml b/addons/email_template/wizard/email_compose_message_view.xml
index 96ea55da9e5..a911034cb1a 100644
--- a/addons/email_template/wizard/email_compose_message_view.xml
+++ b/addons/email_template/wizard/email_compose_message_view.xml
@@ -25,5 +25,32 @@
+
+
+ mail.compose.message.form
+ mail.compose.message
+ form
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/email_template/wizard/mail_compose_message.py b/addons/email_template/wizard/mail_compose_message.py
index a4fd749979c..1b007a990c0 100644
--- a/addons/email_template/wizard/mail_compose_message.py
+++ b/addons/email_template/wizard/mail_compose_message.py
@@ -27,19 +27,6 @@ from tools.translate import _
import tools
-def _reopen(self,res_id,model):
- return {'type': 'ir.actions.act_window',
- 'view_mode': 'form',
- 'view_type': 'form',
- 'res_id': res_id,
- 'res_model': self._name,
- 'target': 'new',
-
- # save original model in context, otherwise
- # it will be lost on the action's context switch
- 'context': {'mail.compose.target.model': model}
- }
-
class mail_compose_message(osv.osv_memory):
_inherit = 'mail.compose.message'
@@ -87,6 +74,8 @@ class mail_compose_message(osv.osv_memory):
else:
# render the mail as one-shot
values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context)
+ # get partner_ids back
+ values['dest_partner_ids'] = values['partner_ids']
# retrofit generated attachments in the expected field format
if values['attachments']:
attachment = values.pop('attachments')
@@ -110,18 +99,24 @@ class mail_compose_message(osv.osv_memory):
return {'value': values}
-
def template_toggle(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
- had_template = record.use_template
- record.write({'use_template': not(had_template)})
- if had_template:
+ values = {}
+ use_template = record.use_template
+ # simulate an on_change on use_template
+ values.update(self.onchange_use_template(cr, uid, ids, not use_template, context=context)['value'])
+ record.write(values)
+ return False
+
+ def onchange_use_template(self, cr, uid, ids, use_template, context=None):
+ values = {'use_template': use_template}
+ for record in self.browse(cr, uid, ids, context=context):
+ if not use_template:
# equivalent to choosing an empty template
- onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template),
- False, email_from=record.email_from,
- email_to=record.email_to, context=context)
- record.write(onchange_defaults['value'])
- return _reopen(self, record.id, record.model)
+ onchange_template_values = self.on_change_template(cr, uid, record.id, use_template,
+ False, email_from=record.email_from, email_to=record.email_to, context=context)
+ values.update(onchange_template_values['value'])
+ return {'value': values}
def save_as_template(self, cr, uid, ids, context=None):
if context is None:
@@ -153,7 +148,7 @@ class mail_compose_message(osv.osv_memory):
'use_template': True})
# _reopen same wizard screen with new template preselected
- return _reopen(self, record.id, model)
+ return False
# override the basic implementation
def render_template(self, cr, uid, template, model, res_id, context=None):
diff --git a/addons/hr/hr.py b/addons/hr/hr.py
index 4a0c3736222..2a0ea3b45a4 100644
--- a/addons/hr/hr.py
+++ b/addons/hr/hr.py
@@ -212,6 +212,16 @@ class hr_employee(osv.osv):
'last_login': fields.related('user_id', 'date', type='datetime', string='Latest Connection', readonly=1),
}
+ def create(self, cr, uid, data, context=None):
+ employee_id = super(hr_employee, self).create(cr, uid, data, context=context)
+ try:
+ (model, mail_group_id) = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'group_all_employees')
+ employee = self.browse(cr, uid, employee_id, context=context)
+ self.pool.get('mail.group').message_append_note(cr, uid, [mail_group_id], body='Welcome to %s! Please help him make its first steps in OpenERP!' % (employee.name), context=context)
+ except:
+ pass # group deleted: do not push a message
+ return employee_id
+
def unlink(self, cr, uid, ids, context=None):
resource_obj = self.pool.get('resource.resource')
resource_ids = []
diff --git a/addons/hr_evaluation/wizard/mail_compose_message.py b/addons/hr_evaluation/wizard/mail_compose_message.py
index 7b4c1b69164..7e4ba326947 100644
--- a/addons/hr_evaluation/wizard/mail_compose_message.py
+++ b/addons/hr_evaluation/wizard/mail_compose_message.py
@@ -44,15 +44,9 @@ class mail_compose_message(osv.osv_memory):
if record_data.state == "waiting_answer":
msg = _("Hello %s, \n\n Kindly post your response for '%s' survey interview. \n\n Thanks,") %(record_data.user_to_review_id.name, record_data.survey_id.title)
result.update({
- 'email_from': tools.config.get('email_from',''),
'email_to': record_data.user_to_review_id.work_email or False,
'subject': _("Reminder to fill up Survey"),
'body_text': msg,
- 'res_id': resource_id,
- 'model': model,
- 'email_cc': False,
- 'email_bcc': False,
- 'reply_to': False,
})
return result
diff --git a/addons/hr_recruitment/hr_recruitment_data.xml b/addons/hr_recruitment/hr_recruitment_data.xml
index fe5d3d9969b..6b64964eb2a 100644
--- a/addons/hr_recruitment/hr_recruitment_data.xml
+++ b/addons/hr_recruitment/hr_recruitment_data.xml
@@ -1,9 +1,6 @@
-
-
diff --git a/addons/hr_recruitment/security/ir.model.access.csv b/addons/hr_recruitment/security/ir.model.access.csv
index 7d082070be5..8b029c9324a 100644
--- a/addons/hr_recruitment/security/ir.model.access.csv
+++ b/addons/hr_recruitment/security/ir.model.access.csv
@@ -3,7 +3,6 @@ access_hr_applicant_user,hr.applicant.user,model_hr_applicant,base.group_hr_user
access_hr_recruitment_report,hr.recruitment.report,model_hr_recruitment_report,base.group_hr_manager,1,1,1,1
access_hr_recruitment_stage_user,hr.recruitment.stage.user,model_hr_recruitment_stage,base.group_hr_user,1,1,1,1
access_hr_recruitment_degree,hr.recruitment.degree,model_hr_recruitment_degree,base.group_hr_user,1,1,1,1
-access_mail_message_user,mail.message.user,mail.model_mail_message,base.group_hr_user,1,1,1,1
access_res_partner_hr_user,res.partner.user,base.model_res_partner,base.group_hr_user,1,1,1,1
access_survey_hr_user,survey.hr.user,survey.model_survey,base.group_hr_user,1,1,1,0
access_crm_meeting_hruser,crm.meeting.hruser,base_calendar.model_crm_meeting,base.group_hr_user,1,1,1,1
diff --git a/addons/mail/__openerp__.py b/addons/mail/__openerp__.py
index cb949a63efc..abb290332a7 100644
--- a/addons/mail/__openerp__.py
+++ b/addons/mail/__openerp__.py
@@ -67,11 +67,11 @@ The main features of the module are :
'mail_thread_view.xml',
'mail_group_view.xml',
'res_partner_view.xml',
+ 'res_users_view.xml',
+ 'data/mail_data.xml',
+ 'data/mail_group_data.xml',
'security/mail_security.xml',
'security/ir.model.access.csv',
- 'mail_data.xml',
- 'mail_group_data.xml',
- 'res_users_view.xml',
],
'installable': True,
'auto_install': False,
@@ -84,13 +84,15 @@ The main features of the module are :
'static/src/img/email_icong.png',
'static/src/img/_al.png',
'static/src/img/_pincky.png',
- 'static/src/img/feeds.png',
- 'static/src/img/feeds-hover.png',
'static/src/img/groupdefault.png',
+ 'static/src/img/attachment.png',
+ 'static/src/img/checklist.png',
+ 'static/src/img/formatting.png',
],
'css': [
'static/src/css/mail.css',
'static/src/css/mail_group.css',
+ 'static/src/css/mail_compose_message.css',
],
'js': [
'static/lib/jquery.expander/jquery.expander.js',
@@ -100,7 +102,7 @@ The main features of the module are :
'static/src/xml/mail.xml',
],
'demo': [
- 'mail_demo.xml',
+ 'data/mail_demo.xml',
],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/mail/mail_data.xml b/addons/mail/data/mail_data.xml
similarity index 100%
rename from addons/mail/mail_data.xml
rename to addons/mail/data/mail_data.xml
diff --git a/addons/mail/mail_demo.xml b/addons/mail/data/mail_demo.xml
similarity index 93%
rename from addons/mail/mail_demo.xml
rename to addons/mail/data/mail_demo.xml
index 1adec42a910..274259e544e 100644
--- a/addons/mail/mail_demo.xml
+++ b/addons/mail/data/mail_demo.xml
@@ -1,6 +1,6 @@
-
+
A cool attachment
@@ -28,7 +28,7 @@
Internal company announcemail.group
- html
+ htmlsit amet, consectetur adipiscing elit. Pellentesque et quam sapien, in sagittis tellus.
Praesent vel massa sed massa consequat egestas in tristique orci. Praesent iaculis libero et neque vehicula iaculis. Vivamus placerat tincidunt orci ac ornare. Proin ut dolor fringilla velit ultricies consequat. Maecenas sit amet ipsum non leo interdum imperdiet. Donec sapien mi, varius a consequat id, consectetur sit amet nulla.
@@ -41,10 +41,9 @@ Nulla turpis leo, rhoncus ut egestas sit amet, consectetur vitae urna. Mauris in
- Replymail.group
- html
+ htmltremendous blogpost ! (first comment)]]>comment
@@ -52,10 +51,9 @@ Nulla turpis leo, rhoncus ut egestas sit amet, consectetur vitae urna. Mauris in
- Replymail.group
- html
+ html
@@ -75,10 +73,9 @@ Would it be possible to learn more about the author ? (second comment)]]>
- Replymail.group
- html
+ htmlAll Company
+ All company users can come here and discuss.Sales
+
+ All Employees
+
+
diff --git a/addons/mail/doc/mail_message.rst b/addons/mail/doc/mail_message.rst
index e41a772cac8..56244e251bf 100644
--- a/addons/mail/doc/mail_message.rst
+++ b/addons/mail/doc/mail_message.rst
@@ -3,22 +3,26 @@
mail.message
============
-TODO
+Models
++++++++
-mail.group
-++++++++++
+``mail.message.common`` is an abstract class for holding the main attributes of a
+message object. It could be reused as parent model for any database model
+or wizard screen that needs to hold a kind of message.
-A mail_group is a collection of users sharing messages in a discussion group. Group users are users that follow the mail group, using the subscription/follow mechanism of OpenSocial. A mail group has nothing in common wih res.users.group.
-Additional information on fields:
+All internal logic should be in a database-based model while this model
+holds the basics of a message. For example, a wizard for writing emails
+should inherit from this class and not from mail.message.
- - ``member_ids``: user member of the groups are calculated with ``message_get_subscribers`` method from mail.thread
- - ``member_count``: calculated with member_ids
- - ``is_subscriber``: calculated with member_ids
-res.users
-+++++++++
+.. versionchanged:: 7.0
-OpenChatter updates the res.users class:
- - it adds a preference about sending emails when receiving a notification
- - make a new user follow itself automatically
- - create a welcome message when creating a new user, to make his arrival in OpenERP more friendly
+ - ``subtype`` is renamed to ``content_subtype``: usually 'html' or 'plain'.
+ This field is used to select plain-text or rich-text contents accordingly.
+ - ``subtype`` is moved to mail.message model. The purpose is to be able to
+ distinguish message of the same type, such as notifications about creating
+ or cancelling a record. For example, it is used to add the possibility
+ to hide notifications in the wall.
+
+Those changes aim at being able to distinguish the message content to the
+message itself.
diff --git a/addons/mail/doc/mail_thread.rst b/addons/mail/doc/mail_thread.rst
index f15f78156d3..41ea014b06c 100644
--- a/addons/mail/doc/mail_thread.rst
+++ b/addons/mail/doc/mail_thread.rst
@@ -3,7 +3,25 @@
mail.thread and OpenChatter
===========================
-TODO
+API
++++
+
+Writing messages and notifications
+----------------------------------
+
+``message_append``
+
+Creates a new mail.message through message_create. The new message is attached
+to the current mail.thread, containing all the details passed as parameters.
+All attachments will be attached to the thread record as well as to the
+actual message.
+
+This method calls message_create that will handle management of subscription
+and notifications, and effectively create the message.
+
+If ``email_from`` is not set or ``type`` not set as 'email', a note message
+is created (comment or system notification), without the usual envelope
+attributes (sender, recipients, etc.).
mail.group
++++++++++
diff --git a/addons/mail/mail_group.py b/addons/mail/mail_group.py
index f691d75e0bc..36001ee6074 100644
--- a/addons/mail/mail_group.py
+++ b/addons/mail/mail_group.py
@@ -36,7 +36,7 @@ class mail_group(osv.osv):
A mail_group is a collection of users sharing messages in a discussion
group. Group users are users that follow the mail group, using the
subscription/follow mechanism of OpenSocial. A mail group has nothing
- in common wih res.users.group.
+ in common with res.users.group.
Additional information on fields:
- ``member_ids``: user member of the groups are calculated with
``message_get_subscribers`` method from mail.thread
@@ -49,12 +49,6 @@ class mail_group(osv.osv):
_name = 'mail.group'
_inherit = ['mail.thread']
- def action_group_join(self, cr, uid, ids, context={}):
- return self.message_subscribe(cr, uid, ids, context=context);
-
- def action_group_leave(self, cr, uid, ids, context={}):
- return self.message_unsubscribe(cr, uid, ids, context=context);
-
def onchange_photo(self, cr, uid, ids, value, context=None):
if not value:
return {'value': {'avatar_big': value, 'avatar': value} }
@@ -105,7 +99,7 @@ class mail_group(osv.osv):
message_obj = self.pool.get('mail.message')
for id in ids:
lower_date = (DT.datetime.now() - DT.timedelta(days=30)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
- result[id] = message_obj.search(cr, uid, ['&', '&', ('model', '=', self._name), ('res_id', 'in', ids), ('date', '>=', lower_date)], count=True, context=context)
+ result[id] = self.message_search(cr, uid, [id], limit=None, domain=[('date', '>=', lower_date)], count=True, context=context)
return result
def _get_default_photo(self, cr, uid, context=None):
@@ -116,19 +110,33 @@ class mail_group(osv.osv):
'name': fields.char('Name', size=64, required=True),
'description': fields.text('Description'),
'responsible_id': fields.many2one('res.users', string='Responsible',
- ondelete='set null', required=True, select=1,
- help="Responsible of the group that has all rights on the record."),
- 'public': fields.boolean('Public', help='This group is visible by non members. Invisible groups can add members through the invite button.'),
- 'photo_big': fields.binary('Full-size photo', help='Field holding the full-sized PIL-supported and base64 encoded version of the group image. The photo field is used as an interface for this field.'),
- 'photo': fields.function(_get_photo, fnct_inv=_set_photo, string='Photo', type="binary",
+ ondelete='set null', required=True, select=1,
+ help="Responsible of the group that has all rights on the record."),
+ 'public': fields.boolean('Visible by non members', help='This group is visible by non members. \
+ Invisible groups can add members through the invite button.'),
+ 'group_ids': fields.many2many('res.groups', rel='mail_group_res_group_rel',
+ id1='mail_group_id', id2='groups_id', string='Linked groups',
+ help="Members of those groups will automatically added as followers. "\
+ "Note that they will be able to manage their subscription manually "\
+ "if necessary."),
+ 'photo_big': fields.binary('Full-size photo',
+ help='Field holding the full-sized PIL-supported and base64 encoded "\
+ version of the group image. The photo field is used as an "\
+ interface for this field.'),
+ 'photo': fields.function(_get_photo, fnct_inv=_set_photo,
+ string='Photo', type="binary",
store = {
'mail.group': (lambda self, cr, uid, ids, c={}: ids, ['photo_big'], 10),
- }, help='Field holding the automatically resized (128x128) PIL-supported and base64 encoded version of the group image.'),
- 'member_ids': fields.function(get_member_ids, fnct_search=search_member_ids, type='many2many',
- relation='res.users', string='Group members', multi='get_member_ids'),
- 'member_count': fields.function(get_member_ids, type='integer', string='Member count', multi='get_member_ids'),
- 'is_subscriber': fields.function(get_member_ids, type='boolean', string='Joined', multi='get_member_ids'),
- 'last_month_msg_nbr': fields.function(get_last_month_msg_nbr, type='integer', string='Messages count for last month'),
+ },
+ help='Field holding the automatically resized (128x128) PIL-supported and base64 encoded version of the group image.'),
+ 'member_ids': fields.function(get_member_ids, fnct_search=search_member_ids,
+ type='many2many', relation='res.users', string='Group members', multi='get_member_ids'),
+ 'member_count': fields.function(get_member_ids, type='integer',
+ string='Member count', multi='get_member_ids'),
+ 'is_subscriber': fields.function(get_member_ids, type='boolean',
+ string='Joined', multi='get_member_ids'),
+ 'last_month_msg_nbr': fields.function(get_last_month_msg_nbr, type='integer',
+ string='Messages count for last month'),
}
_defaults = {
@@ -136,3 +144,32 @@ class mail_group(osv.osv):
'responsible_id': (lambda s, cr, uid, ctx: uid),
'photo': _get_default_photo,
}
+
+ def _subscribe_user_with_group_m2m_command(self, cr, uid, ids, group_ids_command, context=None):
+ # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
+ user_group_ids = [command[1] for command in group_ids_command if command[0] == 4]
+ user_group_ids += [id for command in group_ids_command if command[0] == 6 for id in command[2]]
+ # retrieve the user member of those groups
+ user_ids = []
+ res_groups_obj = self.pool.get('res.groups')
+ for group in res_groups_obj.browse(cr, uid, user_group_ids, context=context):
+ user_ids += [user.id for user in group.users]
+ # subscribe the users
+ return self.message_subscribe(cr, uid, ids, user_ids, context=context)
+
+ def create(self, cr, uid, vals, context=None):
+ mail_group_id = super(mail_group, self).create(cr, uid, vals, context=context)
+ if vals.get('group_ids'):
+ self._subscribe_user_with_group_m2m_command(cr, uid, [mail_group_id], vals.get('group_ids'), context=context)
+ return mail_group_id
+
+ def write(self, cr, uid, ids, vals, context=None):
+ if vals.get('group_ids'):
+ self._subscribe_user_with_group_m2m_command(cr, uid, ids, vals.get('group_ids'), context=context)
+ return super(mail_group, self).write(cr, uid, ids, vals, context=context)
+
+ def action_group_join(self, cr, uid, ids, context=None):
+ return self.message_subscribe(cr, uid, ids, context=context)
+
+ def action_group_leave(self, cr, uid, ids, context=None):
+ return self.message_unsubscribe(cr, uid, ids, context=context)
diff --git a/addons/mail/mail_group_view.xml b/addons/mail/mail_group_view.xml
index 97210b8c179..c755209f952 100644
--- a/addons/mail/mail_group_view.xml
+++ b/addons/mail/mail_group_view.xml
@@ -64,6 +64,7 @@
+
diff --git a/addons/mail/mail_message.py b/addons/mail/mail_message.py
index 301657ba4c2..b96b6e3791e 100644
--- a/addons/mail/mail_message.py
+++ b/addons/mail/mail_message.py
@@ -30,66 +30,61 @@ import datetime
from email.header import decode_header
from email.message import Message
-import tools
+from openerp import SUPERUSER_ID
from osv import osv
from osv import fields
+import pytz
+from tools import DEFAULT_SERVER_DATETIME_FORMAT
from tools.translate import _
-from openerp import SUPERUSER_ID
+import tools
_logger = logging.getLogger(__name__)
-def format_date_tz(date, tz=None):
- if not date:
- return 'n/a'
- format = tools.DEFAULT_SERVER_DATETIME_FORMAT
- return tools.server_to_local_timestamp(date, format, format, tz)
-
-def truncate_text(text):
- lines = text and text.split('\n') or []
- if len(lines) > 3:
- res = '\n\t'.join(lines[:3]) + '...'
- else:
- res = '\n\t'.join(lines)
- return res
-
+""" Some tools for parsing / creating email fields """
def decode(text):
"""Returns unicode() string conversion of the the given encoded smtp header text"""
if text:
text = decode_header(text.replace('\r', ''))
return ''.join([tools.ustr(x[0], x[1]) for x in text])
-def to_email(text):
+def mail_tools_to_email(text):
"""Return a list of the email addresses found in ``text``"""
if not text: return []
return re.findall(r'([^ ,<@]+@[^> ,]+)', text)
-class mail_message_common(osv.osv_memory):
- """Common abstract class for holding the main attributes of a
- message object. It could be reused as parent model for any
- database model or wizard screen that needs to hold a kind of
- message"""
+# TODO: remove that after cleaning
+def to_email(text):
+ return mail_tools_to_email(text)
+
+class mail_message_common(osv.TransientModel):
+ """ Common abstract class for holding the main attributes of a
+ message object. It could be reused as parent model for any
+ database model or wizard screen that needs to hold a kind of
+ message.
+ All internal logic should be in another model while this
+ model holds the basics of a message. For example, a wizard for writing
+ emails should inherit from this class and not from mail.message."""
def get_body(self, cr, uid, ids, name, arg, context=None):
- if context is None:
- context = {}
+ """ get correct body version: body_html for html messages, and
+ body_text for plain text messages
+ """
result = dict.fromkeys(ids, '')
for message in self.browse(cr, uid, ids, context=context):
- if message.subtype == 'html':
+ if message.content_subtype == 'html':
result[message.id] = message.body_html
else:
result[message.id] = message.body_text
return result
def search_body(self, cr, uid, obj, name, args, context=None):
- """will receive:
- - obj: mail.message object
- - name: 'body'
- - args: [('body', 'ilike', 'blah')]"""
- return ['|', '&', ('subtype', '=', 'html'), ('body_html', args[0][1], args[0][2]), ('body_text', args[0][1], args[0][2])]
+ # will receive:
+ # - obj: mail.message object
+ # - name: 'body'
+ # - args: [('body', 'ilike', 'blah')]
+ return ['|', '&', ('content_subtype', '=', 'html'), ('body_html', args[0][1], args[0][2]), ('body_text', args[0][1], args[0][2])]
def get_record_name(self, cr, uid, ids, name, arg, context=None):
- if context is None:
- context = {}
result = dict.fromkeys(ids, '')
for message in self.browse(cr, uid, ids, context=context):
if not message.model or not message.res_id:
@@ -116,8 +111,9 @@ class mail_message_common(osv.osv_memory):
'subject': fields.char('Subject', size=512),
'model': fields.char('Related Document Model', size=128, select=1),
'res_id': fields.integer('Related Document ID', select=1),
- 'record_name': fields.function(get_record_name, type='string', string='Message Record Name',
- help="Name of the record, matching the result of the name_get."),
+ 'record_name': fields.function(get_record_name, type='string',
+ string='Message Record Name',
+ help="Name get of the related document."),
'date': fields.datetime('Date'),
'email_from': fields.char('From', size=128, help='Message sender, taken from user preferences.'),
'email_to': fields.char('To', size=256, help='Message recipients'),
@@ -125,104 +121,99 @@ class mail_message_common(osv.osv_memory):
'email_bcc': fields.char('Bcc', size=256, help='Blind carbon copy message recipients'),
'reply_to':fields.char('Reply-To', size=256, help='Preferred response address for the message'),
'headers': fields.text('Message Headers', readonly=1,
- help="Full message headers, e.g. SMTP session headers (usually available on inbound messages only)"),
+ help="Full message headers, e.g. SMTP session headers (usually available on inbound messages only)"),
'message_id': fields.char('Message-Id', size=256, help='Message unique identifier', select=1, readonly=1),
'references': fields.text('References', help='Message references, such as identifiers of previous messages', readonly=1),
- 'subtype': fields.char('Message Type', size=32, help="Type of message, usually 'html' or 'plain', used to "
- "select plaintext or rich text contents accordingly", readonly=1),
+ 'content_subtype': fields.char('Message content subtype', size=32,
+ oldname="subtype", readonly=1,
+ help="Type of message, usually 'html' or 'plain', used to select "\
+ "plain-text or rich-text contents accordingly"),
'body_text': fields.text('Text Contents', help="Plain-text version of the message"),
'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML version of the message"),
- 'body': fields.function(get_body, fnct_search = search_body, string='Message Content', type='text',
- help="Content of the message. This content equals the body_text field for plain-test messages, and body_html for rich-text/HTML messages. This allows having one field if we want to access the content matching the message subtype."),
- 'parent_id': fields.many2one('mail.message', 'Parent Message', help="Parent message, used for displaying as threads with hierarchy",
- select=True, ondelete='set null',),
- 'child_ids': fields.one2many('mail.message', 'parent_id', 'Child Messages'),
+ 'body': fields.function(get_body, fnct_search = search_body, type='text',
+ string='Message Content', store=True,
+ help="Content of the message. This content equals the body_text field "\
+ "for plain-test messages, and body_html for rich-text/HTML "\
+ "messages. This allows having one field if we want to access "\
+ "the content matching the message content_subtype."),
+ 'parent_id': fields.many2one('mail.message.common', 'Parent Message',
+ select=True, ondelete='set null',
+ help="Parent message, used for displaying as threads with hierarchy"),
}
_defaults = {
- 'subtype': 'plain',
+ 'content_subtype': 'plain',
'date': (lambda *a: fields.datetime.now()),
}
-class mail_message(osv.osv):
- '''Model holding messages: system notification (replacing res.log
- notifications), comments (for OpenSocial feature) and
+class mail_message(osv.Model):
+ """Model holding messages: system notification (replacing res.log
+ notifications), comments (for OpenChatter feature) and
RFC2822 email messages. This model also provides facilities to
parse, queue and send new email messages. Type of messages
- are differentiated using the 'type' column.
-
- The ``display_text`` field will have a slightly different
- presentation for real emails and for log messages.
- '''
+ are differentiated using the 'type' column. """
_name = 'mail.message'
_inherit = 'mail.message.common'
_description = 'Mail Message (email, comment, notification)'
_order = 'date desc'
- # XXX to review - how to determine action to use?
def open_document(self, cr, uid, ids, context=None):
+ """ Open the message related document. Note that only the document of
+ ids[0] will be opened.
+ TODO: how to determine the action to use ?
+ """
action_data = False
- if ids:
- msg = self.browse(cr, uid, ids[0], context=context)
- model = msg.model
- res_id = msg.res_id
-
- ir_act_window = self.pool.get('ir.actions.act_window')
- action_ids = ir_act_window.search(cr, uid, [('res_model', '=', model)])
- if action_ids:
- action_data = ir_act_window.read(cr, uid, action_ids[0], context=context)
- action_data.update({
- 'domain' : "[('id','=',%d)]"%(res_id),
+ if not ids:
+ return action_data
+ msg = self.browse(cr, uid, ids[0], context=context)
+ ir_act_window = self.pool.get('ir.actions.act_window')
+ action_ids = ir_act_window.search(cr, uid, [('res_model', '=', msg.model)], context=context)
+ if action_ids:
+ action_data = ir_act_window.read(cr, uid, action_ids[0], context=context)
+ action_data.update({
+ 'domain' : "[('id', '=', %d)]" % (msg.res_id),
'nodestroy': True,
'context': {}
})
return action_data
- # XXX to review - how to determine action to use?
def open_attachment(self, cr, uid, ids, context=None):
+ """ Open the message related attachments.
+ TODO: how to determine the action to use ?
+ """
action_data = False
+ if not ids:
+ return action_data
action_pool = self.pool.get('ir.actions.act_window')
- message = self.browse(cr, uid, ids, context=context)[0]
- att_ids = [x.id for x in message.attachment_ids]
- action_ids = action_pool.search(cr, uid, [('res_model', '=', 'ir.attachment')])
+ messages = self.browse(cr, uid, ids, context=context)
+ att_ids = [x.id for message in messages for x in message.attachment_ids]
+ action_ids = action_pool.search(cr, uid, [('res_model', '=', 'ir.attachment')], context=context)
if action_ids:
action_data = action_pool.read(cr, uid, action_ids[0], context=context)
action_data.update({
- 'domain': [('id','in',att_ids)],
+ 'domain': [('id', 'in', att_ids)],
'nodestroy': True
})
return action_data
-
- def _get_display_text(self, cr, uid, ids, name, arg, context=None):
- if context is None:
- context = {}
- tz = context.get('tz')
- result = {}
-
- # Read message as UID 1 to allow viewing author even if from different company
- for message in self.browse(cr, SUPERUSER_ID, ids):
- msg_txt = ''
- if message.email_from:
- msg_txt += _('%s wrote on %s: \n Subject: %s \n\t') % (message.email_from or '/', format_date_tz(message.date, tz), message.subject)
- if message.body_text:
- msg_txt += truncate_text(message.body_text)
- else:
- msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t'
- msg_txt += (message.subject or '')
- result[message.id] = msg_txt
- return result
_columns = {
'type': fields.selection([
('email', 'email'),
('comment', 'Comment'),
('notification', 'System notification'),
- ], 'Type', help="Message type: email for email message, notification for system message, comment for other messages such as user replies"),
- 'partner_id': fields.many2one('res.partner', 'Related partner'),
+ ], 'Type',
+ help="Message type: email for email message, notification for system "\
+ "message, comment for other messages such as user replies"),
+ 'partner_id': fields.many2one('res.partner', 'Related partner',
+ help="Deprecated field. Use partner_ids instead."),
+ 'partner_ids': fields.many2many('res.partner',
+ 'mail_message_destination_partner_rel',
+ 'message_id', 'partner_id', 'Destination partners',
+ help="When sending emails through the social network composition wizard"\
+ "you may choose to send a copy of the mail to partners."),
'user_id': fields.many2one('res.users', 'Related User', readonly=1),
'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments'),
- 'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1),
'state': fields.selection([
('outgoing', 'Outgoing'),
@@ -231,8 +222,14 @@ class mail_message(osv.osv):
('exception', 'Delivery Failed'),
('cancel', 'Cancelled'),
], 'Status', readonly=True),
- 'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"),
- 'original': fields.binary('Original', help="Original version of the message, as it was sent on the network", readonly=1),
+ 'auto_delete': fields.boolean('Auto Delete',
+ help="Permanently delete this email after sending it, to save space"),
+ 'original': fields.binary('Original', readonly=1,
+ help="Original version of the message, as it was sent on the network"),
+ 'parent_id': fields.many2one('mail.message', 'Parent Message',
+ select=True, ondelete='set null',
+ help="Parent message, used for displaying as threads with hierarchy"),
+ 'child_ids': fields.one2many('mail.message', 'parent_id', 'Child Messages'),
}
_defaults = {
@@ -249,72 +246,124 @@ class mail_message(osv.osv):
if not cr.fetchone():
cr.execute("""CREATE INDEX mail_message_model_res_id_idx ON mail_message (model, res_id)""")
+ def check(self, cr, uid, ids, mode, context=None, values=None):
+ """Restricts the access to a mail.message, according to referred model
+ """
+ if not ids:
+ return
+ res_ids = {}
+ if isinstance(ids, (int, long)):
+ ids = [ids]
+ cr.execute('SELECT DISTINCT model, res_id FROM mail_message WHERE id = ANY (%s)', (ids,))
+ for rmod, rid in cr.fetchall():
+ if not (rmod and rid):
+ continue
+ res_ids.setdefault(rmod,set()).add(rid)
+ if values:
+ if 'res_model' in values and 'res_id' in values:
+ res_ids.setdefault(values['res_model'],set()).add(values['res_id'])
+
+ ima_obj = self.pool.get('ir.model.access')
+ for model, mids in res_ids.items():
+ # ignore mail messages that are not attached to a resource anymore when checking access rights
+ # (resource was deleted but message was not)
+ mids = self.pool.get(model).exists(cr, uid, mids)
+ ima_obj.check(cr, uid, model, mode)
+ self.pool.get(model).check_access_rule(cr, uid, mids, mode, context=context)
+
+ def create(self, cr, uid, values, context=None):
+ self.check(cr, uid, [], mode='create', context=context, values=values)
+ return super(mail_message, self).create(cr, uid, values, context)
+
+ def read(self, cr, uid, ids, fields_to_read=None, context=None, load='_classic_read'):
+ self.check(cr, uid, ids, 'read', context=context)
+ return super(mail_message, self).read(cr, uid, ids, fields_to_read, context, load)
+
def copy(self, cr, uid, id, default=None, context=None):
"""Overridden to avoid duplicating fields that are unique to each email"""
if default is None:
default = {}
- default.update(message_id=False,original=False,headers=False)
+ self.check(cr, uid, [id], 'read', context=context)
+ default.update(message_id=False, original=False, headers=False)
return super(mail_message,self).copy(cr, uid, id, default=default, context=context)
+
+ def write(self, cr, uid, ids, vals, context=None):
+ self.check(cr, uid, ids, 'write', context=context, values=vals)
+ return super(mail_message, self).write(cr, uid, ids, vals, context)
- def schedule_with_attach(self, cr, uid, email_from, email_to, subject, body, model=False, email_cc=None,
- email_bcc=None, reply_to=False, attachments=None, message_id=False, references=False,
- res_id=False, subtype='plain', headers=None, mail_server_id=False, auto_delete=False,
- context=None):
- """Schedule sending a new email message, to be sent the next time the mail scheduler runs, or
- the next time :meth:`process_email_queue` is called explicitly.
+ def unlink(self, cr, uid, ids, context=None):
+ self.check(cr, uid, ids, 'unlink', context=context)
+ return super(mail_message, self).unlink(cr, uid, ids, context)
- :param string email_from: sender email address
- :param list email_to: list of recipient addresses (to be joined with commas)
- :param string subject: email subject (no pre-encoding/quoting necessary)
- :param string body: email body, according to the ``subtype`` (by default, plaintext).
- If html subtype is used, the message will be automatically converted
- to plaintext and wrapped in multipart/alternative.
- :param list email_cc: optional list of string values for CC header (to be joined with commas)
- :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
- :param string model: optional model name of the document this mail is related to (this will also
- be used to generate a tracking id, used to match any response related to the
- same document)
- :param int res_id: optional resource identifier this mail is related to (this will also
- be used to generate a tracking id, used to match any response related to the
- same document)
- :param string reply_to: optional value of Reply-To header
- :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
- must match the format of the ``body`` parameter. Default is 'plain',
- making the content part of the mail "text/plain".
- :param dict attachments: map of filename to filecontents, where filecontents is a string
- containing the bytes of the attachment
- :param dict headers: optional map of headers to set on the outgoing mail (may override the
- other headers, including Subject, Reply-To, Message-Id, etc.)
- :param int mail_server_id: optional id of the preferred outgoing mail server for this mail
- :param bool auto_delete: optional flag to turn on auto-deletion of the message after it has been
- successfully sent (default to False)
+ def schedule_with_attach(self, cr, uid, email_from, email_to, subject, body, model=False, type='email',
+ email_cc=None, email_bcc=None, reply_to=False, partner_ids=None, attachments=None,
+ message_id=False, references=False, res_id=False, content_subtype='plain',
+ headers=None, mail_server_id=False, auto_delete=False, context=None):
+ """ Schedule sending a new email message, to be sent the next time the
+ mail scheduler runs, or the next time :meth:`process_email_queue` is
+ called explicitly.
+ :param string email_from: sender email address
+ :param list email_to: list of recipient addresses (to be joined with commas)
+ :param string subject: email subject (no pre-encoding/quoting necessary)
+ :param string body: email body, according to the ``content_subtype``
+ (by default, plaintext). If html content_subtype is used, the
+ message will be automatically converted to plaintext and wrapped
+ in multipart/alternative.
+ :param list email_cc: optional list of string values for CC header
+ (to be joined with commas)
+ :param list email_bcc: optional list of string values for BCC header
+ (to be joined with commas)
+ :param string model: optional model name of the document this mail
+ is related to (this will also be used to generate a tracking id,
+ used to match any response related to the same document)
+ :param int res_id: optional resource identifier this mail is related
+ to (this will also be used to generate a tracking id, used to
+ match any response related to the same document)
+ :param string reply_to: optional value of Reply-To header
+ :param partner_ids: destination partner_ids
+ :param string content_subtype: optional mime content_subtype for
+ the text body (usually 'plain' or 'html'), must match the format
+ of the ``body`` parameter. Default is 'plain', making the content
+ part of the mail "text/plain".
+ :param dict attachments: map of filename to filecontents, where
+ filecontents is a string containing the bytes of the attachment
+ :param dict headers: optional map of headers to set on the outgoing
+ mail (may override the other headers, including Subject,
+ Reply-To, Message-Id, etc.)
+ :param int mail_server_id: optional id of the preferred outgoing
+ mail server for this mail
+ :param bool auto_delete: optional flag to turn on auto-deletion of
+ the message after it has been successfully sent (default to False)
"""
if context is None:
context = {}
if attachments is None:
attachments = {}
+ if partner_ids is None:
+ partner_ids = []
attachment_obj = self.pool.get('ir.attachment')
for param in (email_to, email_cc, email_bcc):
if param and not isinstance(param, list):
param = [param]
msg_vals = {
'subject': subject,
- 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
+ 'date': fields.datetime.now(),
'user_id': uid,
'model': model,
'res_id': res_id,
- 'type': 'email',
- 'body_text': body if subtype != 'html' else False,
- 'body_html': body if subtype == 'html' else False,
+ 'type': type,
+ 'body_text': body if content_subtype != 'html' else False,
+ 'body_html': body if content_subtype == 'html' else False,
'email_from': email_from,
'email_to': email_to and ','.join(email_to) or '',
'email_cc': email_cc and ','.join(email_cc) or '',
'email_bcc': email_bcc and ','.join(email_bcc) or '',
+ 'partner_ids': partner_ids,
'reply_to': reply_to,
'message_id': message_id,
'references': references,
- 'subtype': subtype,
+ 'content_subtype': content_subtype,
'headers': headers, # serialize the dict on the fly
'mail_server_id': mail_server_id,
'state': 'outgoing',
@@ -338,7 +387,10 @@ class mail_message(osv.osv):
return email_msg_id
def mark_outgoing(self, cr, uid, ids, context=None):
- return self.write(cr, uid, ids, {'state':'outgoing'}, context)
+ return self.write(cr, uid, ids, {'state':'outgoing'}, context=context)
+
+ def cancel(self, cr, uid, ids, context=None):
+ return self.write(cr, uid, ids, {'state':'cancel'}, context=context)
def process_email_queue(self, cr, uid, ids=None, context=None):
"""Send immediately queued messages, committing after each
@@ -357,7 +409,7 @@ class mail_message(osv.osv):
if context is None:
context = {}
if not ids:
- filters = [('state', '=', 'outgoing')]
+ filters = ['&', ('state', '=', 'outgoing'), ('type', '=', 'email')]
if 'filters' in context:
filters.extend(context['filters'])
ids = self.search(cr, uid, filters, context=context)
@@ -371,7 +423,7 @@ class mail_message(osv.osv):
_logger.exception("Failed processing mail queue")
return res
- def parse_message(self, message, save_original=False):
+ def parse_message(self, message, save_original=False, context=None):
"""Parses a string or email.message.Message representing an
RFC-2822 email, and returns a generic dict holding the
message details.
@@ -394,7 +446,7 @@ class mail_message(osv.osv):
'headers' : { 'X-Mailer': mailer,
#.. all X- headers...
},
- 'subtype': msg_mime_subtype,
+ 'content_subtype': msg_mime_subtype,
'body_text': plaintext_body
'body_html': html_body,
'attachments': [('file1', 'bytes'),
@@ -428,49 +480,52 @@ class mail_message(osv.osv):
msg_txt['message-id'] = message_id
_logger.info('Parsing Message without message-id, generating a random one: %s', message_id)
- fields = msg_txt.keys()
+ msg_fields = msg_txt.keys()
msg['id'] = message_id
msg['message-id'] = message_id
- if 'Subject' in fields:
+ if 'Subject' in msg_fields:
msg['subject'] = decode(msg_txt.get('Subject'))
- if 'Content-Type' in fields:
+ if 'Content-Type' in msg_fields:
msg['content-type'] = msg_txt.get('Content-Type')
- if 'From' in fields:
+ if 'From' in msg_fields:
msg['from'] = decode(msg_txt.get('From') or msg_txt.get_unixfrom())
- if 'To' in fields:
+ if 'To' in msg_fields:
msg['to'] = decode(msg_txt.get('To'))
- if 'Delivered-To' in fields:
+ if 'Delivered-To' in msg_fields:
msg['to'] = decode(msg_txt.get('Delivered-To'))
- if 'CC' in fields:
+ if 'CC' in msg_fields:
msg['cc'] = decode(msg_txt.get('CC'))
- if 'Cc' in fields:
+ if 'Cc' in msg_fields:
msg['cc'] = decode(msg_txt.get('Cc'))
- if 'Reply-To' in fields:
+ if 'Reply-To' in msg_fields:
msg['reply'] = decode(msg_txt.get('Reply-To'))
- if 'Date' in fields:
+ if 'Date' in msg_fields:
date_hdr = decode(msg_txt.get('Date'))
- msg['date'] = dateutil.parser.parse(date_hdr).strftime("%Y-%m-%d %H:%M:%S")
+ # convert from email timezone to server timezone
+ date_server_datetime = dateutil.parser.parse(date_hdr).astimezone(pytz.timezone(tools.get_server_timezone()))
+ date_server_datetime_str = date_server_datetime.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
+ msg['date'] = date_server_datetime_str
- if 'Content-Transfer-Encoding' in fields:
+ if 'Content-Transfer-Encoding' in msg_fields:
msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
- if 'References' in fields:
+ if 'References' in msg_fields:
msg['references'] = msg_txt.get('References')
- if 'In-Reply-To' in fields:
+ if 'In-Reply-To' in msg_fields:
msg['in-reply-to'] = msg_txt.get('In-Reply-To')
msg['headers'] = {}
- msg['subtype'] = 'plain'
+ msg['content_subtype'] = 'plain'
for item in msg_txt.items():
if item[0].startswith('X-'):
msg['headers'].update({item[0]: item[1]})
@@ -479,7 +534,7 @@ class mail_message(osv.osv):
body = msg_txt.get_payload(decode=True)
if 'text/html' in msg.get('content-type', ''):
msg['body_html'] = body
- msg['subtype'] = 'html'
+ msg['content_subtype'] = 'html'
if body:
body = tools.html2plaintext(body)
msg['body_text'] = tools.ustr(body, encoding)
@@ -488,9 +543,9 @@ class mail_message(osv.osv):
if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
body = ""
if 'multipart/alternative' in msg.get('content-type', ''):
- msg['subtype'] = 'alternative'
+ msg['content_subtype'] = 'alternative'
else:
- msg['subtype'] = 'mixed'
+ msg['content_subtype'] = 'mixed'
for part in msg_txt.walk():
if part.get_content_maintype() == 'multipart':
continue
@@ -504,7 +559,7 @@ class mail_message(osv.osv):
content = tools.ustr(content, encoding)
if part.get_content_subtype() == 'html':
msg['body_html'] = content
- msg['subtype'] = 'html' # html version prevails
+ msg['content_subtype'] = 'html' # html version prevails
body = tools.ustr(tools.html2plaintext(content))
body = body.replace('
', '')
elif part.get_content_subtype() == 'plain':
@@ -521,7 +576,7 @@ class mail_message(osv.osv):
# for backwards compatibility:
msg['body'] = msg['body_text']
- msg['sub_type'] = msg['subtype'] or 'plain'
+ msg['sub_type'] = msg['content_subtype'] or 'plain'
return msg
def _postprocess_sent_message(self, cr, uid, message, context=None):
@@ -535,10 +590,9 @@ class mail_message(osv.osv):
"""
if message.auto_delete:
self.pool.get('ir.attachment').unlink(cr, uid,
- [x.id for x in message.attachment_ids \
- if x.res_model == self._name and \
- x.res_id == message.id],
- context=context)
+ [x.id for x in message.attachment_ids
+ if x.res_model == self._name and x.res_id == message.id],
+ context=context)
message.unlink()
return True
@@ -557,8 +611,6 @@ class mail_message(osv.osv):
transactions (default: False)
:return: True
"""
- if context is None:
- context = {}
ir_mail_server = self.pool.get('ir.mail_server')
self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
for message in self.browse(cr, uid, ids, context=context):
@@ -567,37 +619,45 @@ class mail_message(osv.osv):
for attach in message.attachment_ids:
attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
- body = message.body_html if message.subtype == 'html' else message.body_text
+ body = message.body_html if message.content_subtype == 'html' else message.body_text
body_alternative = None
- subtype_alternative = None
- if message.subtype == 'html' and message.body_text:
+ content_subtype_alternative = None
+ if message.content_subtype == 'html' and message.body_text:
# we have a plain text alternative prepared, pass it to
# build_message instead of letting it build one
body_alternative = message.body_text
- subtype_alternative = 'plain'
+ content_subtype_alternative = 'plain'
+ # handle destination_partners
+ partner_ids_email_to = ''
+ for partner in message.partner_ids:
+ partner_ids_email_to += '%s ' % (partner.email or '')
+ message_email_to = '%s %s' % (partner_ids_email_to, message.email_to or '')
+
+ # build an RFC2822 email.message.Message object and send it
+ # without queuing
msg = ir_mail_server.build_email(
email_from=message.email_from,
- email_to=to_email(message.email_to),
+ email_to=mail_tools_to_email(message_email_to),
subject=message.subject,
body=body,
body_alternative=body_alternative,
- email_cc=to_email(message.email_cc),
- email_bcc=to_email(message.email_bcc),
+ email_cc=mail_tools_to_email(message.email_cc),
+ email_bcc=mail_tools_to_email(message.email_bcc),
reply_to=message.reply_to,
attachments=attachments, message_id=message.message_id,
references = message.references,
object_id=message.res_id and ('%s-%s' % (message.res_id,message.model)),
- subtype=message.subtype,
- subtype_alternative=subtype_alternative,
+ subtype=message.content_subtype,
+ subtype_alternative=content_subtype_alternative,
headers=message.headers and ast.literal_eval(message.headers))
res = ir_mail_server.send_email(cr, uid, msg,
mail_server_id=message.mail_server_id.id,
context=context)
if res:
- message.write({'state':'sent', 'message_id': res})
+ message.write({'state':'sent', 'message_id': res, 'email_to': message_email_to})
else:
- message.write({'state':'exception'})
+ message.write({'state':'exception', 'email_to': message_email_to})
message.refresh()
if message.state == 'sent':
self._postprocess_sent_message(cr, uid, message, context=context)
@@ -609,8 +669,6 @@ class mail_message(osv.osv):
cr.commit()
return True
- def cancel(self, cr, uid, ids, context=None):
- self.write(cr, uid, ids, {'state':'cancel'}, context=context)
- return True
+
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/mail/mail_message_view.xml b/addons/mail/mail_message_view.xml
index 34ba6db1477..634b5317d27 100644
--- a/addons/mail/mail_message_view.xml
+++ b/addons/mail/mail_message_view.xml
@@ -30,17 +30,26 @@
+
-
+
-
+
+
+
+
+
+
+
+
+
@@ -73,7 +82,30 @@
-
+
+
+
+
+
+
+
+
@@ -86,55 +118,60 @@
@@ -236,13 +273,13 @@
News Feed
- mail.all_feeds
+ mail.wallMy Feeds
- mail.all_feeds
+ mail.wall
diff --git a/addons/mail/mail_subscription_view.xml b/addons/mail/mail_subscription_view.xml
index 7dbaea098dc..c3d79d48308 100644
--- a/addons/mail/mail_subscription_view.xml
+++ b/addons/mail/mail_subscription_view.xml
@@ -52,11 +52,13 @@
tree,form
-
-
+
+ -->
-
-
+
+
diff --git a/addons/mail/mail_thread.py b/addons/mail/mail_thread.py
index cdcaf4f464d..d036150b21c 100644
--- a/addons/mail/mail_thread.py
+++ b/addons/mail/mail_thread.py
@@ -65,7 +65,7 @@ class mail_thread(osv.Model):
def _get_message_ids(self, cr, uid, ids, name, args, context=None):
res = {}
for id in ids:
- message_ids = self.message_load_ids(cr, uid, [id], context=context)
+ message_ids = self.message_search(cr, uid, [id], context=context)
subscriber_ids = self.message_get_subscribers(cr, uid, [id], context=context)
res[id] = {
'message_ids': message_ids,
@@ -130,7 +130,7 @@ class mail_thread(osv.Model):
# delete subscriptions
subscr_to_del_ids = subscr_obj.search(cr, uid, [('res_model', '=', self._name), ('res_id', 'in', ids)], context=context)
subscr_obj.unlink(cr, uid, subscr_to_del_ids, context=context)
- # delete notifications
+ # delete messages and notifications
msg_to_del_ids = msg_obj.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)], context=context)
msg_obj.unlink(cr, uid, msg_to_del_ids, context=context)
@@ -150,39 +150,13 @@ class mail_thread(osv.Model):
context = {}
message_obj = self.pool.get('mail.message')
- subscription_obj = self.pool.get('mail.subscription')
notification_obj = self.pool.get('mail.notification')
- res_users_obj = self.pool.get('res.users')
- body = vals.get('body_html', '') if vals.get('subtype', 'plain') == 'html' else vals.get('body_text', '')
-
+ body = vals.get('body_html', '') if vals.get('content_subtype') == 'html' else vals.get('body_text', '')
+
# automatically subscribe the writer of the message
if vals['user_id']:
self.message_subscribe(cr, uid, [thread_id], [vals['user_id']], context=context)
-
- # get users that will get a notification pushed
- user_to_push_ids = self.message_create_get_notification_user_ids(cr, uid, [thread_id], vals, context=context)
- user_to_push_from_parse_ids = self.message_parse_users(cr, uid, [thread_id], body, context=context)
-
- # set email_from and email_to for comments and notifications
- if vals.get('type', False) and vals['type'] == 'comment' or vals['type'] == 'notification':
- current_user = res_users_obj.browse(cr, uid, [uid], context=context)[0]
- if not vals.get('email_from', False):
- vals['email_from'] = current_user.user_email
- if not vals.get('email_to', False):
- email_to = ''
- for user in res_users_obj.browse(cr, uid, user_to_push_ids, context=context):
- if not user.notification_email_pref == 'all' and \
- not (user.notification_email_pref == 'comments' and vals['type'] == 'comment') and \
- not (user.notification_email_pref == 'to_me' and user.id in user_to_push_from_parse_ids):
- continue
- if not user.user_email:
- continue
- email_to = '%s, %s' % (email_to, user.user_email)
- email_to = email_to.lstrip(', ')
- if email_to:
- vals['email_to'] = email_to
- vals['state'] = 'outgoing'
-
+
# create message
msg_id = message_obj.create(cr, uid, vals, context=context)
@@ -191,43 +165,50 @@ class mail_thread(osv.Model):
# special: if install mode, do not push demo data
if context.get('install_mode', False):
- return True
-
- # push to users
+ return msg_id
+
+ # get users that will get a notification pushed
+ user_to_push_ids = self.message_get_user_ids_to_notify(cr, uid, [thread_id], vals, context=context)
for id in user_to_push_ids:
notification_obj.create(cr, uid, {'user_id': id, 'message_id': msg_id}, context=context)
-
+
+ # create the email to send
+ email_id = self.message_create_notify_by_email(cr, uid, vals, user_to_push_ids, context=context)
+
return msg_id
-
- def message_create_get_notification_user_ids(self, cr, uid, thread_ids, new_msg_vals, context=None):
- if context is None:
- context = {}
-
- notif_user_ids = []
- body = new_msg_vals.get('body_html', '') if new_msg_vals.get('subtype', 'plain') == 'html' else new_msg_vals.get('body_text', '')
- for thread_id in thread_ids:
- # add subscribers
- notif_user_ids += self.message_get_subscribers(cr, uid, [thread_id], context=context)
- # add users requested via parsing message (@login)
- notif_user_ids += self.message_parse_users(cr, uid, [thread_id], body, context=context)
- # add users requested to perform an action (need_action mechanism)
- if hasattr(self, 'get_needaction_user_ids'):
- notif_user_ids += self.get_needaction_user_ids(cr, uid, [thread_id], context=context)[thread_id]
- # add users notified of the parent messages (because: if parent message contains @login, login must receive the replies)
- if new_msg_vals.get('parent_id'):
- notif_obj = self.pool.get('mail.notification')
- parent_notif_ids = notif_obj.search(cr, uid, [('message_id', '=', new_msg_vals.get('parent_id'))], context=context)
- parent_notifs = notif_obj.read(cr, uid, parent_notif_ids, context=context)
- notif_user_ids += [parent_notif['user_id'][0] for parent_notif in parent_notifs]
+
+ def message_get_user_ids_to_notify(self, cr, uid, thread_ids, new_msg_vals, context=None):
+ subscription_obj = self.pool.get('mail.subscription')
+ # get body
+ body = new_msg_vals.get('body_html', '') if new_msg_vals.get('content_subtype') == 'html' else new_msg_vals.get('body_text', '')
+
+ # get subscribers
+ notif_user_ids = self.message_get_subscribers(cr, uid, thread_ids, context=context)
+
+ # add users requested via parsing message (@login)
+ notif_user_ids += self.message_parse_users(cr, uid, body, context=context)
+
+ # add users requested to perform an action (need_action mechanism)
+ if hasattr(self, 'get_needaction_user_ids'):
+ user_ids_dict = self.get_needaction_user_ids(cr, uid, thread_ids, context=context)
+ for id, user_ids in user_ids_dict.iteritems():
+ notif_user_ids += user_ids
+
+ # add users notified of the parent messages (because: if parent message contains @login, login must receive the replies)
+ if new_msg_vals.get('parent_id'):
+ notif_obj = self.pool.get('mail.notification')
+ parent_notif_ids = notif_obj.search(cr, uid, [('message_id', '=', new_msg_vals.get('parent_id'))], context=context)
+ parent_notifs = notif_obj.read(cr, uid, parent_notif_ids, context=context)
+ notif_user_ids += [parent_notif['user_id'][0] for parent_notif in parent_notifs]
# remove duplicate entries
notif_user_ids = list(set(notif_user_ids))
return notif_user_ids
- def message_parse_users(self, cr, uid, ids, string, context=None):
+ def message_parse_users(self, cr, uid, string, context=None):
"""Parse message content
- if find @login -(^|\s)@((\w|@|\.)*)-: returns the related ids
- this supports login that are emails (such as @admin@lapin.net)
+ this supports login that are emails (such as @raoul@grobedon.net)
"""
regex = re.compile('(^|\s)@((\w|@|\.)*)')
login_lst = [item[1] for item in regex.findall(string)]
@@ -248,46 +229,61 @@ class mail_thread(osv.Model):
return ret_dict
def message_append(self, cr, uid, threads, subject, body_text=None, body_html=None,
- parent_id=False, type='email', subtype='plain', state='received',
- email_to=False, email_from=False, email_cc=None, email_bcc=None,
- reply_to=None, email_date=None, message_id=False, references=None,
- attachments=None, headers=None, original=None, context=None):
- """Creates a new mail.message attached to the current mail.thread,
- containing all the details passed as parameters. All attachments
- will be attached to the thread record as well as to the actual
- message.
- If ``email_from`` is not set or ``type`` not set as 'email',
- a note message is created, without the usual envelope
- attributes (sender, recipients, etc.).
- The creation of the message is done by calling ``message_create``
- method, that will manage automatic pushing of notifications.
+ type='email', email_date=None, parent_id=False,
+ content_subtype='plain', state=None,
+ partner_ids=None, email_from=False, email_to=False,
+ email_cc=None, email_bcc=None, reply_to=None,
+ headers=None, message_id=False, references=None,
+ attachments=None, original=None, context=None):
+ """ Creates a new mail.message through message_create. The new message
+ is attached to the current mail.thread, containing all the details
+ passed as parameters. All attachments will be attached to the
+ thread record as well as to the actual message.
+
+ This method calls message_create that will handle management of
+ subscription and notifications, and effectively create the message.
+
+ If ``email_from`` is not set or ``type`` not set as 'email',
+ a note message is created (comment or system notification),
+ without the usual envelope attributes (sender, recipients, etc.).
- :param threads: list of thread ids, or list of browse_records representing
- threads to which a new message should be attached
- :param subject: subject of the message, or description of the event if this
- is an *event log* entry.
- :param body_text: plaintext contents of the mail or log message
- :param body_html: html contents of the mail or log message
- :param parent_id: id of the parent message (threaded messaging model)
- :param type: optional type of message: 'email', 'comment', 'notification'
- :param subtype: optional subtype of message: 'plain' or 'html', corresponding to the main
- body contents (body_text or body_html).
- :param state: optional state of message; 'received' by default
- :param email_to: Email-To / Recipient address
- :param email_from: Email From / Sender address if any
- :param email_cc: Comma-Separated list of Carbon Copy Emails To addresse if any
- :param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To addresses if any
- :param reply_to: reply_to header
- :param email_date: email date string if different from now, in server timezone
- :param message_id: optional email identifier
- :param references: optional email references
- :param headers: mail headers to store
- :param dict attachments: map of attachment filenames to binary contents, if any.
- :param str original: optional full source of the RFC2822 email, for reference
- :param dict context: if a ``thread_model`` value is present
- in the context, its value will be used
- to determine the model of the thread to
- update (instead of the current model).
+ :param threads: list of thread ids, or list of browse_records
+ representing threads to which a new message should be attached
+ :param subject: subject of the message, or description of the event;
+ this is totally optional as subjects are not important except
+ for specific messages (blog post, job offers) or for emails
+ :param body_text: plaintext contents of the mail or log message
+ :param body_html: html contents of the mail or log message
+ :param type: type of message: 'email', 'comment', 'notification';
+ email by default
+ :param email_date: email date string if different from now, in
+ server timezone
+ :param parent_id: id of the parent message (threaded messaging model)
+ :param content_subtype: optional content_subtype of message: 'plain'
+ or 'html', corresponding to the main body contents (body_text or
+ body_html).
+ :param state: state of message
+ :param partner_ids: destination partners of the message, in addition
+ to the now fully optional email_to; this method is supposed to
+ received a list of ids is not None. The specific many2many
+ instruction will be generated by this method.
+ :param email_from: Email From / Sender address if any
+ :param email_to: Email-To / Recipient address
+ :param email_cc: Comma-Separated list of Carbon Copy Emails To
+ addresses if any
+ :param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To
+ addresses if any
+ :param reply_to: reply_to header
+ :param headers: mail headers to store
+ :param message_id: optional email identifier
+ :param references: optional email references
+ :param dict attachments: map of attachment filenames to binary
+ contents, if any.
+ :param str original: optional full source of the RFC2822 email, for
+ reference
+ :param dict context: if a ``thread_model`` value is present in the
+ context, its value will be used to determine the model of the
+ thread to update (instead of the current model).
"""
if context is None:
context = {}
@@ -323,10 +319,15 @@ class mail_thread(osv.Model):
'res_id': thread.id,
}
to_attach.append(ir_attachment.create(cr, uid, data_attach, context=context))
-
+ # find related partner: partner_id column in thread object, or self is res.partner model
partner_id = ('partner_id' in thread._columns.keys()) and (thread.partner_id and thread.partner_id.id or False) or False
if not partner_id and thread._name == 'res.partner':
partner_id = thread.id
+ # destination partners
+ if partner_ids is None:
+ partner_ids = []
+ mail_partner_ids = [(6, 0, partner_ids)]
+
data = {
'subject': subject,
'body_text': body_text or (hasattr(thread, 'description') and thread.description or ''),
@@ -334,9 +335,10 @@ class mail_thread(osv.Model):
'parent_id': parent_id,
'date': email_date or fields.datetime.now(),
'type': type,
- 'subtype': subtype,
+ 'content_subtype': content_subtype,
'state': state,
'message_id': message_id,
+ 'partner_ids': mail_partner_ids,
'attachment_ids': [(6, 0, to_attach)],
'user_id': uid,
'model' : thread._name,
@@ -349,7 +351,6 @@ class mail_thread(osv.Model):
if isinstance(param, list):
param = ", ".join(param)
data.update({
- 'subject': subject or _('History'),
'email_to': email_to,
'email_from': email_from or \
(hasattr(thread, 'user_id') and thread.user_id and thread.user_id.user_email),
@@ -385,8 +386,9 @@ class mail_thread(osv.Model):
body_html= msg_dict.get('body_html'),
parent_id = msg_dict.get('parent_id', False),
type = msg_dict.get('type', 'email'),
- subtype = msg_dict.get('subtype', 'plain'),
- state = msg_dict.get('state', 'received'),
+ content_subtype = msg_dict.get('content_subtype'),
+ state = msg_dict.get('state'),
+ partner_ids = msg_dict.get('partner_ids'),
email_from = msg_dict.get('from', msg_dict.get('email_from')),
email_to = msg_dict.get('to', msg_dict.get('email_to')),
email_cc = msg_dict.get('cc', msg_dict.get('email_cc')),
@@ -401,59 +403,109 @@ class mail_thread(osv.Model):
original = msg_dict.get('original'),
context = context)
- def _message_add_ancestor_ids(self, cr, uid, ids, child_ids, root_ids, context=None):
- """ Given message child_ids
- Find their ancestors until root ids"""
- if context is None:
- context = {}
- msg_obj = self.pool.get('mail.message')
- tmp_msgs = msg_obj.read(cr, uid, child_ids, ['id', 'parent_id'], context=context)
- parent_ids = [msg['parent_id'][0] for msg in tmp_msgs if msg['parent_id'] and msg['parent_id'][0] not in root_ids and msg['parent_id'][0] not in child_ids]
+ #------------------------------------------------------
+ # Message loading
+ #------------------------------------------------------
+
+ def _message_search_ancestor_ids(self, cr, uid, ids, child_ids, ancestor_ids, context=None):
+ """ Given message child_ids ids, find their ancestors until ancestor_ids
+ using their parent_id relationship.
+
+ :param child_ids: the first nodes of the search
+ :param ancestor_ids: list of ancestors. When the search reach an
+ ancestor, it stops.
+ """
+ def _get_parent_ids(message_list, ancestor_ids, child_ids):
+ """ Tool function: return the list of parent_ids of messages
+ contained in message_list. Parents that are in ancestor_ids
+ or in child_ids are not returned. """
+ return [message['parent_id'][0] for message in message_list
+ if message['parent_id']
+ and message['parent_id'][0] not in ancestor_ids
+ and message['parent_id'][0] not in child_ids
+ ]
+
+ message_obj = self.pool.get('mail.message')
+ messages_temp = message_obj.read(cr, uid, child_ids, ['id', 'parent_id'], context=context)
+ parent_ids = _get_parent_ids(messages_temp, ancestor_ids, child_ids)
child_ids += parent_ids
cur_iter = 0; max_iter = 100; # avoid infinite loop
while (parent_ids and (cur_iter < max_iter)):
cur_iter += 1
- tmp_msgs = msg_obj.read(cr, uid, parent_ids, ['id', 'parent_id'], context=context)
- parent_ids = [msg['parent_id'][0] for msg in tmp_msgs if msg['parent_id'] and msg['parent_id'][0] not in root_ids and msg['parent_id'][0] not in child_ids]
+ messages_temp = message_obj.read(cr, uid, parent_ids, ['id', 'parent_id'], context=context)
+ parent_ids = _get_parent_ids(messages_temp, ancestor_ids, child_ids)
child_ids += parent_ids
if (cur_iter > max_iter):
- _logger.warning("Possible infinite loop in _message_add_ancestor_ids. Note that this algorithm is intended to check for cycle in message graph.")
+ _logger.warning("Possible infinite loop in _message_search_ancestor_ids. "\
+ "Note that this algorithm is intended to check for cycle in "\
+ "message graph, leading to a curious error. Have fun.")
return child_ids
- def message_load_ids(self, cr, uid, ids, limit=100, offset=0, domain=[], ascent=False, root_ids=[], context=None):
- """ OpenChatter feature: return thread messages ids. It searches in
- mail.messages where res_id = ids, (res_)model = current model.
- :param domain: domain to add to the search; especially child_of
- is interesting when dealing with threaded display
- :param ascent: performs an ascended search; will add to fetched msgs
- all their parents until root_ids
- :param root_ids: for ascent search
- :param root_ids: root_ids when performing an ascended search
+ def message_search_get_domain(self, cr, uid, ids, context=None):
+ """ OpenChatter feature: get the domain to search the messages related
+ to a document. mail.thread defines the default behavior as
+ being messages with model = self._name, id in ids.
+ This method should be overridden if a model has to implement a
+ particular behavior.
"""
- if context is None:
- context = {}
- msg_obj = self.pool.get('mail.message')
- msg_ids = msg_obj.search(cr, uid, ['&', ('res_id', 'in', ids), ('model', '=', self._name)] + domain,
- limit=limit, offset=offset, context=context)
- if (ascent): msg_ids = self._message_add_ancestor_ids(cr, uid, ids, msg_ids, root_ids, context=context)
- return msg_ids
+ return ['&', ('res_id', 'in', ids), ('model', '=', self._name)]
- def message_load(self, cr, uid, ids, limit=100, offset=0, domain=[], ascent=False, root_ids=[], context=None):
- """ OpenChatter feature: return thread messages
+ def message_search(self, cr, uid, ids, fetch_ancestors=False, ancestor_ids=None,
+ limit=100, offset=0, domain=None, count=False, context=None):
+ """ OpenChatter feature: return thread messages ids according to the
+ search domain given by ``message_search_get_domain``.
+
+ It is possible to add in the search the parent of messages by
+ setting the fetch_ancestors flag to True. In that case, using
+ the parent_id relationship, the method returns the id list according
+ to the search domain, but then calls ``_message_search_ancestor_ids``
+ that will add to the list the ancestors ids. The search is limited
+ to parent messages having an id in ancestor_ids or having
+ parent_id set to False.
+
+ If ``count==True``, the number of ids is returned instead of the
+ id list. The count is done by hand instead of passing it as an
+ argument to the search call because we might want to perform
+ a research including parent messages until some ancestor_ids.
+
+ :param fetch_ancestors: performs an ascended search; will add
+ to fetched msgs all their parents until
+ ancestor_ids
+ :param ancestor_ids: used when fetching ancestors
+ :param domain: domain to add to the search; especially child_of
+ is interesting when dealing with threaded display.
+ Note that the added domain is anded with the
+ default domain.
+ :param limit, offset, count, context: as usual
"""
- msg_ids = self.message_load_ids(cr, uid, ids, limit, offset, domain, ascent, root_ids, context=context)
- msgs = self.pool.get('mail.message').read(cr, uid, msg_ids, [], context=context)
-
- # Set as read
- self.message_check_and_set_read(cr, uid, ids, context=context)
-
+ search_domain = self.message_search_get_domain(cr, uid, ids, context=context)
+ if domain:
+ search_domain += domain
+ message_obj = self.pool.get('mail.message')
+ message_res = message_obj.search(cr, uid, search_domain, limit=limit, offset=offset, count=count, context=context)
+ if not count and fetch_ancestors:
+ message_res += self._message_search_ancestor_ids(cr, uid, ids, message_res, ancestor_ids, context=context)
+ return message_res
+
+ def message_read(self, cr, uid, ids, fetch_ancestors=False, ancestor_ids=None,
+ limit=100, offset=0, domain=None, context=None):
+ """ OpenChatter feature: read the messages related to some threads.
+ This method is used mainly the Chatter widget, to directly have
+ read result instead of searching then reading.
+
+ Please see message_search for more information about the parameters.
+ """
+ message_ids = self.message_search(cr, uid, ids, fetch_ancestors, ancestor_ids,
+ limit, offset, domain, context=context)
+ messages = self.pool.get('mail.message').read(cr, uid, message_ids, context=context)
+
""" Retrieve all attachments names """
+ map_id_to_name = dict((attachment_id, '') for message in messages for attachment_id in message['attachment_ids'])
map_id_to_name = {}
-
- for msg in msgs:
+ for msg in messages:
for attach_id in msg["attachment_ids"]:
map_id_to_name[attach_id] = '' # use empty string as a placeholder
-
+
ids = map_id_to_name.keys()
names = self.pool.get('ir.attachment').name_get(cr, uid, ids, context=context)
@@ -462,26 +514,34 @@ class mail_thread(osv.Model):
map_id_to_name[name[0]] = name[1]
# give corresponding ids and names to each message
- for msg in msgs:
+ for msg in messages:
msg["attachments"] = []
for attach_id in msg["attachment_ids"]:
msg["attachments"].append({'id': attach_id, 'name': map_id_to_name[attach_id]})
- """ Sort and return messages """
- msgs = sorted(msgs, key=lambda d: (-d['id']))
- return msgs
+ # Set the threads as read
+ self.message_check_and_set_read(cr, uid, ids, context=context)
+ # Sort and return the messages
+ messages = sorted(messages, key=lambda d: (-d['id']))
+ return messages
- def get_pushed_messages(self, cr, uid, ids, limit=100, offset=0, msg_search_domain=[], ascent=False, root_ids=[], context=None):
- """ OpenChatter: wall: get messages to display (=pushed notifications)
+ def message_get_pushed_messages(self, cr, uid, ids, fetch_ancestors=False, ancestor_ids=None,
+ limit=100, offset=0, msg_search_domain=[], context=None):
+ """ OpenChatter: wall: get the pushed notifications and used them
+ to fetch messages to display on the wall.
+
+ :param fetch_ancestors: performs an ascended search; will add
+ to fetched msgs all their parents until
+ ancestor_ids
+ :param ancestor_ids: used when fetching ancestors
:param domain: domain to add to the search; especially child_of
is interesting when dealing with threaded display
:param ascent: performs an ascended search; will add to fetched msgs
all their parents until root_ids
:param root_ids: for ascent search
- :return list of mail.messages sorted by date
+ :return: list of mail.messages sorted by date
"""
- if context is None: context = {}
notification_obj = self.pool.get('mail.notification')
msg_obj = self.pool.get('mail.message')
# update message search
@@ -496,7 +556,7 @@ class mail_thread(osv.Model):
msg_ids = [notification.message_id.id for notification in notifications]
# get messages
msg_ids = msg_obj.search(cr, uid, [('id', 'in', msg_ids)], context=context)
- if (ascent): msg_ids = self._message_add_ancestor_ids(cr, uid, ids, msg_ids, root_ids, context=context)
+ if (fetch_ancestors): msg_ids = self._message_search_ancestor_ids(cr, uid, ids, msg_ids, ancestor_ids, context=context)
msgs = msg_obj.read(cr, uid, msg_ids, context=context)
return msgs
@@ -524,9 +584,9 @@ class mail_thread(osv.Model):
record needs to be created. Ignored
if the thread record already exists.
:param bool save_original: whether to keep a copy of the original
- email source attached to the message after it is imported.
+ email source attached to the message after it is imported.
:param bool strip_attachments: whether to strip all attachments
- before processing the message, in order to save some space.
+ before processing the message, in order to save some space.
"""
# extract message bytes - we are forced to pass the message as binary because
# we don't know its encoding until we parse its headers and hence can't
@@ -540,7 +600,6 @@ class mail_thread(osv.Model):
context.update({'thread_model': model})
mail_message = self.pool.get('mail.message')
- res_id = False
# Parse Message
# Warning: message_from_string doesn't always work correctly on unicode,
@@ -548,8 +607,11 @@ class mail_thread(osv.Model):
if isinstance(message, unicode):
message = message.encode('utf-8')
msg_txt = email.message_from_string(message)
- msg = mail_message.parse_message(msg_txt, save_original=save_original)
+ msg = mail_message.parse_message(msg_txt, save_original=save_original, context=context)
+ # update state
+ msg['state'] = 'received'
+
if strip_attachments and 'attachments' in msg:
del msg['attachments']
@@ -587,6 +649,8 @@ class mail_thread(osv.Model):
res_id = create_record(msg)
# To forward the email to other followers
self.message_forward(cr, uid, model, [res_id], msg_txt, context=context)
+ # Set as Unread
+ model_pool.message_mark_as_unread(cr, uid, [res_id], context=context)
return res_id
def message_new(self, cr, uid, msg_dict, custom_values=None, context=None):
@@ -652,9 +716,9 @@ class mail_thread(osv.Model):
return self.message_append_dict(cr, uid, ids, msg_dict, context=context)
def message_thread_followers(self, cr, uid, ids, context=None):
- """Returns a list of email addresses of the people following
- this thread, including the sender of each mail, and the
- people who were in CC of the messages, if any.
+ """ Returns a list of email addresses of the people following
+ this thread, including the sender of each mail, and the
+ people who were in CC of the messages, if any.
"""
res = {}
if isinstance(ids, (str, int, long)):
@@ -748,45 +812,27 @@ class mail_thread(osv.Model):
# Note specific
#------------------------------------------------------
- def message_broadcast(self, cr, uid, ids, subject=None, body=None, parent_id=False, type='notification', subtype='html', context=None):
- if context is None:
- context = {}
- notification_obj = self.pool.get('mail.notification')
- # write message
- msg_ids = self.message_append_note(cr, uid, ids, subject=subject, body=body, parent_id=parent_id, type=type, subtype=subtype, context=context)
- # escape if in install mode or note writing was not successfull
- if 'install_mode' in context:
- return True
- if not isinstance(msg_ids, (list)):
- return True
- # get already existing notigications
- notification_ids = notification_obj.search(cr, uid, [('message_id', 'in', msg_ids)], context=context)
- already_pushed_user_ids = map(itemgetter('user_id'), notification_obj.read(cr, uid, notification_ids, context=context))
- # get base.group_user group
- res = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_user') or False
- group_id = res and res[1] or False
- if not group_id: return True
- group = self.pool.get('res.groups').browse(cr, uid, [group_id], context=context)[0]
- for user in group.users:
- if user.id in already_pushed_user_ids: continue
- for msg_id in msg_ids:
- notification_obj.create(cr, uid, {'user_id': user.id, 'message_id': msg_id}, context=context)
- return True
-
def log(self, cr, uid, id, message, secondary=False, context=None):
- _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.")
+ _logger.warning("log() is deprecated. As this module inherit from \
+ mail.thread, the message will be managed by this \
+ module instead of by the res.log mechanism. Please \
+ use the mail.thread OpenChatter API instead of the \
+ now deprecated res.log.")
self.message_append_note(cr, uid, [id], 'res.log', message, context=context)
- def message_append_note(self, cr, uid, ids, subject=None, body=None, parent_id=False, type='notification', subtype='html', context=None):
- if type in ['notification', 'reply']:
+ def message_append_note(self, cr, uid, ids, subject=None, body=None, parent_id=False,
+ type='notification', content_subtype='html', context=None):
+ if type in ['notification', 'comment']:
subject = None
- if subtype == 'html':
+ if content_subtype == 'html':
body_html = body
body_text = body
else:
body_html = body
body_text = body
- return self.message_append(cr, uid, ids, subject, body_html=body_html, body_text=body_text, parent_id=parent_id, type=type, subtype=subtype, context=context)
+ return self.message_append(cr, uid, ids, subject, body_html, body_text,
+ type, parent_id=parent_id,
+ content_subtype=content_subtype, context=context)
#------------------------------------------------------
# Subscription mechanism
@@ -796,9 +842,9 @@ class mail_thread(osv.Model):
""" Returns the current document followers. Basically this method
checks in mail.subscription for entries with matching res_model,
res_id.
-
- :param get_ids: if set to True, return the ids of users; if set
- to False, returns the result of a read in res.users
+ This method can be overriden to add implicit subscribers, such
+ as project managers, by adding their user_id to the list of
+ ids returned by this method.
"""
subscr_obj = self.pool.get('mail.subscription')
subscr_ids = subscr_obj.search(cr, uid, ['&', ('res_model', '=', self._name), ('res_id', 'in', ids)], context=context)
@@ -849,19 +895,97 @@ class mail_thread(osv.Model):
# Trying to unsubscribe somebody not in subscribers: returns False
# if special management is needed; allows to know that an automatically
# subscribed user tries to unsubscribe and allows to warn him
- mail_thread_model = self.pool.get('mail.thread')
- if not user_ids and not uid in mail_thread_model.message_get_subscribers(cr, uid, ids, context=context):
- return False
- subscription_obj = self.pool.get('mail.subscription')
to_unsubscribe_uids = [uid] if user_ids is None else user_ids
+ subscription_obj = self.pool.get('mail.subscription')
to_delete_sub_ids = subscription_obj.search(cr, uid,
['&', '&', ('res_model', '=', self._name), ('res_id', 'in', ids), ('user_id', 'in', to_unsubscribe_uids)], context=context)
+ if not to_delete_sub_ids:
+ return False
return subscription_obj.unlink(cr, uid, to_delete_sub_ids, context=context)
#------------------------------------------------------
# Notification API
#------------------------------------------------------
+ def message_create_notify_by_email(self, cr, uid, new_msg_values, user_to_notify_ids, context=None):
+ """ When creating a new message and pushing notifications, emails
+ must be send if users have chosen to receive notifications
+ by email via the notification_email_pref field.
+
+ ``notification_email_pref`` can have 3 values :
+ - all: receive all notification by email (for example for shared
+ users)
+ - to_me: messages send directly to me (@login, messages on res.users)
+ - never: never receive notifications
+ Note that an user should never receive notifications for messages
+ he has created.
+
+ :param new_msg_values: dictionary of message values, those that
+ are given to the create method
+ :param user_to_notify_ids: list of user_ids, user that will
+ receive a notification on their Wall
+ """
+ message_obj = self.pool.get('mail.message')
+ res_users_obj = self.pool.get('res.users')
+ body = new_msg_values.get('body_html', '') if new_msg_values.get('content_subtype') == 'html' else new_msg_values.get('body_text', '')
+
+ # remove message writer
+ if user_to_notify_ids.count(new_msg_values.get('user_id')) > 0:
+ user_to_notify_ids.remove(new_msg_values.get('user_id'))
+
+ # get user_ids directly asked
+ user_to_push_from_parse_ids = self.message_parse_users(cr, uid, body, context=context)
+
+ # try to find an email_to
+ email_to = ''
+ for user in res_users_obj.browse(cr, uid, user_to_notify_ids, context=context):
+ if not user.notification_email_pref == 'all' and \
+ not (user.notification_email_pref == 'to_me' and user.id in user_to_push_from_parse_ids):
+ continue
+ if not user.user_email:
+ continue
+ email_to = '%s, %s' % (email_to, user.user_email)
+ email_to = email_to.lstrip(', ')
+
+ # did not find any email address: not necessary to create an email
+ if not email_to:
+ return
+
+ # try to find an email_from
+ current_user = res_users_obj.browse(cr, uid, [uid], context=context)[0]
+ email_from = new_msg_values.get('email_from')
+ if not email_from:
+ email_from = current_user.user_email
+
+ # get email content, create it (with mail_message.create)
+ email_values = self.message_create_notify_get_email_dict(cr, uid, new_msg_values, email_from, email_to, context)
+ email_id = message_obj.create(cr, uid, email_values, context=context)
+ return email_id
+
+ def message_create_notify_get_email_dict(self, cr, uid, new_msg_values, email_from, email_to, context=None):
+ values = dict(new_msg_values)
+
+ body_html = new_msg_values.get('body_html', '')
+ if body_html:
+ body_html += '\n\n----------\nThis email was send automatically by OpenERP, because you have subscribed to a document.'
+ body_text = new_msg_values.get('body_text', '')
+ if body_text:
+ body_text += '\n\n----------\nThis email was send automatically by OpenERP, because you have subscribed to a document.'
+ values.update({
+ 'type': 'email',
+ 'state': 'outgoing',
+ 'email_from': email_from,
+ 'email_to': email_to,
+ 'subject': 'New message',
+ 'content_subtype': new_msg_values.get('content_subtype', 'plain'),
+ 'body_html': body_html,
+ 'body_text': body_text,
+ 'auto_delete': True,
+ 'res_model': '',
+ 'res_id': False,
+ })
+ return values
+
def message_remove_pushed_notifications(self, cr, uid, ids, msg_ids, remove_childs=True, context=None):
notif_obj = self.pool.get('mail.notification')
msg_obj = self.pool.get('mail.message')
diff --git a/addons/mail/res_partner.py b/addons/mail/res_partner.py
index 922f3e4b6ed..3dc1f91d857 100644
--- a/addons/mail/res_partner.py
+++ b/addons/mail/res_partner.py
@@ -22,34 +22,18 @@
from osv import osv
from osv import fields
-class res_partner(osv.osv):
+class res_partner_mail(osv.osv):
""" Inherits partner and adds CRM information in the partner form """
_name = "res.partner"
_inherit = ['res.partner', 'mail.thread']
- _columns = {
- 'emails': fields.one2many('mail.message', 'partner_id', 'Emails', readonly=True, domain=[('email_from','!=',False)]),
- }
- def message_load_ids(self, cr, uid, ids, limit=100, offset=0, domain=[], ascent=False, root_ids=[False], context=None):
- """ Override of message_load_ids
- partner discussion page :
- - messages posted on res.partner, partner_id = partner.id
- - messages directly sent to partner
+ def message_search_get_domain(self, cr, uid, ids, context=None):
+ """ Override of message_search_get_domain for partner discussion page.
+ The purpose is to add messages directly sent to the partner.
"""
- msg_obj = self.pool.get('mail.message')
- msg_ids = []
- partner_ids=[]
- for partner in self.browse(cr, uid, ids, context=context):
- msg_ids += msg_obj.search(cr, uid, [ ('res_id', '=', partner.id), ('model', '=' ,self._name)] + domain,
- limit=limit, offset=offset, context=context)
- if self._name=='res.partner':
- partner_ids=msg_obj.search(cr, uid, [ ('partner_id', 'in', ids)] + domain,
- limit=limit, offset=offset, context=context)
- if partner_ids :
- msg_ids+= partner_ids
- if (ascent): msg_ids = self._message_add_ancestor_ids(cr, uid, ids, msg_ids, root_ids, context=context)
- return msg_ids
-
-res_partner()
+ initial_domain = super(res_partner_mail, self).message_search_get_domain(cr, uid, ids, context=context)
+ if self._name == 'res.partner': # to avoid models inheriting from res.partner
+ search_domain = ['|'] + initial_domain + ['|', ('partner_id', 'in', ids), ('partner_ids', 'in', ids)]
+ return search_domain
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/mail/res_partner_view.xml b/addons/mail/res_partner_view.xml
index 2d425f18c7b..d1e2d881739 100644
--- a/addons/mail/res_partner_view.xml
+++ b/addons/mail/res_partner_view.xml
@@ -9,8 +9,8 @@
-
-
+
diff --git a/addons/mail/res_users.py b/addons/mail/res_users.py
index f62e29fb44d..89767473754 100644
--- a/addons/mail/res_users.py
+++ b/addons/mail/res_users.py
@@ -24,24 +24,26 @@ from tools.translate import _
class res_users(osv.osv):
""" Update of res.users class
- - add a preference about sending emails about notificatoins
+ - add a preference about sending emails about notifications
- make a new user follow itself
+ - add a welcome message
"""
_name = 'res.users'
_inherit = ['res.users', 'mail.thread']
_columns = {
'notification_email_pref': fields.selection([
- ('all', 'All feeds'),
- ('comments', 'Only comments'),
- ('to_me', 'Only when sent directly to me'),
- ('none', 'Never')
- ], 'Receive Feeds by Email', required=True,
- help="Choose in which case you want to receive an email when you receive new feeds."),
+ ('all', 'All feeds'),
+ ('comments', 'Only comments'),
+ ('to_me', 'Only when sent directly to me'),
+ ('none', 'Never')
+ ], 'Receive Feeds by Email', required=True,
+ help="Choose in which case you want to receive an email when you "\
+ "receive new feeds."),
}
_defaults = {
- 'notification_email_pref': 'none',
+ 'notification_email_pref': 'to_me',
}
def __init__(self, pool, cr):
@@ -60,25 +62,61 @@ class res_users(osv.osv):
user = self.browse(cr, uid, [user_id], context=context)[0]
# make user follow itself
self.message_subscribe(cr, uid, [user_id], [user_id], context=context)
- # create a welcome message to broadcast
+ # create a welcome message
company_name = user.company_id.name if user.company_id else 'the company'
- message = _('%s has joined %s! You may leave him/her a message to celebrate a new arrival in the company ! You can help him/her doing its first steps on OpenERP.') % (user.name, company_name)
- # TODO: clean the broadcast feature. As this is not cleany specified, temporarily remove the message broadcasting that is not buggy but not very nice.
- #self.message_broadcast(cr, uid, [user.id], 'Welcome notification', message, context=context)
+ message = _('%s has joined %s! Welcome in OpenERP !') % (user.name, company_name)
+ self.message_append_note(cr, uid, [user_id], subject='Welcom to OpenERP', body=message, type='comment', context=context)
return user_id
- def message_load_ids(self, cr, uid, ids, limit=100, offset=0, domain=[], ascent=False, root_ids=[False], context=None):
- """ Override of message_load_ids
- User discussion page :
- - messages posted on res.users, res_id = user.id
- - messages directly sent to user with @user_login
+ def message_search_get_domain(self, cr, uid, ids, context=None):
+ """ Override of message_search_get_domain for partner discussion page.
+ The purpose is to add messages directly sent to user using
+ @user_login.
"""
- if context is None:
- context = {}
- msg_obj = self.pool.get('mail.message')
- msg_ids = []
+ initial_domain = super(res_users, self).message_search_get_domain(cr, uid, ids, context=context)
+ custom_domain = []
for user in self.browse(cr, uid, ids, context=context):
- msg_ids += msg_obj.search(cr, uid, ['|', '|', ('body_text', 'like', '@%s' % (user.login)), ('body_html', 'like', '@%s' % (user.login)), '&', ('res_id', '=', user.id), ('model', '=', self._name)] + domain,
- limit=limit, offset=offset, context=context)
- if (ascent): msg_ids = self._message_add_ancestor_ids(cr, uid, ids, msg_ids, root_ids, context=context)
- return msg_ids
+ if custom_domain:
+ custom_domain += ['|']
+ custom_domain += ['|', ('body_text', 'like', '@%s' % (user.login)), ('body_html', 'like', '@%s' % (user.login))]
+ return ['|'] + initial_domain + custom_domain
+
+class res_users_mail_group(osv.osv):
+ """ Update of res.groups class
+ - if adding/removing users from a group, check mail.groups linked to
+ this user group, and subscribe / unsubscribe them from the discussion
+ group. This is done by overriding the write method.
+ """
+ _name = 'res.users'
+ _inherit = ['res.users', 'mail.thread']
+
+ def write(self, cr, uid, ids, vals, context=None):
+ write_res = super(res_users_mail_group, self).write(cr, uid, ids, vals, context=context)
+ if vals.get('groups_id'):
+ # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
+ user_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]
+ user_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]
+ mail_group_obj = self.pool.get('mail.group')
+ mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', user_group_ids)], context=context)
+ mail_group_obj.message_subscribe(cr, uid, mail_group_ids, ids, context=context)
+ return write_res
+
+
+class res_groups_mail_group(osv.osv):
+ """ Update of res.groups class
+ - if adding/removing users from a group, check mail.groups linked to
+ this user group, and subscribe / unsubscribe them from the discussion
+ group. This is done by overriding the write method.
+ """
+ _name = 'res.groups'
+ _inherit = 'res.groups'
+
+ def write(self, cr, uid, ids, vals, context=None):
+ if vals.get('users'):
+ # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
+ user_ids = [command[1] for command in vals['users'] if command[0] == 4]
+ user_ids += [id for command in vals['users'] if command[0] == 6 for id in command[2]]
+ mail_group_obj = self.pool.get('mail.group')
+ mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', ids)], context=context)
+ mail_group_obj.message_subscribe(cr, uid, mail_group_ids, user_ids, context=context)
+ return super(res_groups_mail_group, self).write(cr, uid, ids, vals, context=context)
diff --git a/addons/mail/res_users_view.xml b/addons/mail/res_users_view.xml
index 15d32a29992..e268997ac2c 100644
--- a/addons/mail/res_users_view.xml
+++ b/addons/mail/res_users_view.xml
@@ -27,7 +27,7 @@
-
+
diff --git a/addons/mail/security/ir.model.access.csv b/addons/mail/security/ir.model.access.csv
index 011e8b27dc5..1fb909f4435 100644
--- a/addons/mail/security/ir.model.access.csv
+++ b/addons/mail/security/ir.model.access.csv
@@ -1,7 +1,7 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
-access_mail_message,mail.message,model_mail_message,,1,0,1,0
-access_mail_message_all,mail.message.all,model_mail_message,base.group_user,1,1,1,1
+access_mail_message_all,mail.message.all,model_mail_message,,1,0,0,0
+access_mail_message_group_user,mail.message.group.user,model_mail_message,base.group_user,1,1,1,1
access_mail_thread,mail.thread,model_mail_thread,base.group_user,1,1,1,0
-access_mail_subscription,mail.subscription,model_mail_subscription,,1,1,1,1
-access_mail_notification,mail.notification,model_mail_notification,,1,1,1,1
+access_mail_subscription_all,mail.subscription.all,model_mail_subscription,,1,1,1,1
+access_mail_notification_all,mail.notification.all,model_mail_notification,,1,1,1,1
access_mail_group,mail.group,model_mail_group,base.group_user,1,1,1,1
diff --git a/addons/mail/static/src/css/mail.css b/addons/mail/static/src/css/mail.css
index 0cf932f9a25..03f1078e6d5 100644
--- a/addons/mail/static/src/css/mail.css
+++ b/addons/mail/static/src/css/mail.css
@@ -1,7 +1,6 @@
-
-/* ------------------------------ */
-/* Wall */
-/* ------------------------------ */
+/* ------------------------------------------------------------ */
+/* Wall
+/* ------------------------------------------------------------ */
.openerp div.oe_mail_wall {
overflow: auto;
@@ -9,6 +8,17 @@
background: white;
}
+.openerp div.oe_mail_wall_main {
+ float: left;
+ width: 560px;
+ margin: 8px;
+}
+
+.openerp div.oe_mail_wall_aside {
+ margin-left: 565px;
+ margin: 8px;
+}
+
.openerp div.oe_mail_wall_action {
padding: 8px;
background: #eee;
@@ -21,36 +31,32 @@
clear: both;
}
-.openerp .oe_mail_wall_action textarea {
+.openerp div.oe_mail_wall_action .oe_mail_msg_content {
+ width: 484px;
+}
+
+.openerp div.oe_mail_wall_action textarea.oe_mail_compose_textarea,
+.openerp div.oe_mail_wall_action div.oe_mail_compose_message_body_text textarea {
width: 474px;
height: 60px;
padding: 4px;
- margin-bottom: 8px;
- float: right;
+ margin-bottom: 2px;
}
-/* 2 columns view */
-.openerp div.oe_mail_wall_main {
- float: left;
- width: 560px;
- margin: 8px;
-}
-
-.openerp div.oe_mail_wall_aside {
- margin-left: 565px;
- margin: 8px;
-}
-
-/* Threads */
-.openerp .oe_mail_wall_threads {
+.openerp ul.oe_mail_wall_threads {
margin-top: 8px;
}
-.openerp .oe_mail_wall_threads textarea {
- height: 40px;
+
+/* Specific display of threads in the wall */
+/* ------------------------------------------------------------ */
+
+.openerp ul.oe_mail_wall_threads .oe_mail_msg_content textarea {
+ width: 434px;
+ height: 30px;
padding: 4px;
}
-.openerp .oe_mail_wall_thread:first .oe_mail_msg_notification {
+.openerp li.oe_mail_wall_thread:first .oe_mail_msg_notification {
border-top: 0;
}
@@ -64,7 +70,7 @@
width: 486px;
}
-.openerp div.oe_mail_msg_content li{
+.openerp div.oe_mail_msg_content li {
float: left;
margin-right: 3px;
}
@@ -79,40 +85,28 @@
}
-/* ------------------------------ */
-/* RecordThread */
-/* ------------------------------ */
+/* ------------------------------------------------------------ */
+/* RecordThread
+/* ------------------------------------------------------------ */
.openerp div.oe_mail_recthread {
overflow: auto;
}
-/* Left-side CSS */
-.openerp div.oe_mail_recthread_actions {
- margin-bottom: 8px;
-}
-
-.openerp div.oe_mail_recthread_followers {
- margin-bottom: 8px;
-}
-
-.openerp div.oe_mail_recthread_followers img.oe_mail_msg_image {
- width: 28px;
- height: 28px;
- margin: 4px;
-}
-
-/* RecordThread: 2 columns view */
-.openerp div.oe_mail_recthread_left {
+.openerp div.oe_mail_recthread_main {
float: left;
width: 560px;
}
-.openerp div.oe_mail_recthread_right {
+.openerp div.oe_mail_recthread_aside {
float: right;
width: 250px;
}
+.openerp div.oe_mail_recthread_actions {
+ margin-bottom: 8px;
+}
+
.openerp div.oe_mail_recthread_actions button {
width: 120px;
}
@@ -144,16 +138,17 @@
background-image: linear-gradient(to bottom, #dc5f59, #b33630);
}
-.openerp textarea.oe_mail_action_textarea {
- height: 60px;
- padding: 5px;
+.openerp div.oe_mail_recthread_followers {
+ margin-bottom: 8px;
}
-/* ------------------------------ */
-/* ThreadDisplay */
-/* ------------------------------ */
+
+/* ------------------------------------------------------------ */
+/* Thread
+/* ------------------------------------------------------------ */
.openerp div.oe_mail_thread_action {
+ display: none;
white-space: normal;
padding: 8px;
background: #eee;
@@ -166,6 +161,26 @@
clear: both;
}
+/* default textarea (oe_mail_compose_textarea), and body_text textarea for compose form view */
+.openerp .oe_mail_msg_content textarea.oe_mail_compose_textarea,
+.openerp .oe_mail_msg_content div.oe_mail_compose_message_body_text textarea {
+ width: 474px;
+ height: 60px;
+ padding: 4px;
+ font-size: 12px;
+ border: 1px solid #cccccc;
+}
+
+/* default textarea (oe_mail_compose_textarea), and body_text textarea for compose form view */
+.openerp .oe_mail_msg_content textarea.oe_mail_compose_textarea:focus,
+.openerp .oe_mail_msg_content div.oe_mail_compose_message_body_text textarea:focus {
+ outline: 0;
+ border-color: rgba(82, 168, 236, 0.8);
+ -moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
+ -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
+ -box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
+}
+
.openerp div.oe_mail_thread_display {
white-space: normal;
}
@@ -174,7 +189,7 @@
margin-left: 66px;
}
-.openerp div.oe_mail_thread_subthread .oe_mail_thread_msg:last-child {
+.openerp div.oe_mail_thread_subthread li.oe_mail_thread_msg:last-child {
margin-bottom: 8px;
}
@@ -183,18 +198,23 @@
border-bottom: 1px solid #D2D9E7;
}
-.openerp .oe_mail_thread_msg:after {
+.openerp li.oe_mail_thread_msg:after {
content: "";
display: block;
clear: both;
}
-.openerp .oe_mail_thread_msg > div:after {
+.openerp li.oe_mail_thread_msg > div:after {
content: "";
display: block;
clear: both;
}
+.openerp div.oe_mail_msg {
+ padding: 0;
+ margin: 0 0 4px 0;
+}
+
.openerp .oe_mail_msg_notification,
.openerp .oe_mail_msg_comment,
.openerp .oe_mail_msg_email {
@@ -203,11 +223,6 @@
border-top: 1px solid #ccc;
}
-.openerp .oe_email_icon {
- width: 50px;
- height: 50px;
-}
-
.openerp div.oe_mail_thread_subthread .oe_mail_msg_comment {
background: #eee;
}
@@ -230,9 +245,18 @@
clear: both;
}
-.openerp img.oe_mail_msg_image {
+.openerp img.oe_mail_icon {
width: 50px;
height: 50px;
+}
+
+.openerp img.oe_mail_thumbnail {
+ width: 28px;
+ height: 28px;
+ margin: 4px;
+}
+
+.openerp img.oe_mail_frame {
text-align: center;
overflow: hidden;
-moz-border-radius: 3px;
@@ -247,48 +271,60 @@
clip: rect(5px, 40px, 45px, 0px);
}
-/* ------------------------------ */
-/* Styling (should be openerp) */
-/* ------------------------------ */
+.openerp .oe_mail_invisible {
+ display: none;
+}
-.openerp input.oe_mail, textarea.oe_mail {
- width: 432px;
- padding: 4px;
- font-size: 12px;
+/* ------------------------------------------------------------ */
+/* mail.compose.message form view & OpenERP hacks
+/* ------------------------------------------------------------ */
+
+/* form_view: delete white background */
+.openerp .oe_mail_msg_content div.oe_formview {
+ background-color: transparent;
+}
+
+.openerp .oe_mail_msg_content div.oe_form_nosheet {
+ margin: 0px;
+}
+
+.openerp .oe_mail_msg_content table.oe_form_group {
+ margin: 0px;
+}
+
+.openerp .oe_mail_msg_content table.oe_form_field,
+.openerp .oe_mail_msg_content div.oe_form_field {
+ padding: 0px;
+}
+
+.openerp .oe_mail_msg_content td.oe_form_group_cell {
+ vertical-align: bottom;
+}
+
+/* subject: change width */
+.openerp .oe_mail_msg_content .oe_form .oe_form_field input {
+ width: 472px;
+}
+
+/* body_html: cleditor */
+.openerp .oe_mail_msg_content div.cleditorMain {
border: 1px solid #cccccc;
- -webkit-transition: border linear 0.2s, box-shadow linear 0.2s;
- -moz-transition: border linear 0.2s, box-shadow linear 0.2s;
- -ms-transition: border linear 0.2s, box-shadow linear 0.2s;
- -o-transition: border linear 0.2s, box-shadow linear 0.2s;
- transition: border linear 0.2s, box-shadow linear 0.2s;
- -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
- -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
- -box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
- -moz-border-radius: 3px;
- -webkit-border-radius: 3px;
- border-radius: 3px;
}
-.openerp input.oe_mail:focus, textarea.oe_mail:focus {
- outline: 0;
- border-color: rgba(82, 168, 236, 0.8);
- -moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
- -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
- -box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6);
+/* destination_partner_ids */
+.openerp .oe_mail_msg_content div.text-core {
+ height: 22px !important;
+ width: 472px;
}
-.openerp div.oe_mail_msg {
- padding: 0;
- margin: 0 0 4px 0;
+/* buttons */
+.openerp .oe_mail_msg_content .oe_mail_compose_message_icons button.oe_form_button {
+ padding: 1px;
}
-.openerp .oe_mail_oe_bold {
- font-weight: bold;
-}
-
-/* ------------------------------ */
-/* Messages layout */
-/* ------------------------------ */
+/* ------------------------------------------------------------ */
+/* Messages layout
+/* ------------------------------------------------------------ */
.openerp .oe_mail_msg .oe_mail_msg_title {
margin: 0;
@@ -318,6 +354,10 @@
display: inline;
}
+.openerp .oe_mail_oe_bold {
+ font-weight: bold;
+}
+
/* Read more/less link */
.openerp .oe_mail_msg_content .expand,
.openerp .oe_mail_msg_content .reduce {
@@ -360,35 +400,3 @@
padding: 0;
list-style-type: square;
}
-
-
-/* ------------------------------ */
-/* Group Form */
-/* ------------------------------ */
-
-div.oe_mail_group_advanced_details {
- display: none;
-}
-
-.oe_form_sheetbg.openerp_mail_group_sheet {
- min-height: 0px;
- max-height: none;
-}
-
-.oe_form_sheetbg.openerp_mail_group_sheet .oe_form_sheet {
- min-height: 0px;
- max-height: none;
- padding: 0px 18px;
- max-width: 80%;
-}
-
-/* Resize group logo */
-.oe_form_sheetbg.openerp_mail_group_sheet .oe_form_field_image > img {
- max-width: 100px;
- max-height: 100px;
-}
-
-/* Resize group description */
-.oe_form_sheetbg.openerp_mail_group_sheet .oe_form_field_text > textarea {
- height: 40px;
-}
diff --git a/addons/mail/static/src/css/mail_compose_message.css b/addons/mail/static/src/css/mail_compose_message.css
new file mode 100644
index 00000000000..4cd1339ded4
--- /dev/null
+++ b/addons/mail/static/src/css/mail_compose_message.css
@@ -0,0 +1,16 @@
+/* ------------------------------ */
+/* Compose Message Wizard Form */
+/* ------------------------------ */
+
+.openerp tr td .oe_form_field.oe_mail_compose_message_invisible {
+ display: none;
+}
+
+.openerp .oe_mail_compose_message_icons {
+ text-align: right;
+}
+
+.openerp .oe_mail_compose_message_icons img {
+ width: 20px;
+ height: 20px;
+}
diff --git a/addons/mail/static/src/img/_fp.png b/addons/mail/static/src/img/_fp.png
deleted file mode 100644
index 17dce2a047c..00000000000
Binary files a/addons/mail/static/src/img/_fp.png and /dev/null differ
diff --git a/addons/mail/static/src/img/attachment.png b/addons/mail/static/src/img/attachment.png
new file mode 100644
index 00000000000..5cc0c33257d
Binary files /dev/null and b/addons/mail/static/src/img/attachment.png differ
diff --git a/addons/mail/static/src/img/checklist.png b/addons/mail/static/src/img/checklist.png
new file mode 100644
index 00000000000..d252606ff53
Binary files /dev/null and b/addons/mail/static/src/img/checklist.png differ
diff --git a/addons/mail/static/src/img/feeds-hover.png b/addons/mail/static/src/img/feeds-hover.png
deleted file mode 100644
index 67070d3e7df..00000000000
Binary files a/addons/mail/static/src/img/feeds-hover.png and /dev/null differ
diff --git a/addons/mail/static/src/img/feeds.png b/addons/mail/static/src/img/feeds.png
deleted file mode 100644
index ac2293c0bf5..00000000000
Binary files a/addons/mail/static/src/img/feeds.png and /dev/null differ
diff --git a/addons/mail/static/src/img/formatting.png b/addons/mail/static/src/img/formatting.png
new file mode 100644
index 00000000000..cf45fdf192f
Binary files /dev/null and b/addons/mail/static/src/img/formatting.png differ
diff --git a/addons/mail/static/src/js/mail.js b/addons/mail/static/src/js/mail.js
index 2140bbe474a..8ce050fd144 100644
--- a/addons/mail/static/src/js/mail.js
+++ b/addons/mail/static/src/js/mail.js
@@ -5,210 +5,652 @@ openerp.mail = function(session) {
var mail = session.mail = {};
/**
- * Add records to sorted_comments array
- * @param {Array} records records from mail.message sorted by date desc
- * @returns {Object} cs comments_structure: dict
- * cs.model_to_root_ids = {model: [root_ids], }
- * cs.new_root_ids = [new_root_ids]
- * cs.root_ids = [root_ids]
- * cs.msgs = {record.id: record,}
- * cs.tree_struct = {record.id: {
- * 'level': record_level in hierarchy, 0 is root,
- * 'msg_nbr': number of childs,
- * 'direct_childs': [msg_ids],
- * 'all_childs': [msg_ids],
- * 'for_thread_msgs': [records],
- * 'ancestors': [msg_ids], } }
+ * ------------------------------------------------------------
+ * FormView
+ * ------------------------------------------------------------
+ *
+ * Override of formview do_action method, to catch all return action about
+ * mail.compose.message. The purpose is to bind 'Send by e-mail' buttons
+ * and redirect them to the Chatter.
*/
- function tools_sort_comments(cs, records, parent_id) {
- var cur_iter = 0; var max_iter = 10; var modif = true;
- while ( modif && (cur_iter++) < max_iter) {
- modif = false;
- _(records).each(function (record) {
- // root and not yet recorded
- if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
- // add to model -> root_list ids
- if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
- else cs['model_to_root_ids'][record.model].push(record.id);
- // add root data
- cs['new_root_ids'].push(record.id);
- // add record
- cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
- cs['msgs'][record.id] = record;
- modif = true;
- }
- // not yet recorded, but parent is recorded
- else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
- var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
- // update parent structure
- cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
- cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
- // update ancestors structure
- for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
- cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
+
+ session.web.FormView = session.web.FormView.extend({
+ do_action: function(action, on_close) {
+ if (action.res_model == 'mail.compose.message' && this.fields && this.fields.message_ids) {
+ var record_thread = this.fields.message_ids;
+ var thread = record_thread.thread;
+ thread.instantiate_composition_form('comment', true, false, 0, action.context);
+ return false;
+ }
+ else {
+ return this._super(action, on_close);
+ }
+ },
+ });
+
+
+ /**
+ * ------------------------------------------------------------
+ * ChatterUtils
+ * ------------------------------------------------------------
+ *
+ * This class holds a few tools method that will be used by
+ * the various Chatter widgets.
+ */
+
+ mail.ChatterUtils = {
+
+ /**
+ * mail_int_mapping: structure to keep a trace of internal links mapping
+ * mail_int_mapping['model'] = {
+ * 'name_get': [[id,label], [id,label], ...]
+ * 'fetch_ids': [id, id, ...] } */
+ //var mail_int_mapping = {};
+
+ /**
+ * mail_msg_struct: structure to orrganize chatter messages
+ */
+ //var mail_msg_struct = {}; // TODO: USE IT OR NOT :)
+
+ /* generic chatter events binding */
+ bind_events: function(widget) {
+ // event: click on an internal link to a document: model, login
+ widget.$element.delegate('a.oe_mail_internal_link', 'click', function (event) {
+ event.preventDefault();
+ // lazy implementation: fetch data and try to redirect
+ if (! event.srcElement.dataset.resModel) return false;
+ else var res_model = event.srcElement.dataset.resModel;
+ var res_login = event.srcElement.dataset.resLogin;
+ if (! res_login) return false;
+ var ds = new session.web.DataSet(widget, res_model);
+ var defer = ds.call('search', [[['login', '=', res_login]]]).pipe(function (records) {
+ if (records[0]) {
+ widget.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
}
- // add record
- cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
- cs['msgs'][record.id] = record;
- modif = true;
- }
+ else return false;
+ });
});
- }
- return cs;
- }
+ },
+
+ /** get an image in /web/binary/image?... */
+ get_image: function(session_prefix, session_id, model, field, id) {
+ return session_prefix + '/web/binary/image?session_id=' + session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
+ },
+
+ /** checks if tue current user is the message author */
+ is_author: function (widget, message_user_id) {
+ return (widget.session && widget.session.uid != 0 && widget.session.uid == message_user_id);
+ },
+
+ /**
+ * Add records to comments_structure array
+ * @param {Array} records records from mail.message sorted by date desc
+ * @returns {Object} cs comments_structure: dict
+ * cs.model_to_root_ids = {model: [root_ids], }
+ * cs.new_root_ids = [new_root_ids]
+ * cs.root_ids = [root_ids]
+ * cs.msgs = {record.id: record,}
+ * cs.tree_struct = {record.id: {
+ * 'level': record_level in hierarchy, 0 is root,
+ * 'msg_nbr': number of childs,
+ * 'direct_childs': [msg_ids],
+ * 'all_childs': [msg_ids],
+ * 'for_thread_msgs': [records],
+ * 'ancestors': [msg_ids], } }
+ */
+ records_struct_add_records: function(cs, records, parent_id) {
+ var cur_iter = 0; var max_iter = 10; var modif = true;
+ while ( modif && (cur_iter++) < max_iter) {
+ modif = false;
+ _(records).each(function (record) {
+ // root and not yet recorded
+ if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
+ // add to model -> root_list ids
+ if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
+ else cs['model_to_root_ids'][record.model].push(record.id);
+ // add root data
+ cs['new_root_ids'].push(record.id);
+ // add record
+ cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
+ cs['msgs'][record.id] = record;
+ modif = true;
+ }
+ // not yet recorded, but parent is recorded
+ else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
+ var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
+ // update parent structure
+ cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
+ cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
+ // update ancestors structure
+ for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
+ cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
+ }
+ // add record
+ cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
+ cs['msgs'][record.id] = record;
+ modif = true;
+ }
+ });
+ }
+ return cs;
+ },
+
+ /* copy cs.new_root_ids into cs.root_ids */
+ records_struct_update_after_display: function(cs) {
+ // update TODO
+ cs['root_ids'] = _.union(cs['root_ids'], cs['new_root_ids']);
+ cs['new_root_ids'] = [];
+ return cs;
+ },
+
+ /**
+ * CONTENT MANIPULATION
+ *
+ * Regular expressions
+ * - (^|\s)@((\w|@|\.)*): @login@log.log, supports inner '@' for
+ * logins that are emails
+ * 1. '(void)'
+ * 2. login@log.log
+ * - (^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]: [ir.attachment,3|My Label],
+ * for internal links to model ir.attachment, id=3, and with
+ * optional label 'My Label'. Note that having a '|Label' is not
+ * mandatory, because the regex should still be correct.
+ * 1. '(void)'
+ * 2. 'ir'
+ * 3. 'attachment'
+ * 4. '3'
+ * 5. 'My Label'
+ */
+
+ /** Removes html tags, except b, em, br, ul, li */
+ do_text_remove_html_tags: function (string) {
+ var html = $('').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('<(/)?(b|em|br|br /|ul|li|div)\\s*>', 'gi'), '<$1$2>');
+ return html;
+ },
+
+ /** Replaces line breaks by html line breaks (br) */
+ do_text_nl2br: function (str, is_xhtml) {
+ var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? ' ' : ' ';
+ return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
+ },
+
+ /* Add a prefix before each new line of the original string */
+ do_text_quote: function (str, prefix) {
+ return str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2' + prefix || '> ');
+ },
+
+ /**
+ * Replaces some expressions
+ * - @login - shorcut to link to a res.user, given its login
+ * - [ir.attachment,3|My Label] - shortcut to an internal
+ * document
+ * - :name - shortcut to an image
+ */
+ do_replace_expressions: function (string) {
+ var self = this;
+ var icon_list = ['al', 'pinky']
+ /* shortcut to user: @login */
+ var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
+ var regex_res = regex_login.exec(string);
+ while (regex_res != null) {
+ var login = regex_res[2];
+ string = string.replace(regex_res[0], regex_res[1] + '@' + login + '');
+ regex_res = regex_login.exec(string);
+ }
+ /* shortcut for internal document */
+ var regex_login = new RegExp(/(^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]/g);
+ var regex_res = regex_login.exec(string);
+ while (regex_res != null) {
+ var res_model = regex_res[2] + '.' + regex_res[3];
+ var res_id = regex_res[4];
+ if (! regex_res[5]) {
+ var label = res_model + ':' + res_id }
+ else {
+ var label = regex_res[5];
+ }
+ string = string.replace(regex_res[0], regex_res[1] + '');
+ regex_res = regex_login.exec(string);
+ }
+ return string;
+ },
+
+ /**
+ * Checks a string to find an expression that will be replaced
+ * by an internal link and requiring a name_get to replace
+ * the expression.
+ * :param mapping: structure to keep a trace of internal links mapping
+ * mapping['model'] = {
+ * name_get': [[id,label], [id,label], ...]
+ * 'to_fetch_ids': [id, id, ...]
+ * }
+ * CURRENTLY NOT IMPLEMENTED */
+ do_check_for_name_get_mapping: function(string, mapping) {
+ /* shortcut to user: @login */
+ //var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
+ //var regex_res = regex_login.exec(string);
+ //while (regex_res != null) {
+ //var login = regex_res[2];
+ //if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
+ //this.map_hash['res.users']['login'].push(login);
+ //regex_res = regex_login.exec(string);
+ //}
+ /* document link with name_get: [res.model,name] */
+ /* internal link with id: [res.model,id], or [res.model,id|display_name] */
+ //var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
+ //regex_res = regex_intlink.exec(string);
+ //while (regex_res != null) {
+ //var res_model = regex_res[2] + '.' + regex_res[3];
+ //var res_name = regex_res[4];
+ //if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
+ //this.map_hash[res_model]['name'].push(res_name);
+ //regex_res = regex_intlink.exec(string);
+ //}
+ },
+
+ /**
+ * Updates the mapping; check for to_fetch_ids for each recorded
+ * model, and perform a name_get to update the mapping.
+ * CURRENTLY NOT IMPLEMENTED */
+ do_update_name_get_mapping: function(mapping) {
+ },
+ };
+
+
+ /**
+ * ------------------------------------------------------------
+ * ComposeMessage widget
+ * ------------------------------------------------------------
+ *
+ * This widget handles the display of a form to compose a new message.
+ * This form is an OpenERP form_view, build on a mail.compose.message
+ * wizard.
+ */
+
+ mail.ComposeMessage = session.web.Widget.extend({
+ template: 'mail.compose_message',
+
+ /**
+ * @param {Object} parent parent
+ * @param {Object} [params]
+ * @param {String} [params.res_model] res_model of document [REQUIRED]
+ * @param {Number} [params.res_id] res_id of record [REQUIRED]
+ * @param {Number} [params.email_mode] true/false, tells whether
+ * we are in email sending mode
+ * @param {Number} [params.formatting] true/false, tells whether
+ * we are in advance formatting mode
+ * @param {String} [params.model] mail.compose.message.mode (see
+ * composition wizard)
+ * @param {Number} [params.msg_id] id of a message in case we are in
+ * reply mode
+ */
+ init: function(parent, params) {
+ var self = this;
+ this._super(parent);
+ // options
+ this.params = params || {};
+ this.params.context = params.context || {};
+ this.params.email_mode = params.email_mode || false;
+ this.params.formatting = params.formatting || false;
+ this.params.mode = params.mode || 'comment';
+ this.params.form_xml_id = params.form_xml_id || 'email_compose_message_wizard_form_chatter';
+ this.params.form_view_id = false;
+ if (this.params.mode == 'reply') {
+ this.params.active_id = this.params.msg_id;
+ } else {
+ this.params.active_id = this.params.res_id;
+ }
+ this.email_mode = false;
+ this.formatting = false;
+ },
+
+ /**
+ * Reinitialize the widget field values to the default values. The
+ * purpose is to avoid to destroy and re-build a form view. Default
+ * values are therefore given as for an onchange. */
+ reinit: function() {
+ var self = this;
+ if (! this.form_view) return;
+ var call_defer = this.ds_compose.call('default_get', [['subject', 'body_text', 'body_html', 'dest_partner_ids'], this.ds_compose.get_context()]).then(
+ function (result) {
+ self.form_view.on_processed_onchange({'value': result}, []);
+ });
+ return call_defer;
+ },
+
+ /**
+ * Override-hack of do_action: clean the form */
+ do_action: function(action, on_close) {
+ // this.init_comments();
+ return this._super(action, on_close);
+ },
+
+ /**
+ * Widget start function
+ * - builds and initializes the form view */
+ start: function() {
+ var self = this;
+ this._super.apply(this, arguments);
+ // customize display: add avatar, clean previous content
+ var user_avatar = mail.ChatterUtils.get_image(this.session.prefix,
+ this.session.session_id, 'res.users', 'avatar', this.session.uid);
+ this.$element.find('img.oe_mail_icon').attr('src', user_avatar);
+ this.$element.find('div.oe_mail_msg_content').empty();
+ // create a context for the default_get of the compose form
+ var widget_context = {
+ 'active_model': this.params.res_model,
+ 'active_id': this.params.active_id,
+ 'mail.compose.message.mode': this.params.mode,
+ };
+ var context = _.extend({}, this.params.context, widget_context);
+ this.ds_compose = new session.web.DataSetSearch(this, 'mail.compose.message', context);
+ // find the id of the view to display in the chatter form
+ var data_ds = new session.web.DataSetSearch(this, 'ir.model.data');
+ var deferred_form_id =data_ds.call('get_object_reference', ['mail', this.params.form_xml_id]).then( function (result) {
+ if (result) {
+ self.params.form_view_id = result[1];
+ }
+ }).pipe(this.proxy('create_form_view'));
+ return deferred_form_id;
+ },
+
+ /**
+ * Create a FormView, then append it to the to widget DOM. */
+ create_form_view: function () {
+ var self = this;
+ // destroy previous form_view if any
+ if (this.form_view) { this.form_view.destroy(); }
+ // create the FormView
+ this.form_view = new session.web.FormView(this, this.ds_compose, this.params.form_view_id, {
+ action_buttons: false,
+ pager: false,
+ initial_mode: 'edit',
+ });
+ // add the form, bind events, activate the form
+ var msg_node = this.$element.find('div.oe_mail_msg_content');
+ return $.when(this.form_view.appendTo(msg_node)).pipe(function() {
+ self.bind_events();
+ self.form_view.do_show();
+ if (self.params.email_mode) { self.toggle_email_mode(); }
+ if (self.params.formatting) { self.toggle_formatting_mode(); }
+ });
+ },
+
+ destroy: function() {
+ this._super.apply(this, arguments);
+ },
+
+ /**
+ * Bind events in the widget. Each event is slightly described
+ * in the function. */
+ bind_events: function() {
+ var self = this;
+ this.$element.find('button.oe_form_button').click(function (event) {
+ event.preventDefault();
+ });
+ // event: click on 'Send an Email' link that toggles the form for
+ // sending an email (partner_ids)
+ this.$element.find('a.oe_mail_compose_message_email').click(function (event) {
+ event.preventDefault();
+ self.toggle_email_mode();
+ });
+ // event: click on 'Formatting' icon-link that toggles the advanced
+ // formatting options for writing a message (subject, body_html)
+ this.$element.find('a.oe_mail_compose_message_formatting').click(function (event) {
+ event.preventDefault();
+ self.toggle_formatting_mode();
+ });
+ // event: click on 'Attachment' icon-link that opens the dialog to
+ // add an attachment.
+ this.$element.find('a.oe_mail_compose_message_attachment').click(function (event) {
+ event.preventDefault();
+ // not yet implemented
+ self.set_body_value('attachment', 'attachment');
+ });
+ // event: click on 'Checklist' icon-link that toggles the options
+ // for adding checklist.
+ this.$element.find('a.oe_mail_compose_message_checklist').click(function (event) {
+ event.preventDefault();
+ // not yet implemented
+ self.set_body_value('checklist', 'checklist');
+ });
+ },
+
+ /**
+ * Toggle the formatting mode. */
+ toggle_formatting_mode: function() {
+ var self = this;
+ this.formatting = ! this.formatting;
+ // calls onchange
+ var call_defer = this.ds_compose.call('onchange_formatting', [[], this.formatting, this.params.res_model, this.params.res_id]).then(
+ function (result) {
+ self.form_view.on_processed_onchange(result, []);
+ });
+ // update context of datasetsearch
+ this.ds_compose.context.formatting = this.formatting;
+ // toggle display
+ this.$element.find('span.oe_mail_compose_message_subject').toggleClass('oe_mail_compose_message_invisible');
+ this.$element.find('div.oe_mail_compose_message_body_text').toggleClass('oe_mail_compose_message_invisible');
+ this.$element.find('div.oe_mail_compose_message_body_html').toggleClass('oe_mail_compose_message_invisible');
+ },
+
+ /**
+ * Toggle the email mode. */
+ toggle_email_mode: function() {
+ var self = this;
+ this.email_mode = ! this.email_mode;
+ // calls onchange
+ var call_defer = this.ds_compose.call('onchange_email_mode', [[], this.email_mode, this.params.res_model, this.params.res_id]).then(
+ function (result) {
+ self.form_view.on_processed_onchange(result, []);
+ });
+ // update context of datasetsearch
+ this.ds_compose.context.email_mode = this.email_mode;
+ // update 'Post' button -> 'Send'
+ // update 'Send an Email' link -> 'Post a comment'
+ if (this.email_mode) {
+ this.$element.find('button.oe_mail_compose_message_button_send').html('Send');
+ this.$element.find('a.oe_mail_compose_message_email').html('Comment');
+ } else {
+ this.$element.find('button.oe_mail_compose_message_button_send').html('Post');
+ this.$element.find('a.oe_mail_compose_message_email').html('Send an Email');
+ }
+ // toggle display
+ this.$element.find('div.oe_mail_compose_message_partner_ids').toggleClass('oe_mail_compose_message_invisible');
+ },
+
+ /**
+ * Update the values of the composition form; with possible different
+ * values for body_text and body_html. */
+ set_body_value: function(body_text, body_html) {
+ this.form_view.fields.body_text.set_value(body_text);
+ this.form_view.fields.body_html.set_value(body_html);
+ },
+ }),
/**
- * ThreadDisplay widget: this widget handles the display of a thread of
- * messages. The [thread_level] parameter sets the thread level number:
+ * ------------------------------------------------------------
+ * Thread Widget
+ * ------------------------------------------------------------
+ *
+ * This widget handles the display of a thread of messages. The
+ * [thread_level] parameter sets the thread level number:
* - root message
* - - sub message (parent_id = root message)
* - - - sub sub message (parent id = sub message)
* - - sub message (parent_id = root message)
- * This widget has 2 ways of initialization, either you give records to be rendered,
- * either it will fetch [limit] messages related to [res_model]:[res_id].
+ * This widget has 2 ways of initialization, either you give records
+ * to be rendered, either it will fetch [limit] messages related to
+ * [res_model]:[res_id].
*/
+
mail.Thread = session.web.Widget.extend({
- template: 'mail.Thread',
+ template: 'mail.thread',
/**
* @param {Object} parent parent
* @param {Object} [params]
- * @param {String} [params.res_model] res_model of mail.thread object
- * @param {Number} [params.res_id] res_id of record
- * @param {Number} [params.parent_id=false] parent_id of message
- * @param {Number} [params.uid] user id
- * @param {Number} [params.thread_level=0] number of levels in the thread (only 0 or 1 currently)
- * @param {Number} [params.msg_more_limit=100] number of character to display before having a "show more" link;
- * note that the text will not be truncated if it does not have 110% of
- * the parameter (ex: 110 characters needed to be truncated and be displayed
- * as a 100-characters message)
- * @param {Number} [params.limit=10] maximum number of messages to fetch
+ * @param {String} [params.res_model] res_model of document [REQUIRED]
+ * @param {Number} [params.res_id] res_id of record [REQUIRED]
+ * @param {Number} [params.uid] user id [REQUIRED]
+ * @param {Bool} [params.parent_id=false] parent_id of message
+ * @param {Number} [params.thread_level=0] number of levels in the thread
+ * (only 0 or 1 currently)
+ * @param {Bool} [params.is_wall=false] thread is displayed in the wall
+ * @param {Number} [params.msg_more_limit=150] number of character to
+ * display before having a "show more" link; note that the text
+ * will not be truncated if it does not have 110% of the parameter
+ * (ex: 110 characters needed to be truncated and be displayed as
+ * a 100-characters message)
+ * @param {Number} [params.limit=100] maximum number of messages to fetch
* @param {Number} [params.offset=0] offset for fetching messages
* @param {Number} [params.records=null] records to show instead of fetching messages
*/
init: function(parent, params) {
this._super(parent);
+ // options
this.params = params;
this.params.parent_id = this.params.parent_id || false;
this.params.thread_level = this.params.thread_level || 0;
- this.params.msg_more_limit = this.params.msg_more_limit || 290;
+ this.params.is_wall = this.params.is_wall || (this.params.records != undefined) || false;
+ this.params.msg_more_limit = this.params.msg_more_limit || 150;
this.params.limit = this.params.limit || 100;
+ // this.params.limit = 3; // tmp for testing
this.params.offset = this.params.offset || 0;
this.params.records = this.params.records || null;
// datasets and internal vars
- this.ds = new session.web.DataSet(this, this.params.res_model);
- this.ds_users = new session.web.DataSet(this, 'res.users');
- this.ds_msg = new session.web.DataSet(this, 'mail.message');
- this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
+ this.ds = new session.web.DataSetSearch(this, this.params.res_model);
+ this.ds_users = new session.web.DataSetSearch(this, 'res.users');
+ this.ds_msg = new session.web.DataSetSearch(this, 'mail.message');
this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
// display customization vars
this.display = {};
this.display.show_post_comment = this.params.show_post_comment || false;
- this.display.show_reply = (this.params.thread_level > 0);
- this.display.show_delete = true;
- this.display.show_hide = this.params.show_hide || false;
+ this.display.show_reply = (this.params.thread_level > 0 && this.params.is_wall);
+ this.display.show_delete = ! this.params.is_wall;
+ this.display.show_hide = this.params.is_wall;
+ this.display.show_reply_by_email = ! this.params.is_wall;
this.display.show_more = (this.params.thread_level == 0);
- // not used currently
- this.intlinks_mapping = {};
},
start: function() {
- var self = this;
-
this._super.apply(this, arguments);
- // customize display
- if (! this.display.show_post_comment) {
- this.$element.find('div.oe_mail_thread_action').hide();
- }
// add events
- this.add_events();
-
+ this.bind_events();
// display user, fetch comments
this.display_current_user();
-
- if (this.params.records) {
- var display_done = this.display_comments_from_parameters(this.params.records);
- } else {
- var display_done = this.init_comments();
+ if (this.params.records) var display_done = this.display_comments_from_parameters(this.params.records);
+ else var display_done = this.init_comments();
+ // customize display
+ $.when(display_done).then(this.proxy('do_customize_display'));
+ // add message composition form view
+ if (this.display.show_post_comment) {
+ var compose_done = this.instantiate_composition_form();
}
- return display_done
+ return display_done && compose_done;
},
-
- add_events: function() {
+
+ /**
+ * Override-hack of do_action: automatically reload the chatter.
+ * Normally it should be called only when clicking on 'Post/Send'
+ * in the composition form. */
+ do_action: function(action, on_close) {
+ this.init_comments();
+ if (this.compose_message_widget) {
+ this.compose_message_widget.reinit(); }
+ return this._super(action, on_close);
+ },
+
+ instantiate_composition_form: function(mode, email_mode, formatting, msg_id, context) {
+ if (this.compose_message_widget) {
+ this.compose_message_widget.destroy();
+ }
+ this.compose_message_widget = new mail.ComposeMessage(this, {
+ 'extended_mode': false, 'uid': this.params.uid, 'res_model': this.params.res_model,
+ 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id,
+ 'email_mode': email_mode || false, 'formatting': formatting || false,
+ 'context': context || false } );
+ var composition_node = this.$element.find('div.oe_mail_thread_action');
+ composition_node.empty();
+ var compose_done = this.compose_message_widget.appendTo(composition_node);
+ return compose_done;
+ },
+
+ do_customize_display: function() {
+ if (this.display.show_post_comment) { this.$element.find('div.oe_mail_thread_action').eq(0).show(); }
+ },
+
+ /**
+ * Bind events in the widget. Each event is slightly described
+ * in the function. */
+ bind_events: function() {
var self = this;
+ // generic events from Chatter Mixin
+ mail.ChatterUtils.bind_events(this);
// event: click on 'more' at bottom of thread
this.$element.find('button.oe_mail_button_more').click(function () {
self.do_more();
});
- // event: writing in textarea
- this.$element.find('textarea.oe_mail_action_textarea').keyup(function (event) {
+ // event: writing in basic textarea of composition form (quick reply)
+ this.$element.find('textarea.oe_mail_compose_textarea').keyup(function (event) {
var charCode = (event.which) ? event.which : window.event.keyCode;
if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
else if (charCode == 13) { return self.do_comment(); }
});
- // event: click on 'reply' in msg
+ // event: click on 'Reply' in msg
this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
act_dom.toggle();
event.preventDefault();
});
- // event: click on 'delete' in msg
- this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
- //console.log('deleting');
- if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
- var msg_id = event.srcElement.dataset.id;
- if (! msg_id) return false;
- var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
- $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
- if (self.params.thread_level > 0) {
- $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
- }
- return false;
- });
- // event: click on 'hide' in msg
- this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
- //console.log('hiding');
- if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
- var msg_id = event.srcElement.dataset.id;
- if (! msg_id) return false;
- //console.log(msg_id);
- var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
- $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
- if (self.params.thread_level > 0) {
- $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
- }
- return false;
- });
- // event: click on an internal link
- this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_internal_link', 'click', function (event) {
- // lazy implementation: fetch data and try to redirect
- if (! event.srcElement.dataset.resModel) return false;
- else var res_model = event.srcElement.dataset.resModel;
- var res_login = event.srcElement.dataset.resLogin;
- var res_id = event.srcElement.dataset.resId;
- if ((! res_login) && (! res_id)) return false;
- if (! res_id) {
- var ds = new session.web.DataSet(self, res_model);
- var defer = ds.call('search', [[['login', '=', res_login]]]).then(function (records) {
- if (records[0]) {
- self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
- }
- else return false;
- });
- }
- else self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(res_id), views: [[false, 'form']]});
- });
// event: click on 'attachment(s)' in msg
this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
act_dom.toggle();
- return false;
+ event.preventDefault();
});
- // see more
- this.$element.on('click','a.oe_mail_msg_more', function (event) {
- $(this).siblings('.oe_mail_msg_tail').show();
- $(this).hide();
- return false;
+ // event: click on 'Delete' in msg side menu
+ this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
+ if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
+ var msg_id = event.srcElement.dataset.id;
+ if (! msg_id) return false;
+ var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
+ $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
+ if (self.params.thread_level > 0) {
+ $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
+ }
+ event.preventDefault();
+ return call_defer;
+ });
+ // event: click on 'Hide' in msg side menu
+ this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
+ if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
+ var msg_id = event.srcElement.dataset.id;
+ if (! msg_id) return false;
+ var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
+ $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
+ if (self.params.thread_level > 0) {
+ $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
+ }
+ event.preventDefault();
+ return call_defer;
+ });
+ // event: click on "Reply" in msg side menu (email style)
+ this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply_by_email', 'click', function (event) {
+ var msg_id = event.srcElement.dataset.msg_id;
+ var email_mode = (event.srcElement.dataset.type == 'email');
+ var formatting = (event.srcElement.dataset.formatting == 'html');
+ if (! msg_id) return false;
+ self.instantiate_composition_form('reply', email_mode, formatting, msg_id);
+ event.preventDefault();
});
},
@@ -219,21 +661,22 @@ openerp.mail = function(session) {
init_comments: function() {
var self = this;
this.params.offset = 0;
- this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
this.$element.find('div.oe_mail_thread_display').empty();
- domain = this.get_fetch_domain(this.sorted_comments);
+ var domain = this.get_fetch_domain(this.comments_structure);
return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
},
fetch_comments: function (limit, offset, domain) {
var self = this;
- var defer = this.ds.call('message_load', [[this.params.res_id], ( (limit+1)||(this.params.limit+1) ), (offset||this.params.offset), (domain||[]), (this.params.thread_level > 0), (this.sorted_comments['root_ids'])]);
- $.when(defer).then(function (records) {
+ var defer = this.ds.call('message_read', [[this.params.res_id], (this.params.thread_level > 0), (this.comments_structure['root_ids']),
+ (limit+1) || (this.params.limit+1), offset||this.params.offset, domain||undefined ]).then(function (records) {
if (records.length <= self.params.limit) self.display.show_more = false;
- else { self.display.show_more = true; records.pop(); }
-
+ // else { self.display.show_more = true; records.pop(); }
+ // else { self.display.show_more = true; records.splice(0, 1); }
+ else { self.display.show_more = true; }
self.display_comments(records);
+ // TODO: move to customize display
if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
else self.$element.find('div.oe_mail_thread_more:last').hide();
});
@@ -245,6 +688,7 @@ openerp.mail = function(session) {
if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
else this.display.show_more = false;
var defer = this.display_comments(records);
+ // TODO: move to customize display
if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
else $('div.oe_mail_thread_more').eq(-2).hide();
return defer;
@@ -252,7 +696,8 @@ openerp.mail = function(session) {
display_comments: function (records) {
var self = this;
-
+ // sort the records
+ mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, this.params.parent_id);
//build attachments download urls and compute time-relative from dates
for (var k in records) {
records[k].timerelative = $.timeago(records[k].date);
@@ -263,11 +708,10 @@ openerp.mail = function(session) {
}
}
}
- this.cs = this.sort_comments_tmp(records);
_(records).each(function (record) {
var sub_msgs = [];
if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
- var sub_list = self.cs['tree_struct'][record.id]['direct_childs'];
+ var sub_list = self.comments_structure['tree_struct'][record.id]['direct_childs'];
_(records).each(function (record) {
//if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
if (_.indexOf(sub_list, record.id) != -1) {
@@ -276,35 +720,40 @@ openerp.mail = function(session) {
});
self.display_comment(record);
self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
- 'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id});
- self.$element.find('.oe_mail_thread_msg:last').append('');
+ 'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id,
+ 'is_wall': self.params.is_wall});
+ self.$element.find('li.oe_mail_thread_msg:last').append('');
self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
}
else if (self.params.thread_level == 0) {
self.display_comment(record);
}
});
+ mail.ChatterUtils.records_struct_update_after_display(this.comments_structure);
// update offset for "More" buttons
if (this.params.thread_level == 0) this.params.offset += records.length;
},
- /**
- * Display a record
- */
+ /** Displays a record, performs text/link formatting */
display_comment: function (record) {
- record.body = this.do_text_nl2br(record.body, true);
+ record.body = mail.ChatterUtils.do_text_nl2br(record.body, true);
+ // if (record.type == 'email' && record.state == 'received') {
if (record.type == 'email') {
record.mini_url = ('/mail/static/src/img/email_icon.png');
- } else {
- record.mini_url = this.thread_get_avatar('res.users', 'avatar', record.user_id[0]);
+ } else {
+ record.mini_url = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'avatar', record.user_id[0]);
}
// body text manipulation
- record.body = this.do_clean_text(record.body);
- record.body = this.do_replace_internal_links(record.body);
-
+ if (record.subtype == 'plain') {
+ record.body = mail.ChatterUtils.do_text_remove_html_tags(record.body);
+ }
+ record.body = mail.ChatterUtils.do_replace_expressions(record.body);
// format date according to the user timezone
record.date = session.web.format_value(record.date, {type:"datetime"});
- var rendered = session.web.qweb.render('mail.Thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
+ // is the user the author ?
+ record.is_author = mail.ChatterUtils.is_author(this, record.user_id[0]);
+ // render
+ var rendered = session.web.qweb.render('mail.thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
$(rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
// expand feature
this.$element.find('div.oe_mail_msg_body:last').expander({
@@ -316,84 +765,33 @@ openerp.mail = function(session) {
lesClass: 'oe_mail_reduce',
});
},
-
- /**
- * Add records to sorted_comments array
- * @param {Array} records records from mail.message sorted by date desc
- * @returns {Object} sc sorted_comments: dict {
- * 'root_id_list': list or root_ids
- * 'root_id_msg_list': {'record_id': [ancestor_ids]}, still sorted by date desc
- * 'id_to_root': {'root_id': [records]}, still sorted by date desc
- * }
- */
- sort_comments: function (records) {
- var self = this;
- sc = {'root_id_list': [], 'root_id_msg_list': {}, 'id_to_root': {}}
- var cur_iter = 0; var max_iter = 10; var modif = true;
- /* step1: get roots */
- while ( modif && (cur_iter++) < max_iter) {
- modif = false;
- _(records).each(function (record) {
- if ( (record.parent_id == false || record.parent_id[0] == self.params.parent_id) && (_.indexOf(sc['root_id_list'], record.id) == -1)) {
- sc['root_id_list'].push(record.id);
- sc['root_id_msg_list'][record.id] = [];
- self.sorted_comments['root_ids'].push(record.id);
- modif = true;
- }
- else {
- if (_.indexOf(sc['root_id_list'], record.parent_id[0]) != -1) {
- sc['id_to_root'][record.id] = record.parent_id[0];
- modif = true;
- }
- else if ( sc['id_to_root'][record.parent_id[0]] ) {
- sc['id_to_root'][record.id] = sc['id_to_root'][record.parent_id[0]];
- modif = true;
- }
- }
- });
- }
- /* step2: add records */
- _(records).each(function (record) {
- var root_id = sc['id_to_root'][record.id];
- if (! root_id) return;
- sc['root_id_msg_list'][root_id].push(record);
- //self.sorted_comments['root_id_msg_list'][root_id].push(record.id);
- });
- return sc;
- },
-
- /**
- * Add records to comments_structure object: see function for details
- */
- sort_comments_tmp: function(records) {
- return tools_sort_comments(this.comments_structure, records, this.params.parent_id);
- },
-
+
display_current_user: function () {
- return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'avatar', this.params.uid));
+ var avatar = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'avatar', this.params.uid);
+ return this.$element.find('img.oe_mail_icon').attr('src', avatar);
},
do_comment: function () {
var comment_node = this.$element.find('textarea');
var body_text = comment_node.val();
comment_node.val('');
- return this.ds.call('message_append_note', [[this.params.res_id], 'Reply', body_text, this.params.parent_id, 'comment', 'html']).then(
+ return this.ds.call('message_append_note', [[this.params.res_id], '', body_text, this.params.parent_id, 'comment', 'plain']).then(
this.proxy('init_comments'));
},
/**
* Create a domain to fetch new comments according to
- * comment already present in sorted_comments
- * @param {Object} sorted_comments (see sort_comments)
+ * comment already present in comments_structure
+ * @param {Object} comments_structure (see chatter utils)
* @returns {Array} fetch_domain (OpenERP domain style)
*/
- get_fetch_domain: function (sorted_comments) {
+ get_fetch_domain: function (comments_structure) {
var domain = [];
- var ids = sorted_comments.root_ids.slice();
+ var ids = comments_structure.root_ids.slice();
var ids2 = [];
// must be child of current parent
if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
- _(sorted_comments.root_ids).each(function (id) { // each record
+ _(comments_structure.root_ids).each(function (id) { // each record
ids.push(id);
ids2.push(id);
});
@@ -413,109 +811,46 @@ openerp.mail = function(session) {
},
do_more: function () {
- domain = this.get_fetch_domain(this.sorted_comments);
+ domain = this.get_fetch_domain(this.comments_structure);
return this.fetch_comments(this.params.limit, this.params.offset, domain);
},
-
- /**
- *
- * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
- * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
- */
- do_replace_internal_links: function (string) {
- var self = this;
- var icon_list = ['al', 'pinky']
- /* shortcut to user: @login */
- var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
- var regex_res = regex_login.exec(string);
- while (regex_res != null) {
- var login = regex_res[2];
- string = string.replace(regex_res[0], regex_res[1] + '@' + login + '');
- regex_res = regex_login.exec(string);
- }
- /* special shortcut: :name, try to find an icon if in list */
- var regex_login = new RegExp(/(^|\s):((\w)*)/g);
- var regex_res = regex_login.exec(string);
- while (regex_res != null) {
- var icon_name = regex_res[2];
- if (_.include(icon_list, icon_name))
- string = string.replace(regex_res[0], regex_res[1] + '');
- regex_res = regex_login.exec(string);
- }
- return string;
- },
-
- thread_get_avatar: function(model, field, id) {
- return this.session.prefix + '/web/binary/image?session_id=' + this.session.session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
- },
-
- /** Removes html tags, except b, em, br */
- do_clean_text: function (string) {
- var html = $('').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('<(/)?(b|em|br|br /)\\s*>', 'gi'), '<$1$2>');
- return html;
- },
-
- /** Replaces line bracks by html line breaks (br) */
- do_text_nl2br: function (str, is_xhtml) {
- var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? ' ' : ' ';
- return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
- },
-
- /**
- *
- * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
- * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
- */
- do_check_internal_links: function(string) {
- /* shortcut to user: @login */
- var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
- var regex_res = regex_login.exec(string);
- while (regex_res != null) {
- var login = regex_res[2];
- if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
- this.map_hash['res.users']['login'].push(login);
- regex_res = regex_login.exec(string);
- }
- /* internal links: #res.model,name */
- var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
- regex_res = regex_intlink.exec(string);
- while (regex_res != null) {
- var res_model = regex_res[2] + '.' + regex_res[3];
- var res_name = regex_res[4];
- if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
- this.map_hash[res_model]['name'].push(res_name);
- regex_res = regex_intlink.exec(string);
- }
- },
-
- /** checks if tue current user is the message author */
- _is_author: function (id) {
- return (this.session.uid == id);
- },
-
});
- session.web.form.widgets.add( 'Thread', 'openerp.mail.Thread');
+
+
+ /**
+ * ------------------------------------------------------------
+ * mail_thread Widget
+ * ------------------------------------------------------------
+ *
+ * This widget handles the display of the Chatter on documents.
+ */
+
+ /* Add mail_thread widget to registry */
+ session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
/** mail_thread widget: thread of comments */
mail.RecordThread = session.web.form.AbstractField.extend({
- template: 'mail.RecordThread',
+ // QWeb template to use when rendering the object
+ template: 'mail.record_thread',
init: function() {
this._super.apply(this, arguments);
- this.see_subscribers = true;
- this.thread = null;
this.params = this.get_definition_options();
this.params.thread_level = this.params.thread_level || 0;
- // datasets
+ this.params.see_subscribers = true;
+ this.params.see_subscribers_options = this.params.see_subscribers_options || false;
+ this.thread = null;
this.ds = new session.web.DataSet(this, this.view.model);
this.ds_users = new session.web.DataSet(this, 'res.users');
},
start: function() {
- this._super.apply(this, arguments);
var self = this;
- // bind buttons
- this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); }).hide();
+ this._super.apply(this, arguments);
+ mail.ChatterUtils.bind_events(this);
+ this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); });
+ if (! this.params.see_subscribers_options) {
+ this.$element.find('button.oe_mail_button_followers').hide(); }
this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
.mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
.mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
@@ -530,7 +865,8 @@ openerp.mail = function(session) {
},
reinit: function() {
- this.see_subscribers = true;
+ this.params.see_subscribers = true;
+ this.params.see_subscribers_options = this.params.see_subscribers_options || false;
this.$element.find('button.oe_mail_button_followers').html('Hide followers')
this.$element.find('button.oe_mail_button_follow').hide();
this.$element.find('button.oe_mail_button_unfollow').hide();
@@ -548,11 +884,11 @@ openerp.mail = function(session) {
// fetch followers
var fetch_sub_done = this.fetch_subscribers();
// create and render Thread widget
- this.$element.find('div.oe_mail_recthread_left').empty();
+ this.$element.find('div.oe_mail_recthread_main').empty();
if (this.thread) this.thread.destroy();
this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
- 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
- var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_left'));
+ 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
+ var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_main'));
return fetch_sub_done && thread_done;
},
@@ -567,9 +903,8 @@ openerp.mail = function(session) {
this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
_(records).each(function (record) {
if (record.id == self.session.uid) { self.is_subscriber = true; }
- var mini_url = self.thread_get_avatar('res.users', 'avatar', record.id);
- $('
+
+
diff --git a/addons/mail/wizard/mail_compose_message.py b/addons/mail/wizard/mail_compose_message.py
index 1b19a383c10..d26511464f8 100644
--- a/addons/mail/wizard/mail_compose_message.py
+++ b/addons/mail/wizard/mail_compose_message.py
@@ -33,7 +33,7 @@ from ..mail_message import to_email
# main mako-like expression pattern
EXPRESSION_PATTERN = re.compile('(\$\{.+?\})')
-class mail_compose_message(osv.osv_memory):
+class mail_compose_message(osv.TransientModel):
"""Generic Email composition wizard. This wizard is meant to be inherited
at model and view level to provide specific wizard features.
@@ -41,13 +41,12 @@ class mail_compose_message(osv.osv_memory):
parameters, among which are:
* mail.compose.message.mode: if set to 'reply', the wizard is in
- reply mode and pre-populated with the original quote.
- If set to 'mass_mail', the wizard is in mass mailing
- where the mail details can contain template placeholders
- that will be merged with actual data before being sent
- to each recipient. Recipients will be derived from the
- records determined via ``context['active_model']`` and
- ``context['active_ids']``.
+ reply to a previous message mode and pre-populated with the original
+ quote. If set to 'comment', it means you are writing a new message to
+ be attached to a document. If set to 'mass_mail', the wizard is in
+ mass mailing where the mail details can contain template placeholders
+ that will be merged with actual data before being sent to each
+ recipient.
* active_model: model name of the document to which the mail being
composed is related
* active_id: id of the document to which the mail being composed is
@@ -61,119 +60,179 @@ class mail_compose_message(osv.osv_memory):
_description = 'Email composition wizard'
def default_get(self, cr, uid, fields, context=None):
- """Overridden to provide specific defaults depending on the context
- parameters.
+ """ Overridden to provide specific defaults depending on the context
+ parameters.
+
+ Composition mode
+ - comment: default mode; active_model, active_id = model and ID of a
+ document we are commenting,
+ - reply: active_id = ID of a mail.message to which we are replying.
+ From this message we can find the related model and res_id,
+ - mass_mailing mode: active_model, active_id = model and ID of a
+ document we are commenting,
:param dict context: several context values will modify the behavior
of the wizard, cfr. the class description.
"""
if context is None:
context = {}
+ compose_mode = context.get('mail.compose.message.mode', 'comment')
+ active_model = context.get('active_model')
+ active_id = context.get('active_id')
result = super(mail_compose_message, self).default_get(cr, uid, fields, context=context)
+
+ # get default values according to the composition mode
vals = {}
- reply_mode = context.get('mail.compose.message.mode') == 'reply'
- if (not reply_mode) and context.get('active_model') and context.get('active_id'):
- # normal mode when sending an email related to any document, as specified by
- # active_model and active_id in context
- vals = self.get_value(cr, uid, context.get('active_model'), context.get('active_id'), context)
- elif reply_mode and context.get('active_id'):
- # reply mode, consider active_id is the ID of a mail.message to which we're
- # replying
- vals = self.get_message_data(cr, uid, int(context['active_id']), context)
- else:
- # default mode
- result['model'] = context.get('active_model', False)
+ if compose_mode in ['reply']:
+ vals = self.get_message_data(cr, uid, int(context['active_id']), context=context)
+ elif compose_mode in ['comment', 'mass_mail'] and active_model and active_id:
+ vals = self.get_value(cr, uid, active_model, active_id, context)
for field in vals:
if field in fields:
- result.update({field : vals[field]})
+ result[field] = vals[field]
# link to model and record if not done yet
- if not result.get('model') or not result.get('res_id'):
- active_model = context.get('active_model')
- res_id = context.get('active_id')
- if active_model and active_model not in (self._name, 'mail.message'):
- result['model'] = active_model
- if res_id:
- result['res_id'] = res_id
+ if not result.get('model') and active_model:
+ result['model'] = active_model
+ if not result.get('res_id') and active_id:
+ result['res_id'] = active_id
# Try to provide default email_from if not specified yet
if not result.get('email_from'):
- current_user = self.pool.get('res.users').browse(cr, uid, uid, context)
+ current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
result['email_from'] = current_user.user_email or False
return result
_columns = {
+ 'dest_partner_ids': fields.many2many('res.partner',
+ 'email_message_send_partner_rel',
+ 'wizard_id', 'partner_id', 'Destination partners',
+ help="When sending emails through the social network composition wizard"\
+ "you may choose to send a copy of the mail to partners."),
'attachment_ids': fields.many2many('ir.attachment','email_message_send_attachment_rel', 'wizard_id', 'attachment_id', 'Attachments'),
'auto_delete': fields.boolean('Auto Delete', help="Permanently delete emails after sending"),
'filter_id': fields.many2one('ir.filters', 'Filters'),
}
def get_value(self, cr, uid, model, res_id, context=None):
- """Returns a defaults-like dict with initial values for the composition
- wizard when sending an email related to the document record identified
- by ``model`` and ``res_id``.
+ """ Returns a defaults-like dict with initial values for the composition
+ wizard when sending an email related to the document record
+ identified by ``model`` and ``res_id``.
- The default implementation returns an empty dictionary, and is meant
- to be overridden by subclasses.
+ The default implementation returns an empty dictionary, and is meant
+ to be overridden by subclasses.
- :param str model: model name of the document record this mail is related to.
- :param int res_id: id of the document record this mail is related to.
- :param dict context: several context values will modify the behavior
- of the wizard, cfr. the class description.
+ :param str model: model name of the document record this mail is
+ related to.
+ :param int res_id: id of the document record this mail is related to.
+ :param dict context: several context values will modify the behavior
+ of the wizard, cfr. the class description.
"""
- return {}
+ result = {}
+ user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
+ result.update({
+ 'model': model,
+ 'res_id': res_id,
+ 'email_from': user.user_email or tools.config.get('email_from', False),
+ 'body_html': False,
+ 'body_text': False,
+ 'subject': False,
+ 'dest_partner_ids': [],
+ })
+ return result
+
+ def onchange_email_mode(self, cr, uid, ids, value, model, res_id, context=None):
+ """ email_mode (values: True or False). This onchange on the email mode
+ allows to have some specific behavior when going in email mode, or
+ when going out of email mode.
+ Basically, dest_partner_ids is reset when going out of email
+ mode.
+ This method can be overridden for models that want to have their
+ specific behavior.
+ Note that currently, this onchange is used in mail.js and called
+ manually on the form instantiated in the Chatter.
+ """
+ if not value:
+ return {'value': {'dest_partner_ids': []}}
+ return {'value': {}}
+
+ def onchange_formatting(self, cr, uid, ids, value, model, res_id, context=None):
+ """ onchange_formatting (values: True or False). This onchange on the
+ formatting allows to have some specific behavior when going in
+ formatting mode, or when going out of formatting.
+ Basically, subject is reset when going out of formatting mode.
+ This method can be overridden for models that want to have their
+ specific behavior.
+ Note that currently, this onchange is used in mail.js and called
+ manually on the form instantiated in the Chatter.
+ """
+ if not value:
+ return {'value': {'subject': False}}
+ return {'value': {}}
def get_message_data(self, cr, uid, message_id, context=None):
- """Returns a defaults-like dict with initial values for the composition
- wizard when replying to the given message (e.g. including the quote
- of the initial message, and the correct recipient).
- Should not be called unless ``context['mail.compose.message.mode'] == 'reply'``.
+ """ Returns a defaults-like dict with initial values for the composition
+ wizard when replying to the given message (e.g. including the quote
+ of the initial message, and the correct recipient). It should not be
+ called unless ``context['mail.compose.message.mode'] == 'reply'``.
- :param int message_id: id of the mail.message to which the user
- is replying.
- :param dict context: several context values will modify the behavior
- of the wizard, cfr. the class description.
- When calling this method, the ``'mail'`` value
- in the context should be ``'reply'``.
+ :param int message_id: id of the mail.message to which the user
+ is replying.
+ :param dict context: several context values will modify the behavior
+ of the wizard, cfr. the class description.
"""
if context is None:
context = {}
result = {}
- mail_message = self.pool.get('mail.message')
- if message_id:
- message_data = mail_message.browse(cr, uid, message_id, context)
- subject = tools.ustr(message_data.subject or '')
- # we use the plain text version of the original mail, by default,
- # as it is easier to quote than the HTML version.
- # XXX TODO: make it possible to switch to HTML on the fly
- current_user = self.pool.get('res.users').browse(cr, uid, uid, context)
- body = message_data.body_text or current_user.signature or ''
- if context.get('mail.compose.message.mode') == 'reply':
- sent_date = _('On %(date)s, ') % {'date': message_data.date} if message_data.date else ''
- sender = _('%(sender_name)s wrote:') % {'sender_name': tools.ustr(message_data.email_from or _('You'))}
- quoted_body = '> %s' % tools.ustr(body.replace('\n', "\n> ") or '')
- body = '\n'.join(["\n", (sent_date + sender), quoted_body])
- body += "\n" + (current_user.signature or '')
- re_prefix = _("Re:")
- if not (subject.startswith('Re:') or subject.startswith(re_prefix)):
- subject = "%s %s" % (re_prefix, subject)
- result.update({
- 'subtype' : 'plain', # default to the text version due to quoting
- 'body_text' : body,
- 'subject' : subject,
- 'attachment_ids' : [],
- 'model' : message_data.model or False,
- 'res_id' : message_data.res_id or False,
- 'email_from' : current_user.user_email or message_data.email_to or False,
- 'email_to' : message_data.reply_to or message_data.email_from or False,
- 'email_cc' : message_data.email_cc or False,
- 'user_id' : uid,
+ if not message_id:
+ return result
- # pass msg-id and references of mail we're replying to, to construct the
- # new ones later when sending
- 'message_id' : message_data.message_id or False,
- 'references' : message_data.references and tools.ustr(message_data.references) or False,
- })
+ current_user = self.pool.get('res.users').browse(cr, uid, uid, context)
+ message_data = self.pool.get('mail.message').browse(cr, uid, message_id, context)
+ # Form the subject
+ re_prefix = _("Re:")
+ reply_subject = tools.ustr(message_data.subject or '')
+ if not (reply_subject.startswith('Re:') or reply_subject.startswith(re_prefix)):
+ reply_subject = "%s %s" % (re_prefix, reply_subject)
+ # Form the bodies (text and html). We use the plain text version of the
+ # original mail, by default, as it is easier to quote than the HTML
+ # version. TODO: make it possible to switch to HTML on the fly
+ sent_date = _('On %(date)s, ') % {'date': message_data.date} if message_data.date else ''
+ sender = _('%(sender_name)s wrote:') % {'sender_name': tools.ustr(message_data.email_from or _('You'))}
+ body_text = message_data.body_text or ''
+ body_html = message_data.body_html or ''
+ quoted_body_text = '> %s' % tools.ustr(body_text.replace('\n', "\n> ") or '')
+ quoted_body_html = '