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 && this.fields.message_ids.view.get("actual_mode") != 'create') {
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', 'image_small', 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',
376 disable_autofocus: true,
378 // add the form, bind events, activate the form
379 var msg_node = this.$element.find('div.oe_mail_msg_content');
380 return $.when(this.form_view.appendTo(msg_node)).pipe(function() {
382 self.form_view.do_show();
383 if (self.params.email_mode) { self.toggle_email_mode(); }
384 if (self.params.formatting) { self.toggle_formatting_mode(); }
388 destroy: function() {
389 this._super.apply(this, arguments);
393 * Bind events in the widget. Each event is slightly described
394 * in the function. */
395 bind_events: function() {
397 this.$element.find('button.oe_form_button').click(function (event) {
398 event.preventDefault();
400 // event: click on 'Send an Email' link that toggles the form for
401 // sending an email (partner_ids)
402 this.$element.find('a.oe_mail_compose_message_email').click(function (event) {
403 event.preventDefault();
404 self.toggle_email_mode();
406 // event: click on 'Formatting' icon-link that toggles the advanced
407 // formatting options for writing a message (subject, body_html)
408 this.$element.find('a.oe_mail_compose_message_formatting').click(function (event) {
409 event.preventDefault();
410 self.toggle_formatting_mode();
412 // event: click on 'Attachment' icon-link that opens the dialog to
413 // add an attachment.
414 this.$element.find('a.oe_mail_compose_message_attachment').click(function (event) {
415 event.preventDefault();
416 // not yet implemented
417 self.set_body_value('attachment', 'attachment');
419 // event: click on 'Checklist' icon-link that toggles the options
420 // for adding checklist.
421 this.$element.find('a.oe_mail_compose_message_checklist').click(function (event) {
422 event.preventDefault();
423 // not yet implemented
424 self.set_body_value('checklist', 'checklist');
429 * Toggle the formatting mode. */
430 toggle_formatting_mode: function() {
432 this.formatting = ! this.formatting;
434 var call_defer = this.ds_compose.call('onchange_formatting', [[], this.formatting, this.params.res_model, this.params.res_id]).then(
436 self.form_view.on_processed_onchange(result, []);
438 // update context of datasetsearch
439 this.ds_compose.context.formatting = this.formatting;
441 this.$element.find('span.oe_mail_compose_message_subject').toggleClass('oe_mail_compose_message_invisible');
442 this.$element.find('div.oe_mail_compose_message_body_text').toggleClass('oe_mail_compose_message_invisible');
443 this.$element.find('div.oe_mail_compose_message_body_html').toggleClass('oe_mail_compose_message_invisible');
447 * Toggle the email mode. */
448 toggle_email_mode: function() {
450 this.email_mode = ! this.email_mode;
452 var call_defer = this.ds_compose.call('onchange_email_mode', [[], this.email_mode, this.params.res_model, this.params.res_id]).then(
454 self.form_view.on_processed_onchange(result, []);
456 // update context of datasetsearch
457 this.ds_compose.context.email_mode = this.email_mode;
458 // update 'Post' button -> 'Send'
459 // update 'Send an Email' link -> 'Post a comment'
460 if (this.email_mode) {
461 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Send</span>');
462 this.$element.find('a.oe_mail_compose_message_email').html('Comment');
464 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Post</span>');
465 this.$element.find('a.oe_mail_compose_message_email').html('Send an Email');
468 this.$element.find('div.oe_mail_compose_message_partner_ids').toggleClass('oe_mail_compose_message_invisible');
472 * Update the values of the composition form; with possible different
473 * values for body_text and body_html. */
474 set_body_value: function(body_text, body_html) {
475 this.form_view.fields.body_text.set_value(body_text);
476 this.form_view.fields.body_html.set_value(body_html);
481 * ------------------------------------------------------------
483 * ------------------------------------------------------------
485 * This widget handles the display of a thread of messages. The
486 * [thread_level] parameter sets the thread level number:
488 * - - sub message (parent_id = root message)
489 * - - - sub sub message (parent id = sub message)
490 * - - sub message (parent_id = root message)
491 * This widget has 2 ways of initialization, either you give records
492 * to be rendered, either it will fetch [limit] messages related to
493 * [res_model]:[res_id].
496 mail.Thread = session.web.Widget.extend({
497 template: 'mail.thread',
500 * @param {Object} parent parent
501 * @param {Object} [params]
502 * @param {String} [params.res_model] res_model of document [REQUIRED]
503 * @param {Number} [params.res_id] res_id of record [REQUIRED]
504 * @param {Number} [params.uid] user id [REQUIRED]
505 * @param {Bool} [params.parent_id=false] parent_id of message
506 * @param {Number} [params.thread_level=0] number of levels in the thread
507 * (only 0 or 1 currently)
508 * @param {Bool} [params.is_wall=false] thread is displayed in the wall
509 * @param {Number} [params.msg_more_limit=150] number of character to
510 * display before having a "show more" link; note that the text
511 * will not be truncated if it does not have 110% of the parameter
512 * (ex: 110 characters needed to be truncated and be displayed as
513 * a 100-characters message)
514 * @param {Number} [params.limit=100] maximum number of messages to fetch
515 * @param {Number} [params.offset=0] offset for fetching messages
516 * @param {Number} [params.records=null] records to show instead of fetching messages
518 init: function(parent, params) {
521 this.params = params;
522 this.params.parent_id = this.params.parent_id || false;
523 this.params.thread_level = this.params.thread_level || 0;
524 this.params.is_wall = this.params.is_wall || (this.params.records != undefined) || false;
525 this.params.msg_more_limit = this.params.msg_more_limit || 250;
526 this.params.limit = this.params.limit || 100;
527 // this.params.limit = 3; // tmp for testing
528 this.params.offset = this.params.offset || 0;
529 this.params.records = this.params.records || null;
530 // datasets and internal vars
531 this.ds = new session.web.DataSetSearch(this, this.params.res_model);
532 this.ds_users = new session.web.DataSetSearch(this, 'res.users');
533 this.ds_msg = new session.web.DataSetSearch(this, 'mail.message');
534 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
535 // display customization vars
537 this.display.show_post_comment = this.params.show_post_comment || false;
538 this.display.show_reply = (this.params.thread_level > 0 && this.params.is_wall);
539 this.display.show_delete = ! this.params.is_wall;
540 this.display.show_hide = this.params.is_wall;
541 this.display.show_reply_by_email = ! this.params.is_wall;
542 this.display.show_more = (this.params.thread_level == 0);
546 this._super.apply(this, arguments);
549 // display user, fetch comments
550 this.display_current_user();
551 if (this.params.records) var display_done = this.display_comments_from_parameters(this.params.records);
552 else var display_done = this.init_comments();
554 $.when(display_done).then(this.proxy('do_customize_display'));
555 // add message composition form view
556 if (this.display.show_post_comment) {
557 var compose_done = this.instantiate_composition_form();
559 return display_done && compose_done;
563 * Override-hack of do_action: automatically reload the chatter.
564 * Normally it should be called only when clicking on 'Post/Send'
565 * in the composition form. */
566 do_action: function(action, on_close) {
567 this.init_comments();
568 if (this.compose_message_widget) {
569 this.compose_message_widget.reinit(); }
570 return this._super(action, on_close);
573 instantiate_composition_form: function(mode, email_mode, formatting, msg_id, context) {
574 if (this.compose_message_widget) {
575 this.compose_message_widget.destroy();
577 this.compose_message_widget = new mail.ComposeMessage(this, {
578 'extended_mode': false, 'uid': this.params.uid, 'res_model': this.params.res_model,
579 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id,
580 'email_mode': email_mode || false, 'formatting': formatting || false,
581 'context': context || false } );
582 var composition_node = this.$element.find('div.oe_mail_thread_action');
583 composition_node.empty();
584 var compose_done = this.compose_message_widget.appendTo(composition_node);
588 do_customize_display: function() {
589 if (this.display.show_post_comment) { this.$element.find('div.oe_mail_thread_action').eq(0).show(); }
593 * Bind events in the widget. Each event is slightly described
594 * in the function. */
595 bind_events: function() {
597 // generic events from Chatter Mixin
598 mail.ChatterUtils.bind_events(this);
599 // event: click on 'more' at bottom of thread
600 this.$element.find('button.oe_mail_button_more').click(function () {
603 // event: writing in basic textarea of composition form (quick reply)
604 this.$element.find('textarea.oe_mail_compose_textarea').keyup(function (event) {
605 var charCode = (event.which) ? event.which : window.event.keyCode;
606 if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
607 else if (charCode == 13) { return self.do_comment(); }
609 // event: click on 'Reply' in msg
610 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
611 var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
613 event.preventDefault();
615 // event: click on 'attachment(s)' in msg
616 this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
617 var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
619 event.preventDefault();
621 // event: click on 'Delete' in msg side menu
622 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
623 if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
624 var msg_id = event.srcElement.dataset.id;
625 if (! msg_id) return false;
626 var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
627 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
628 if (self.params.thread_level > 0) {
629 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
631 event.preventDefault();
634 // event: click on 'Hide' in msg side menu
635 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
636 if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
637 var msg_id = event.srcElement.dataset.id;
638 if (! msg_id) return false;
639 var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
640 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
641 if (self.params.thread_level > 0) {
642 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
644 event.preventDefault();
647 // event: click on "Reply" in msg side menu (email style)
648 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply_by_email', 'click', function (event) {
649 var msg_id = event.srcElement.dataset.msg_id;
650 var email_mode = (event.srcElement.dataset.type == 'email');
651 var formatting = (event.srcElement.dataset.formatting == 'html');
652 if (! msg_id) return false;
653 self.instantiate_composition_form('reply', email_mode, formatting, msg_id);
654 event.preventDefault();
658 destroy: function () {
659 this._super.apply(this, arguments);
662 init_comments: function() {
664 this.params.offset = 0;
665 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
666 this.$element.find('div.oe_mail_thread_display').empty();
667 var domain = this.get_fetch_domain(this.comments_structure);
668 return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
671 fetch_comments: function (limit, offset, domain) {
673 var defer = this.ds.call('message_read', [[this.params.res_id], (this.params.thread_level > 0), (this.comments_structure['root_ids']),
674 (limit+1) || (this.params.limit+1), offset||this.params.offset, domain||undefined ]).then(function (records) {
675 if (records.length <= self.params.limit) self.display.show_more = false;
676 // else { self.display.show_more = true; records.pop(); }
677 // else { self.display.show_more = true; records.splice(0, 1); }
678 else { self.display.show_more = true; }
679 self.display_comments(records);
680 // TODO: move to customize display
681 if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
682 else self.$element.find('div.oe_mail_thread_more:last').hide();
688 display_comments_from_parameters: function (records) {
689 if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
690 else this.display.show_more = false;
691 var defer = this.display_comments(records);
692 // TODO: move to customize display
693 if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
694 else $('div.oe_mail_thread_more').eq(-2).hide();
698 display_comments: function (records) {
701 mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, this.params.parent_id);
702 //build attachments download urls and compute time-relative from dates
703 for (var k in records) {
704 records[k].timerelative = $.timeago(records[k].date);
705 if (records[k].attachments) {
706 for (var l in records[k].attachments) {
707 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;
708 records[k].attachments[l].url = url;
712 _(records).each(function (record) {
714 if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
715 var sub_list = self.comments_structure['tree_struct'][record.id]['direct_childs'];
716 _(records).each(function (record) {
717 //if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
718 if (_.indexOf(sub_list, record.id) != -1) {
719 sub_msgs.push(record);
722 self.display_comment(record);
723 self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
724 'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id,
725 'is_wall': self.params.is_wall});
726 self.$element.find('li.oe_mail_thread_msg:last').append('<div class="oe_mail_thread_subthread"/>');
727 self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
729 else if (self.params.thread_level == 0) {
730 self.display_comment(record);
733 mail.ChatterUtils.records_struct_update_after_display(this.comments_structure);
734 // update offset for "More" buttons
735 if (this.params.thread_level == 0) this.params.offset += records.length;
738 /** Displays a record, performs text/link formatting */
739 display_comment: function (record) {
740 record.body = mail.ChatterUtils.do_text_nl2br($.trim(record.body), true);
741 // if (record.type == 'email' && record.state == 'received') {
742 if (record.type == 'email') {
743 record.mini_url = ('/mail/static/src/img/email_icon.png');
745 record.mini_url = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'image_small', record.user_id[0]);
747 // body text manipulation
748 if (record.subtype == 'plain') {
749 record.body = mail.ChatterUtils.do_text_remove_html_tags(record.body);
751 record.body = mail.ChatterUtils.do_replace_expressions(record.body);
752 // format date according to the user timezone
753 record.date = session.web.format_value(record.date, {type:"datetime"});
754 // is the user the author ?
755 record.is_author = mail.ChatterUtils.is_author(this, record.user_id[0]);
757 var rendered = session.web.qweb.render('mail.thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
759 $(rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
760 this.$element.find('div.oe_mail_msg_record_body').expander({
761 slicePoint: this.params.msg_more_limit,
762 expandText: 'read more',
763 userCollapseText: '[^]',
764 detailClass: 'oe_mail_msg_tail',
765 moreClass: 'oe_mail_expand',
766 lessClass: 'oe_mail_reduce',
770 display_current_user: function () {
771 var avatar = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'image_small', this.params.uid);
772 return this.$element.find('img.oe_mail_icon').attr('src', avatar);
775 do_comment: function () {
776 var comment_node = this.$element.find('textarea');
777 var body_text = comment_node.val();
778 comment_node.val('');
779 return this.ds.call('message_append_note', [[this.params.res_id], '', body_text, this.params.parent_id, 'comment', 'plain']).then(
780 this.proxy('init_comments'));
784 * Create a domain to fetch new comments according to
785 * comment already present in comments_structure
786 * @param {Object} comments_structure (see chatter utils)
787 * @returns {Array} fetch_domain (OpenERP domain style)
789 get_fetch_domain: function (comments_structure) {
791 var ids = comments_structure.root_ids.slice();
793 // must be child of current parent
794 if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
795 _(comments_structure.root_ids).each(function (id) { // each record
799 if (this.params.parent_id != false) {
800 ids2.push(this.params.parent_id);
802 // must not be children of already fetched messages
803 if (ids.length > 0) {
806 domain.push(['id', 'child_of', ids]);
808 if (ids2.length > 0) {
809 domain.push(['id', 'not in', ids2]);
814 do_more: function () {
815 domain = this.get_fetch_domain(this.comments_structure);
816 return this.fetch_comments(this.params.limit, this.params.offset, domain);
822 * ------------------------------------------------------------
824 * ------------------------------------------------------------
826 * This widget handles the display of the Chatter on documents.
829 /* Add mail_thread widget to registry */
830 session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
832 /** mail_thread widget: thread of comments */
833 mail.RecordThread = session.web.form.AbstractField.extend({
834 // QWeb template to use when rendering the object
835 template: 'mail.record_thread',
838 this._super.apply(this, arguments);
839 this.params = this.get_definition_options();
840 this.params.thread_level = this.params.thread_level || 0;
841 this.params.see_subscribers = true;
842 this.params.see_subscribers_options = this.params.see_subscribers_options || false;
844 this.ds = new session.web.DataSet(this, this.view.model);
845 this.ds_users = new session.web.DataSet(this, 'res.users');
851 // NB: all the widget should be modified to check the actual_mode property on view, not use
852 // any other method to know if the view is in create mode anymore
853 this.view.on("change:actual_mode", this, this._check_visibility);
854 this._check_visibility();
856 mail.ChatterUtils.bind_events(this);
857 this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); });
858 if (! this.params.see_subscribers_options) {
859 this.$element.find('button.oe_mail_button_followers').hide(); }
860 this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
861 .mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
862 .mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
863 this.$element.find('button.oe_mail_button_unfollow').click(function () { self.do_unfollow(); })
864 .mouseover(function () { $(this).html('Unfollow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
865 .mouseleave(function () { $(this).html('Following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
869 _check_visibility: function() {
870 this.$element.toggle(this.view.get("actual_mode") !== "create");
873 destroy: function () {
874 this._super.apply(this, arguments);
878 this.params.see_subscribers = true;
879 this.params.see_subscribers_options = this.params.see_subscribers_options || false;
880 this.$element.find('button.oe_mail_button_followers').html('Hide followers')
881 this.$element.find('button.oe_mail_button_follow').hide();
882 this.$element.find('button.oe_mail_button_unfollow').hide();
885 set_value: function() {
886 this._super.apply(this, arguments);
889 if (! this.view.datarecord.id ||
890 session.web.BufferedDataSet.virtual_id_regex.test(this.view.datarecord.id)) {
891 this.$element.find('.oe_mail_thread').hide();
895 var fetch_sub_done = this.fetch_subscribers();
896 // create and render Thread widget
897 this.$element.find('div.oe_mail_recthread_main').empty();
898 if (this.thread) this.thread.destroy();
899 this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
900 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
901 var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_main'));
902 return fetch_sub_done && thread_done;
905 fetch_subscribers: function () {
906 return this.ds.call('message_read_subscribers', [[this.view.datarecord.id]]).then(this.proxy('display_subscribers'));
909 display_subscribers: function (records) {
911 this.is_subscriber = false;
912 var user_list = this.$element.find('ul.oe_mail_followers_display').empty();
913 this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
914 _(records).each(function (record) {
915 if (record.id == self.session.uid) { self.is_subscriber = true; }
916 record.avatar_url = mail.ChatterUtils.get_image(self.session.prefix, self.session.session_id, 'res.users', 'image_small', record.id);
917 $(session.web.qweb.render('mail.record_thread.subscriber', {'record': record})).appendTo(user_list);
919 if (self.is_subscriber) {
920 self.$element.find('button.oe_mail_button_follow').hide();
921 self.$element.find('button.oe_mail_button_unfollow').show(); }
923 self.$element.find('button.oe_mail_button_follow').show();
924 self.$element.find('button.oe_mail_button_unfollow').hide(); }
927 do_follow: function () {
928 return this.ds.call('message_subscribe', [[this.view.datarecord.id]]).pipe(this.proxy('fetch_subscribers'));
931 do_unfollow: function () {
933 return this.ds.call('message_unsubscribe', [[this.view.datarecord.id]]).then(function (record) {
934 if (record == false) self.do_notify("Impossible to unsubscribe", "You are automatically subscribed to this record. You cannot unsubscribe.");
935 }).pipe(this.proxy('fetch_subscribers'));
938 do_toggle_followers: function () {
939 this.params.see_subscribers = ! this.params.see_subscribers;
940 if (this.params.see_subscribers) { this.$element.find('button.oe_mail_button_followers').html('Hide followers'); }
941 else { this.$element.find('button.oe_mail_button_followers').html('Show followers'); }
942 this.$element.find('div.oe_mail_recthread_followers').toggle();
948 * ------------------------------------------------------------
950 * ------------------------------------------------------------
952 * This widget handles the display of the Chatter on the Wall.
955 /* Add WallView widget to registry */
956 session.web.client_actions.add('mail.wall', 'session.mail.Wall');
958 /* WallView widget: a wall of messages */
959 mail.Wall = session.web.Widget.extend({
960 template: 'mail.wall',
963 * @param {Object} parent parent
964 * @param {Object} [params]
965 * @param {Number} [params.limit=20] number of messages to show and fetch
966 * @param {Number} [params.search_view_id=false] search view id for messages
967 * @var {Array} comments_structure (see chatter utils)
969 init: function (parent, params) {
972 this.params.limit = params.limit || 25;
973 this.params.domain = params.domain || [];
974 this.params.context = params.context || {};
975 this.params.res_model = params.res_model || false;
976 this.params.res_id = params.res_id || false;
977 this.params.search_view_id = params.search_view_id || false;
978 this.params.thread_level = params.thread_level || 1;
979 this.params.title = params.title || false;
980 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
981 this.display_show_more = true;
982 this.thread_list = [];
983 this.search = {'domain': [], 'context': {}, 'groupby': {}}
984 this.search_results = {'domain': [], 'context': {}, 'groupby': {}}
986 this.ds_msg = new session.web.DataSet(this, 'mail.message');
987 this.ds_thread = new session.web.DataSet(this, 'mail.thread');
988 this.ds_users = new session.web.DataSet(this, 'res.users');
992 this._super.apply(this, arguments);
993 this.display_current_user();
995 this.add_event_handlers();
996 // load mail.message search view
997 var search_view_ready = this.load_search_view(this.params.search_view_id, {}, false);
998 // load composition form
999 var compose_done = this.instantiate_composition_form();
1000 // fetch first threads
1001 var comments_ready = this.init_and_fetch_comments(this.params.limit, 0);
1002 return (search_view_ready && comments_ready && compose_done);
1006 * Override-hack of do_action: automatically reload the chatter.
1007 * Normally it should be called only when clicking on 'Post/Send'
1008 * in the composition form. */
1009 do_action: function(action, on_close) {
1010 this.init_and_fetch_comments();
1011 if (this.compose_message_widget) {
1012 this.compose_message_widget.reinit(); }
1013 return this._super(action, on_close);
1016 destroy: function () {
1017 this._super.apply(this, arguments);
1020 instantiate_composition_form: function(mode, msg_id) {
1021 if (this.compose_message_widget) {
1022 this.compose_message_widget.destroy();
1025 this.compose_message_widget = new mail.ComposeMessage(this, {
1026 'extended_mode': false, 'uid': this.session.uid, 'res_model': this.params.res_model,
1027 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id });
1028 var composition_node = this.$element.find('div.oe_mail_wall_action');
1029 composition_node.empty();
1030 var compose_done = this.compose_message_widget.appendTo(composition_node);
1031 return compose_done;
1035 add_event_handlers: function () {
1037 // display more threads
1038 this.$element.find('button.oe_mail_wall_button_more').click(function () { return self.do_more(); });
1042 * Loads the mail.message search view
1043 * @param {Number} view_id id of the search view to load
1044 * @param {Object} defaults ??
1045 * @param {Boolean} hidden some kind of trick we do not care here
1047 load_search_view: function (view_id, defaults, hidden) {
1049 this.searchview = new session.web.SearchView(this, this.ds_msg, view_id || false, defaults || {}, hidden || false);
1050 var search_view_loaded = this.searchview.appendTo(this.$element.find('.oe_view_manager_view_search'));
1051 return $.when(search_view_loaded).then(function () {
1052 self.searchview.on_search.add(self.do_searchview_search);
1057 * Aggregate the domains, contexts and groupbys in parameter
1058 * with those from search form, and then calls fetch_comments
1059 * to actually fetch comments
1060 * @param {Array} domains
1061 * @param {Array} contexts
1062 * @param {Array} groupbys
1064 do_searchview_search: function(domains, contexts, groupbys) {
1066 this.rpc('/web/session/eval_domain_and_context', {
1067 domains: domains || [],
1068 contexts: contexts || [],
1069 group_by_seq: groupbys || []
1070 }, function (results) {
1071 self.search_results['context'] = results.context;
1072 self.search_results['domain'] = results.domain;
1073 self.search_results['groupby'] = results.group_by;
1074 return self.init_and_fetch_comments();
1078 display_current_user: function () {
1079 //return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'avatar', this.session.uid));
1083 * Initializes the wall and calls fetch_comments
1084 * @param {Number} limit: number of notifications to fetch
1085 * @param {Number} offset: offset in notifications search
1086 * @param {Array} domain
1087 * @param {Array} context
1089 init_and_fetch_comments: function() {
1090 this.search['domain'] = _.union(this.params.domain, this.search_results.domain);
1091 this.search['context'] = _.extend(this.params.context, this.search_results.context);
1092 this.display_show_more = true;
1093 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
1094 this.$element.find('ul.oe_mail_wall_threads').empty();
1095 return this.fetch_comments(this.params.limit, 0);
1099 * Fetches wall messages
1100 * @param {Number} limit: number of notifications to fetch
1101 * @param {Number} offset: offset in notifications search
1102 * @param {Array} domain
1103 * @param {Array} context
1105 fetch_comments: function (limit, offset, additional_domain, additional_context) {
1107 if (additional_domain) var fetch_domain = this.search['domain'].concat(additional_domain);
1108 else var fetch_domain = this.search['domain'];
1109 if (additional_context) var fetch_context = _.extend(this.search['context'], additional_context);
1110 else var fetch_context = this.search['context'];
1111 return this.ds_thread.call('message_get_pushed_messages',
1112 [[this.session.uid], true, [], (limit || 0), (offset || 0), fetch_domain, fetch_context]).then(this.proxy('display_comments'));
1116 * @param {Array} records records to show in threads
1118 display_comments: function (records) {
1120 this.do_update_show_more(records.length >= self.params.limit);
1121 mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, false);
1122 _(this.comments_structure['new_root_ids']).each(function (root_id) {
1123 var records = self.comments_structure.tree_struct[root_id]['for_thread_msgs'];
1124 var model_name = self.comments_structure.msgs[root_id]['model'];
1125 var res_id = self.comments_structure.msgs[root_id]['res_id'];
1126 var render_res = session.web.qweb.render('mail.wall_thread_container', {});
1127 $('<li class="oe_mail_wall_thread">').html(render_res).appendTo(self.$element.find('ul.oe_mail_wall_threads'));
1128 var thread = new mail.Thread(self, {
1129 'res_model': model_name, 'res_id': res_id, 'uid': self.session.uid, 'records': records,
1130 'parent_id': false, 'thread_level': self.params.thread_level, 'show_hide': true, 'is_wall': true}
1132 self.thread_list.push(thread);
1133 return thread.appendTo(self.$element.find('li.oe_mail_wall_thread:last'));
1136 this.comments_structure['root_ids'] = _.union(this.comments_structure['root_ids'], this.comments_structure['new_root_ids']);
1137 this.comments_structure['new_root_ids'] = [];
1141 * Create a domain to fetch new comments according to
1142 * comments already present in comments_structure
1144 * -- should not be child of already displayed ids
1145 * @returns {Array} fetch_domain (OpenERP domain style)
1147 get_fetch_domain: function () {
1149 var model_to_root = {};
1150 var fetch_domain = [];
1151 _(this.comments_structure['model_to_root_ids']).each(function (sc_model, model_name) {
1152 fetch_domain.push('|', ['model', '!=', model_name], '!', ['id', 'child_of', sc_model]);
1154 return fetch_domain;
1157 /** Display update: show more button */
1158 do_update_show_more: function (new_value) {
1159 if (new_value != undefined) this.display_show_more = new_value;
1160 if (this.display_show_more) this.$element.find('div.oe_mail_wall_more:last').show();
1161 else this.$element.find('div.oe_mail_wall_more:last').hide();
1164 /** Action: Shows more discussions */
1165 do_more: function () {
1166 var domain = this.get_fetch_domain();
1167 return this.fetch_comments(this.params.limit, 0, domain);