1 openerp.mail = function(session) {
2 var _t = session.web._t,
5 var mail = session.mail = {};
8 * ------------------------------------------------------------
10 * ------------------------------------------------------------
12 * Override of formview do_action method, to catch all return action about
13 * mail.compose.message. The purpose is to bind 'Send by e-mail' buttons
14 * and redirect them to the Chatter.
17 session.web.FormView = session.web.FormView.extend({
18 do_action: function(action, on_close) {
19 if (action.res_model == 'mail.compose.message' && this.fields && this.fields.message_ids) {
20 var record_thread = this.fields.message_ids;
21 var thread = record_thread.thread;
22 thread.instantiate_composition_form('comment', true, false, 0, action.context);
26 return this._super(action, on_close);
33 * ------------------------------------------------------------
35 * ------------------------------------------------------------
37 * This class holds a few tools method that will be used by
38 * the various Chatter widgets.
44 * mail_int_mapping: structure to keep a trace of internal links mapping
45 * mail_int_mapping['model'] = {
46 * 'name_get': [[id,label], [id,label], ...]
47 * 'fetch_ids': [id, id, ...] } */
48 //var mail_int_mapping = {};
51 * mail_msg_struct: structure to orrganize chatter messages
53 //var mail_msg_struct = {}; // TODO: USE IT OR NOT :)
55 /* generic chatter events binding */
56 bind_events: function(widget) {
57 // event: click on an internal link to a document: model, login
58 widget.$element.delegate('a.oe_mail_internal_link', 'click', function (event) {
59 event.preventDefault();
60 // lazy implementation: fetch data and try to redirect
61 if (! event.srcElement.dataset.resModel) return false;
62 else var res_model = event.srcElement.dataset.resModel;
63 var res_login = event.srcElement.dataset.resLogin;
64 if (! res_login) return false;
65 var ds = new session.web.DataSet(widget, res_model);
66 var defer = ds.call('search', [[['login', '=', res_login]]]).pipe(function (records) {
68 widget.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
75 /** get an image in /web/binary/image?... */
76 get_image: function(session_prefix, session_id, model, field, id) {
77 return session_prefix + '/web/binary/image?session_id=' + session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
80 /** checks if tue current user is the message author */
81 is_author: function (widget, message_user_id) {
82 return (widget.session && widget.session.uid != 0 && widget.session.uid == message_user_id);
86 * Add records to comments_structure array
87 * @param {Array} records records from mail.message sorted by date desc
88 * @returns {Object} cs comments_structure: dict
89 * cs.model_to_root_ids = {model: [root_ids], }
90 * cs.new_root_ids = [new_root_ids]
91 * cs.root_ids = [root_ids]
92 * cs.msgs = {record.id: record,}
93 * cs.tree_struct = {record.id: {
94 * 'level': record_level in hierarchy, 0 is root,
95 * 'msg_nbr': number of childs,
96 * 'direct_childs': [msg_ids],
97 * 'all_childs': [msg_ids],
98 * 'for_thread_msgs': [records],
99 * 'ancestors': [msg_ids], } }
101 records_struct_add_records: function(cs, records, parent_id) {
102 var cur_iter = 0; var max_iter = 10; var modif = true;
103 while ( modif && (cur_iter++) < max_iter) {
105 _(records).each(function (record) {
106 // root and not yet recorded
107 if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
108 // add to model -> root_list ids
109 if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
110 else cs['model_to_root_ids'][record.model].push(record.id);
112 cs['new_root_ids'].push(record.id);
114 cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
115 cs['msgs'][record.id] = record;
118 // not yet recorded, but parent is recorded
119 else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
120 var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
121 // update parent structure
122 cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
123 cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
124 // update ancestors structure
125 for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
126 cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
129 cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
130 cs['msgs'][record.id] = record;
138 /* copy cs.new_root_ids into cs.root_ids */
139 records_struct_update_after_display: function(cs) {
141 cs['root_ids'] = _.union(cs['root_ids'], cs['new_root_ids']);
142 cs['new_root_ids'] = [];
147 * CONTENT MANIPULATION
149 * Regular expressions
150 * - (^|\s)@((\w|@|\.)*): @login@log.log, supports inner '@' for
151 * logins that are emails
154 * - (^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]: [ir.attachment,3|My Label],
155 * for internal links to model ir.attachment, id=3, and with
156 * optional label 'My Label'. Note that having a '|Label' is not
157 * mandatory, because the regex should still be correct.
165 /** Removes html tags, except b, em, br, ul, li */
166 do_text_remove_html_tags: function (string) {
167 var html = $('<div/>').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('<(/)?(b|em|br|br /|ul|li|div)\\s*>', 'gi'), '<$1$2>');
171 /** Replaces line breaks by html line breaks (br) */
172 do_text_nl2br: function (str, is_xhtml) {
173 var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
174 return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
177 /* Add a prefix before each new line of the original string */
178 do_text_quote: function (str, prefix) {
179 return str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2' + prefix || '> ');
183 * Replaces some expressions
184 * - @login - shorcut to link to a res.user, given its login
185 * - [ir.attachment,3|My Label] - shortcut to an internal
187 * - :name - shortcut to an image
189 do_replace_expressions: function (string) {
191 var icon_list = ['al', 'pinky']
192 /* shortcut to user: @login */
193 var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
194 var regex_res = regex_login.exec(string);
195 while (regex_res != null) {
196 var login = regex_res[2];
197 string = string.replace(regex_res[0], regex_res[1] + '<a href="#" class="oe_mail_internal_link" data-res-model="res.users" data-res-login = ' + login + '>@' + login + '</a>');
198 regex_res = regex_login.exec(string);
200 /* shortcut for internal document */
201 var regex_login = new RegExp(/(^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]/g);
202 var regex_res = regex_login.exec(string);
203 while (regex_res != null) {
204 var res_model = regex_res[2] + '.' + regex_res[3];
205 var res_id = regex_res[4];
206 if (! regex_res[5]) {
207 var label = res_model + ':' + res_id }
209 var label = regex_res[5];
211 string = string.replace(regex_res[0], regex_res[1] + '<a href="#model=' + res_model + '&id=' + res_id + '>' + label + '</a>');
212 regex_res = regex_login.exec(string);
214 /* special shortcut: :name, try to find an icon if in list */
215 var regex_login = new RegExp(/(^|\s):((\w)*)/g);
216 var regex_res = regex_login.exec(string);
217 while (regex_res != null) {
218 var icon_name = regex_res[2];
219 if (_.include(icon_list, icon_name))
220 string = string.replace(regex_res[0], regex_res[1] + '<img src="/mail/static/src/img/_' + icon_name + '.png" width="22px" height="22px" alt="' + icon_name + '"/>');
221 regex_res = regex_login.exec(string);
227 * Checks a string to find an expression that will be replaced
228 * by an internal link and requiring a name_get to replace
230 * :param mapping: structure to keep a trace of internal links mapping
231 * mapping['model'] = {
232 * name_get': [[id,label], [id,label], ...]
233 * 'to_fetch_ids': [id, id, ...]
235 * CURRENTLY NOT IMPLEMENTED */
236 do_check_for_name_get_mapping: function(string, mapping) {
237 /* shortcut to user: @login */
238 //var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
239 //var regex_res = regex_login.exec(string);
240 //while (regex_res != null) {
241 //var login = regex_res[2];
242 //if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
243 //this.map_hash['res.users']['login'].push(login);
244 //regex_res = regex_login.exec(string);
246 /* document link with name_get: [res.model,name] */
247 /* internal link with id: [res.model,id], or [res.model,id|display_name] */
248 //var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
249 //regex_res = regex_intlink.exec(string);
250 //while (regex_res != null) {
251 //var res_model = regex_res[2] + '.' + regex_res[3];
252 //var res_name = regex_res[4];
253 //if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
254 //this.map_hash[res_model]['name'].push(res_name);
255 //regex_res = regex_intlink.exec(string);
260 * Updates the mapping; check for to_fetch_ids for each recorded
261 * model, and perform a name_get to update the mapping.
262 * CURRENTLY NOT IMPLEMENTED */
263 do_update_name_get_mapping: function(mapping) {
269 * ------------------------------------------------------------
270 * ComposeMessage widget
271 * ------------------------------------------------------------
273 * This widget handles the display of a form to compose a new message.
274 * This form is an OpenERP form_view, build on a mail.compose.message
278 mail.ComposeMessage = session.web.Widget.extend({
279 template: 'mail.compose_message',
282 * @param {Object} parent parent
283 * @param {Object} [params]
284 * @param {String} [params.res_model] res_model of document [REQUIRED]
285 * @param {Number} [params.res_id] res_id of record [REQUIRED]
286 * @param {Number} [params.email_mode] true/false, tells whether
287 * we are in email sending mode
288 * @param {Number} [params.formatting] true/false, tells whether
289 * we are in advance formatting mode
290 * @param {String} [params.model] mail.compose.message.mode (see
291 * composition wizard)
292 * @param {Number} [params.msg_id] id of a message in case we are in
295 init: function(parent, params) {
299 this.params = params || {};
300 this.params.context = params.context || {};
301 this.params.email_mode = params.email_mode || false;
302 this.params.formatting = params.formatting || false;
303 this.params.mode = params.mode || 'comment';
304 this.params.form_xml_id = params.form_xml_id || 'email_compose_message_wizard_form_chatter';
305 this.params.form_view_id = false;
306 if (this.params.mode == 'reply') {
307 this.params.active_id = this.params.msg_id;
309 this.params.active_id = this.params.res_id;
311 this.email_mode = false;
312 this.formatting = false;
316 * Reinitialize the widget field values to the default values. The
317 * purpose is to avoid to destroy and re-build a form view. Default
318 * values are therefore given as for an onchange. */
321 if (! this.form_view) return;
322 var call_defer = this.ds_compose.call('default_get', [['subject', 'body_text', 'body_html', 'dest_partner_ids'], this.ds_compose.get_context()]).then(
324 self.form_view.on_processed_onchange({'value': result}, []);
330 * Override-hack of do_action: clean the form */
331 do_action: function(action, on_close) {
332 // this.init_comments();
333 return this._super(action, on_close);
337 * Widget start function
338 * - builds and initializes the form view */
341 this._super.apply(this, arguments);
342 // customize display: add avatar, clean previous content
343 var user_avatar = mail.ChatterUtils.get_image(this.session.prefix,
344 this.session.session_id, 'res.users', 'avatar', this.session.uid);
345 this.$element.find('img.oe_mail_icon').attr('src', user_avatar);
346 this.$element.find('div.oe_mail_msg_content').empty();
347 // create a context for the default_get of the compose form
348 var widget_context = {
349 'active_model': this.params.res_model,
350 'active_id': this.params.active_id,
351 'mail.compose.message.mode': this.params.mode,
353 var context = _.extend({}, this.params.context, widget_context);
354 this.ds_compose = new session.web.DataSetSearch(this, 'mail.compose.message', context);
355 // find the id of the view to display in the chatter form
356 var data_ds = new session.web.DataSetSearch(this, 'ir.model.data');
357 var deferred_form_id =data_ds.call('get_object_reference', ['mail', this.params.form_xml_id]).then( function (result) {
359 self.params.form_view_id = result[1];
361 }).pipe(this.proxy('create_form_view'));
362 return deferred_form_id;
366 * Create a FormView, then append it to the to widget DOM. */
367 create_form_view: function () {
369 // destroy previous form_view if any
370 if (this.form_view) { this.form_view.destroy(); }
371 // create the FormView
372 this.form_view = new session.web.FormView(this, this.ds_compose, this.params.form_view_id, {
373 action_buttons: false,
375 initial_mode: 'edit',
377 // add the form, bind events, activate the form
378 var msg_node = this.$element.find('div.oe_mail_msg_content');
379 return $.when(this.form_view.appendTo(msg_node)).pipe(function() {
381 self.form_view.do_show();
382 if (self.params.email_mode) { self.toggle_email_mode(); }
383 if (self.params.formatting) { self.toggle_formatting_mode(); }
387 destroy: function() {
388 this._super.apply(this, arguments);
392 * Bind events in the widget. Each event is slightly described
393 * in the function. */
394 bind_events: function() {
396 this.$element.find('button.oe_form_button').click(function (event) {
397 event.preventDefault();
399 // event: click on 'Send an Email' link that toggles the form for
400 // sending an email (partner_ids)
401 this.$element.find('a.oe_mail_compose_message_email').click(function (event) {
402 event.preventDefault();
403 self.toggle_email_mode();
405 // event: click on 'Formatting' icon-link that toggles the advanced
406 // formatting options for writing a message (subject, body_html)
407 this.$element.find('a.oe_mail_compose_message_formatting').click(function (event) {
408 event.preventDefault();
409 self.toggle_formatting_mode();
411 // event: click on 'Attachment' icon-link that opens the dialog to
412 // add an attachment.
413 this.$element.find('a.oe_mail_compose_message_attachment').click(function (event) {
414 event.preventDefault();
415 // not yet implemented
416 self.set_body_value('attachment', 'attachment');
418 // event: click on 'Checklist' icon-link that toggles the options
419 // for adding checklist.
420 this.$element.find('a.oe_mail_compose_message_checklist').click(function (event) {
421 event.preventDefault();
422 // not yet implemented
423 self.set_body_value('checklist', 'checklist');
428 * Toggle the formatting mode. */
429 toggle_formatting_mode: function() {
431 this.formatting = ! this.formatting;
433 var call_defer = this.ds_compose.call('onchange_formatting', [[], this.formatting, this.params.res_model, this.params.res_id]).then(
435 self.form_view.on_processed_onchange(result, []);
437 // update context of datasetsearch
438 this.ds_compose.context.formatting = this.formatting;
440 this.$element.find('span.oe_mail_compose_message_subject').toggleClass('oe_mail_compose_message_invisible');
441 this.$element.find('div.oe_mail_compose_message_body_text').toggleClass('oe_mail_compose_message_invisible');
442 this.$element.find('div.oe_mail_compose_message_body_html').toggleClass('oe_mail_compose_message_invisible');
446 * Toggle the email mode. */
447 toggle_email_mode: function() {
449 this.email_mode = ! this.email_mode;
451 var call_defer = this.ds_compose.call('onchange_email_mode', [[], this.email_mode, this.params.res_model, this.params.res_id]).then(
453 self.form_view.on_processed_onchange(result, []);
455 // update context of datasetsearch
456 this.ds_compose.context.email_mode = this.email_mode;
457 // update 'Post' button -> 'Send'
458 // update 'Send an Email' link -> 'Post a comment'
459 if (this.email_mode) {
460 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Send</span>');
461 this.$element.find('a.oe_mail_compose_message_email').html('Comment');
463 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Post</span>');
464 this.$element.find('a.oe_mail_compose_message_email').html('Send an Email');
467 this.$element.find('div.oe_mail_compose_message_partner_ids').toggleClass('oe_mail_compose_message_invisible');
471 * Update the values of the composition form; with possible different
472 * values for body_text and body_html. */
473 set_body_value: function(body_text, body_html) {
474 this.form_view.fields.body_text.set_value(body_text);
475 this.form_view.fields.body_html.set_value(body_html);
480 * ------------------------------------------------------------
482 * ------------------------------------------------------------
484 * This widget handles the display of a thread of messages. The
485 * [thread_level] parameter sets the thread level number:
487 * - - sub message (parent_id = root message)
488 * - - - sub sub message (parent id = sub message)
489 * - - sub message (parent_id = root message)
490 * This widget has 2 ways of initialization, either you give records
491 * to be rendered, either it will fetch [limit] messages related to
492 * [res_model]:[res_id].
495 mail.Thread = session.web.Widget.extend({
496 template: 'mail.thread',
499 * @param {Object} parent parent
500 * @param {Object} [params]
501 * @param {String} [params.res_model] res_model of document [REQUIRED]
502 * @param {Number} [params.res_id] res_id of record [REQUIRED]
503 * @param {Number} [params.uid] user id [REQUIRED]
504 * @param {Bool} [params.parent_id=false] parent_id of message
505 * @param {Number} [params.thread_level=0] number of levels in the thread
506 * (only 0 or 1 currently)
507 * @param {Bool} [params.is_wall=false] thread is displayed in the wall
508 * @param {Number} [params.msg_more_limit=150] number of character to
509 * display before having a "show more" link; note that the text
510 * will not be truncated if it does not have 110% of the parameter
511 * (ex: 110 characters needed to be truncated and be displayed as
512 * a 100-characters message)
513 * @param {Number} [params.limit=100] maximum number of messages to fetch
514 * @param {Number} [params.offset=0] offset for fetching messages
515 * @param {Number} [params.records=null] records to show instead of fetching messages
517 init: function(parent, params) {
520 this.params = params;
521 this.params.parent_id = this.params.parent_id || false;
522 this.params.thread_level = this.params.thread_level || 0;
523 this.params.is_wall = this.params.is_wall || (this.params.records != undefined) || false;
524 this.params.msg_more_limit = this.params.msg_more_limit || 250;
525 this.params.limit = this.params.limit || 100;
526 // this.params.limit = 3; // tmp for testing
527 this.params.offset = this.params.offset || 0;
528 this.params.records = this.params.records || null;
529 // datasets and internal vars
530 this.ds = new session.web.DataSetSearch(this, this.params.res_model);
531 this.ds_users = new session.web.DataSetSearch(this, 'res.users');
532 this.ds_msg = new session.web.DataSetSearch(this, 'mail.message');
533 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
534 // display customization vars
536 this.display.show_post_comment = this.params.show_post_comment || false;
537 this.display.show_reply = (this.params.thread_level > 0 && this.params.is_wall);
538 this.display.show_delete = ! this.params.is_wall;
539 this.display.show_hide = this.params.is_wall;
540 this.display.show_reply_by_email = ! this.params.is_wall;
541 this.display.show_more = (this.params.thread_level == 0);
545 this._super.apply(this, arguments);
548 // display user, fetch comments
549 this.display_current_user();
550 if (this.params.records) var display_done = this.display_comments_from_parameters(this.params.records);
551 else var display_done = this.init_comments();
553 $.when(display_done).then(this.proxy('do_customize_display'));
554 // add message composition form view
555 if (this.display.show_post_comment) {
556 var compose_done = this.instantiate_composition_form();
558 return display_done && compose_done;
562 * Override-hack of do_action: automatically reload the chatter.
563 * Normally it should be called only when clicking on 'Post/Send'
564 * in the composition form. */
565 do_action: function(action, on_close) {
566 this.init_comments();
567 if (this.compose_message_widget) {
568 this.compose_message_widget.reinit(); }
569 return this._super(action, on_close);
572 instantiate_composition_form: function(mode, email_mode, formatting, msg_id, context) {
573 if (this.compose_message_widget) {
574 this.compose_message_widget.destroy();
576 this.compose_message_widget = new mail.ComposeMessage(this, {
577 'extended_mode': false, 'uid': this.params.uid, 'res_model': this.params.res_model,
578 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id,
579 'email_mode': email_mode || false, 'formatting': formatting || false,
580 'context': context || false } );
581 var composition_node = this.$element.find('div.oe_mail_thread_action');
582 composition_node.empty();
583 var compose_done = this.compose_message_widget.appendTo(composition_node);
587 do_customize_display: function() {
588 if (this.display.show_post_comment) { this.$element.find('div.oe_mail_thread_action').eq(0).show(); }
592 * Bind events in the widget. Each event is slightly described
593 * in the function. */
594 bind_events: function() {
596 // generic events from Chatter Mixin
597 mail.ChatterUtils.bind_events(this);
598 // event: click on 'more' at bottom of thread
599 this.$element.find('button.oe_mail_button_more').click(function () {
602 // event: writing in basic textarea of composition form (quick reply)
603 this.$element.find('textarea.oe_mail_compose_textarea').keyup(function (event) {
604 var charCode = (event.which) ? event.which : window.event.keyCode;
605 if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
606 else if (charCode == 13) { return self.do_comment(); }
608 // event: click on 'Reply' in msg
609 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
610 var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
612 event.preventDefault();
614 // event: click on 'attachment(s)' in msg
615 this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
616 var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
618 event.preventDefault();
620 // event: click on 'Delete' in msg side menu
621 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
622 if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
623 var msg_id = event.srcElement.dataset.id;
624 if (! msg_id) return false;
625 var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
626 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
627 if (self.params.thread_level > 0) {
628 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
630 event.preventDefault();
633 // event: click on 'Hide' in msg side menu
634 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
635 if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
636 var msg_id = event.srcElement.dataset.id;
637 if (! msg_id) return false;
638 var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
639 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
640 if (self.params.thread_level > 0) {
641 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
643 event.preventDefault();
646 // event: click on "Reply" in msg side menu (email style)
647 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply_by_email', 'click', function (event) {
648 var msg_id = event.srcElement.dataset.msg_id;
649 var email_mode = (event.srcElement.dataset.type == 'email');
650 var formatting = (event.srcElement.dataset.formatting == 'html');
651 if (! msg_id) return false;
652 self.instantiate_composition_form('reply', email_mode, formatting, msg_id);
653 event.preventDefault();
657 destroy: function () {
658 this._super.apply(this, arguments);
661 init_comments: function() {
663 this.params.offset = 0;
664 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
665 this.$element.find('div.oe_mail_thread_display').empty();
666 var domain = this.get_fetch_domain(this.comments_structure);
667 return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
670 fetch_comments: function (limit, offset, domain) {
672 var defer = this.ds.call('message_read', [[this.params.res_id], (this.params.thread_level > 0), (this.comments_structure['root_ids']),
673 (limit+1) || (this.params.limit+1), offset||this.params.offset, domain||undefined ]).then(function (records) {
674 if (records.length <= self.params.limit) self.display.show_more = false;
675 // else { self.display.show_more = true; records.pop(); }
676 // else { self.display.show_more = true; records.splice(0, 1); }
677 else { self.display.show_more = true; }
678 self.display_comments(records);
679 // TODO: move to customize display
680 if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
681 else self.$element.find('div.oe_mail_thread_more:last').hide();
687 display_comments_from_parameters: function (records) {
688 if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
689 else this.display.show_more = false;
690 var defer = this.display_comments(records);
691 // TODO: move to customize display
692 if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
693 else $('div.oe_mail_thread_more').eq(-2).hide();
697 display_comments: function (records) {
700 mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, this.params.parent_id);
701 //build attachments download urls and compute time-relative from dates
702 for (var k in records) {
703 records[k].timerelative = $.timeago(records[k].date);
704 if (records[k].attachments) {
705 for (var l in records[k].attachments) {
706 var url = self.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=datas_fname&id='+records[k].attachments[l].id;
707 records[k].attachments[l].url = url;
711 _(records).each(function (record) {
713 if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
714 var sub_list = self.comments_structure['tree_struct'][record.id]['direct_childs'];
715 _(records).each(function (record) {
716 //if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
717 if (_.indexOf(sub_list, record.id) != -1) {
718 sub_msgs.push(record);
721 self.display_comment(record);
722 self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
723 'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id,
724 'is_wall': self.params.is_wall});
725 self.$element.find('li.oe_mail_thread_msg:last').append('<div class="oe_mail_thread_subthread"/>');
726 self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
728 else if (self.params.thread_level == 0) {
729 self.display_comment(record);
732 mail.ChatterUtils.records_struct_update_after_display(this.comments_structure);
733 // update offset for "More" buttons
734 if (this.params.thread_level == 0) this.params.offset += records.length;
737 /** Displays a record, performs text/link formatting */
738 display_comment: function (record) {
739 record.body = mail.ChatterUtils.do_text_nl2br(record.body, true);
740 // if (record.type == 'email' && record.state == 'received') {
741 if (record.type == 'email') {
742 record.mini_url = ('/mail/static/src/img/email_icon.png');
744 record.mini_url = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'avatar', record.user_id[0]);
746 // body text manipulation
747 if (record.subtype == 'plain') {
748 record.body = mail.ChatterUtils.do_text_remove_html_tags(record.body);
750 record.body = mail.ChatterUtils.do_replace_expressions(record.body);
751 // format date according to the user timezone
752 record.date = session.web.format_value(record.date, {type:"datetime"});
753 // is the user the author ?
754 record.is_author = mail.ChatterUtils.is_author(this, record.user_id[0]);
756 var rendered = session.web.qweb.render('mail.thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
757 $(rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
759 this.$element.find('div.oe_mail_msg_body:last').expander({
760 slicePoint: this.params.msg_more_limit,
761 expandText: 'read more',
762 userCollapseText: '[^]',
763 detailClass: 'oe_mail_msg_tail',
764 moreClass: 'oe_mail_expand',
765 lessClass: 'oe_mail_reduce',
769 display_current_user: function () {
770 var avatar = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'avatar', this.params.uid);
771 return this.$element.find('img.oe_mail_icon').attr('src', avatar);
774 do_comment: function () {
775 var comment_node = this.$element.find('textarea');
776 var body_text = comment_node.val();
777 comment_node.val('');
778 return this.ds.call('message_append_note', [[this.params.res_id], '', body_text, this.params.parent_id, 'comment', 'plain']).then(
779 this.proxy('init_comments'));
783 * Create a domain to fetch new comments according to
784 * comment already present in comments_structure
785 * @param {Object} comments_structure (see chatter utils)
786 * @returns {Array} fetch_domain (OpenERP domain style)
788 get_fetch_domain: function (comments_structure) {
790 var ids = comments_structure.root_ids.slice();
792 // must be child of current parent
793 if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
794 _(comments_structure.root_ids).each(function (id) { // each record
798 if (this.params.parent_id != false) {
799 ids2.push(this.params.parent_id);
801 // must not be children of already fetched messages
802 if (ids.length > 0) {
805 domain.push(['id', 'child_of', ids]);
807 if (ids2.length > 0) {
808 domain.push(['id', 'not in', ids2]);
813 do_more: function () {
814 domain = this.get_fetch_domain(this.comments_structure);
815 return this.fetch_comments(this.params.limit, this.params.offset, domain);
821 * ------------------------------------------------------------
823 * ------------------------------------------------------------
825 * This widget handles the display of the Chatter on documents.
828 /* Add mail_thread widget to registry */
829 session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
831 /** mail_thread widget: thread of comments */
832 mail.RecordThread = session.web.form.AbstractField.extend({
833 // QWeb template to use when rendering the object
834 template: 'mail.record_thread',
837 this._super.apply(this, arguments);
838 this.params = this.get_definition_options();
839 this.params.thread_level = this.params.thread_level || 0;
840 this.params.see_subscribers = true;
841 this.params.see_subscribers_options = this.params.see_subscribers_options || false;
843 this.ds = new session.web.DataSet(this, this.view.model);
844 this.ds_users = new session.web.DataSet(this, 'res.users');
850 // NB: all the widget should be modified to check the actual_mode property on view, not use
851 // any other method to know if the view is in create mode anymore
852 this.view.on("change:actual_mode", this, this._check_visibility);
853 this._check_visibility();
855 mail.ChatterUtils.bind_events(this);
856 this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); });
857 if (! this.params.see_subscribers_options) {
858 this.$element.find('button.oe_mail_button_followers').hide(); }
859 this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
860 .mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
861 .mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
862 this.$element.find('button.oe_mail_button_unfollow').click(function () { self.do_unfollow(); })
863 .mouseover(function () { $(this).html('Unfollow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
864 .mouseleave(function () { $(this).html('Following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
868 _check_visibility: function() {
869 this.$element.toggle(this.view.get("actual_mode") !== "create");
872 destroy: function () {
873 this._super.apply(this, arguments);
877 this.params.see_subscribers = true;
878 this.params.see_subscribers_options = this.params.see_subscribers_options || false;
879 this.$element.find('button.oe_mail_button_followers').html('Hide followers')
880 this.$element.find('button.oe_mail_button_follow').hide();
881 this.$element.find('button.oe_mail_button_unfollow').hide();
884 set_value: function() {
885 this._super.apply(this, arguments);
888 if (! this.view.datarecord.id ||
889 session.web.BufferedDataSet.virtual_id_regex.test(this.view.datarecord.id)) {
890 this.$element.find('.oe_mail_thread').hide();
894 var fetch_sub_done = this.fetch_subscribers();
895 // create and render Thread widget
896 this.$element.find('div.oe_mail_recthread_main').empty();
897 if (this.thread) this.thread.destroy();
898 this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
899 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
900 var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_main'));
901 return fetch_sub_done && thread_done;
904 fetch_subscribers: function () {
905 return this.ds.call('message_read_subscribers', [[this.view.datarecord.id]]).then(this.proxy('display_subscribers'));
908 display_subscribers: function (records) {
910 this.is_subscriber = false;
911 var user_list = this.$element.find('ul.oe_mail_followers_display').empty();
912 this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
913 _(records).each(function (record) {
914 if (record.id == self.session.uid) { self.is_subscriber = true; }
915 record.avatar_url = mail.ChatterUtils.get_image(self.session.prefix, self.session.session_id, 'res.users', 'avatar', record.id);
916 $(session.web.qweb.render('mail.record_thread.subscriber', {'record': record})).appendTo(user_list);
918 if (self.is_subscriber) {
919 self.$element.find('button.oe_mail_button_follow').hide();
920 self.$element.find('button.oe_mail_button_unfollow').show(); }
922 self.$element.find('button.oe_mail_button_follow').show();
923 self.$element.find('button.oe_mail_button_unfollow').hide(); }
926 do_follow: function () {
927 return this.ds.call('message_subscribe', [[this.view.datarecord.id]]).pipe(this.proxy('fetch_subscribers'));
930 do_unfollow: function () {
932 return this.ds.call('message_unsubscribe', [[this.view.datarecord.id]]).then(function (record) {
933 if (record == false) self.do_notify("Impossible to unsubscribe", "You are automatically subscribed to this record. You cannot unsubscribe.");
934 }).pipe(this.proxy('fetch_subscribers'));
937 do_toggle_followers: function () {
938 this.params.see_subscribers = ! this.params.see_subscribers;
939 if (this.params.see_subscribers) { this.$element.find('button.oe_mail_button_followers').html('Hide followers'); }
940 else { this.$element.find('button.oe_mail_button_followers').html('Show followers'); }
941 this.$element.find('div.oe_mail_recthread_followers').toggle();
947 * ------------------------------------------------------------
949 * ------------------------------------------------------------
951 * This widget handles the display of the Chatter on the Wall.
954 /* Add WallView widget to registry */
955 session.web.client_actions.add('mail.wall', 'session.mail.Wall');
957 /* WallView widget: a wall of messages */
958 mail.Wall = session.web.Widget.extend({
959 template: 'mail.wall',
962 * @param {Object} parent parent
963 * @param {Object} [params]
964 * @param {Number} [params.limit=20] number of messages to show and fetch
965 * @param {Number} [params.search_view_id=false] search view id for messages
966 * @var {Array} comments_structure (see chatter utils)
968 init: function (parent, params) {
971 this.params.limit = params.limit || 25;
972 this.params.domain = params.domain || [];
973 this.params.context = params.context || {};
974 this.params.search_view_id = params.search_view_id || false;
975 this.params.thread_level = params.thread_level || 1;
976 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
977 this.display_show_more = true;
978 this.thread_list = [];
979 this.search = {'domain': [], 'context': {}, 'groupby': {}}
980 this.search_results = {'domain': [], 'context': {}, 'groupby': {}}
982 this.ds_msg = new session.web.DataSet(this, 'mail.message');
983 this.ds_thread = new session.web.DataSet(this, 'mail.thread');
984 this.ds_users = new session.web.DataSet(this, 'res.users');
988 this._super.apply(this, arguments);
989 this.display_current_user();
991 this.add_event_handlers();
992 // load mail.message search view
993 var search_view_ready = this.load_search_view(this.params.search_view_id, {}, false);
994 // load composition form
995 var compose_done = this.instantiate_composition_form();
996 // fetch first threads
997 var comments_ready = this.init_and_fetch_comments(this.params.limit, 0);
998 return (search_view_ready && comments_ready && compose_done);
1002 * Override-hack of do_action: automatically reload the chatter.
1003 * Normally it should be called only when clicking on 'Post/Send'
1004 * in the composition form. */
1005 do_action: function(action, on_close) {
1006 this.init_and_fetch_comments();
1007 if (this.compose_message_widget) {
1008 this.compose_message_widget.reinit(); }
1009 return this._super(action, on_close);
1012 destroy: function () {
1013 this._super.apply(this, arguments);
1016 instantiate_composition_form: function(mode, msg_id) {
1017 if (this.compose_message_widget) {
1018 this.compose_message_widget.destroy();
1020 this.compose_message_widget = new mail.ComposeMessage(this, {
1021 'extended_mode': false, 'uid': this.session.uid, 'res_model': 'res.users',
1022 'res_id': this.session.uid, 'mode': mode || 'comment', 'msg_id': msg_id });
1023 var composition_node = this.$element.find('div.oe_mail_wall_action');
1024 composition_node.empty();
1025 var compose_done = this.compose_message_widget.appendTo(composition_node);
1026 return compose_done;
1030 add_event_handlers: function () {
1032 // display more threads
1033 this.$element.find('button.oe_mail_wall_button_more').click(function () { return self.do_more(); });
1037 * Loads the mail.message search view
1038 * @param {Number} view_id id of the search view to load
1039 * @param {Object} defaults ??
1040 * @param {Boolean} hidden some kind of trick we do not care here
1042 load_search_view: function (view_id, defaults, hidden) {
1044 this.searchview = new session.web.SearchView(this, this.ds_msg, view_id || false, defaults || {}, hidden || false);
1045 var search_view_loaded = this.searchview.appendTo(this.$element.find('.oe_view_manager_view_search'));
1046 return $.when(search_view_loaded).then(function () {
1047 self.searchview.on_search.add(self.do_searchview_search);
1052 * Aggregate the domains, contexts and groupbys in parameter
1053 * with those from search form, and then calls fetch_comments
1054 * to actually fetch comments
1055 * @param {Array} domains
1056 * @param {Array} contexts
1057 * @param {Array} groupbys
1059 do_searchview_search: function(domains, contexts, groupbys) {
1061 this.rpc('/web/session/eval_domain_and_context', {
1062 domains: domains || [],
1063 contexts: contexts || [],
1064 group_by_seq: groupbys || []
1065 }, function (results) {
1066 self.search_results['context'] = results.context;
1067 self.search_results['domain'] = results.domain;
1068 self.search_results['groupby'] = results.group_by;
1069 return self.init_and_fetch_comments();
1073 display_current_user: function () {
1074 //return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'avatar', this.session.uid));
1078 * Initializes the wall and calls fetch_comments
1079 * @param {Number} limit: number of notifications to fetch
1080 * @param {Number} offset: offset in notifications search
1081 * @param {Array} domain
1082 * @param {Array} context
1084 init_and_fetch_comments: function() {
1085 this.search['domain'] = _.union(this.params.domain, this.search_results.domain);
1086 this.search['context'] = _.extend(this.params.context, this.search_results.context);
1087 this.display_show_more = true;
1088 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
1089 this.$element.find('ul.oe_mail_wall_threads').empty();
1090 return this.fetch_comments(this.params.limit, 0);
1094 * Fetches wall messages
1095 * @param {Number} limit: number of notifications to fetch
1096 * @param {Number} offset: offset in notifications search
1097 * @param {Array} domain
1098 * @param {Array} context
1100 fetch_comments: function (limit, offset, additional_domain, additional_context) {
1102 if (additional_domain) var fetch_domain = this.search['domain'].concat(additional_domain);
1103 else var fetch_domain = this.search['domain'];
1104 if (additional_context) var fetch_context = _.extend(this.search['context'], additional_context);
1105 else var fetch_context = this.search['context'];
1106 return this.ds_thread.call('message_get_pushed_messages',
1107 [[this.session.uid], true, [], (limit || 0), (offset || 0), fetch_domain, fetch_context]).then(this.proxy('display_comments'));
1111 * @param {Array} records records to show in threads
1113 display_comments: function (records) {
1115 this.do_update_show_more(records.length >= self.params.limit);
1116 mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, false);
1117 _(this.comments_structure['new_root_ids']).each(function (root_id) {
1118 var records = self.comments_structure.tree_struct[root_id]['for_thread_msgs'];
1119 var model_name = self.comments_structure.msgs[root_id]['model'];
1120 var res_id = self.comments_structure.msgs[root_id]['res_id'];
1121 var render_res = session.web.qweb.render('mail.wall_thread_container', {});
1122 $('<li class="oe_mail_wall_thread">').html(render_res).appendTo(self.$element.find('ul.oe_mail_wall_threads'));
1123 var thread = new mail.Thread(self, {
1124 'res_model': model_name, 'res_id': res_id, 'uid': self.session.uid, 'records': records,
1125 'parent_id': false, 'thread_level': self.params.thread_level, 'show_hide': true, 'is_wall': true}
1127 self.thread_list.push(thread);
1128 return thread.appendTo(self.$element.find('li.oe_mail_wall_thread:last'));
1131 this.comments_structure['root_ids'] = _.union(this.comments_structure['root_ids'], this.comments_structure['new_root_ids']);
1132 this.comments_structure['new_root_ids'] = [];
1136 * Create a domain to fetch new comments according to
1137 * comments already present in comments_structure
1139 * -- should not be child of already displayed ids
1140 * @returns {Array} fetch_domain (OpenERP domain style)
1142 get_fetch_domain: function () {
1144 var model_to_root = {};
1145 var fetch_domain = [];
1146 _(this.comments_structure['model_to_root_ids']).each(function (sc_model, model_name) {
1147 fetch_domain.push('|', ['model', '!=', model_name], '!', ['id', 'child_of', sc_model]);
1149 return fetch_domain;
1152 /** Display update: show more button */
1153 do_update_show_more: function (new_value) {
1154 if (new_value != undefined) this.display_show_more = new_value;
1155 if (this.display_show_more) this.$element.find('div.oe_mail_wall_more:last').show();
1156 else this.$element.find('div.oe_mail_wall_more:last').hide();
1159 /** Action: Shows more discussions */
1160 do_more: function () {
1161 var domain = this.get_fetch_domain();
1162 return this.fetch_comments(this.params.limit, 0, domain);