1 openerp.mail = function(session) {
2 var _t = session.web._t,
5 var mail = session.mail = {};
8 * Add records to sorted_comments array
9 * @param {Array} records records from mail.message sorted by date desc
10 * @returns {Object} cs comments_structure: dict
11 * cs.model_to_root_ids = {model: [root_ids], }
12 * cs.new_root_ids = [new_root_ids]
13 * cs.root_ids = [root_ids]
14 * cs.msgs = {record.id: record,}
15 * cs.tree_struct = {record.id: {
16 * 'level': record_level in hierarchy, 0 is root,
17 * 'msg_nbr': number of childs,
18 * 'direct_childs': [msg_ids],
19 * 'all_childs': [msg_ids],
20 * 'for_thread_msgs': [records],
21 * 'ancestors': [msg_ids], } }
23 function tools_sort_comments(cs, records, parent_id) {
24 var cur_iter = 0; var max_iter = 10; var modif = true;
25 while ( modif && (cur_iter++) < max_iter) {
27 _(records).each(function (record) {
28 // root and not yet recorded
29 if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
30 // add to model -> root_list ids
31 if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
32 else cs['model_to_root_ids'][record.model].push(record.id);
34 cs['new_root_ids'].push(record.id);
36 cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
37 cs['msgs'][record.id] = record;
40 // not yet recorded, but parent is recorded
41 else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
42 var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
43 // update parent structure
44 cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
45 cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
46 // update ancestors structure
47 for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
48 cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
51 cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
52 cs['msgs'][record.id] = record;
61 * ThreadDisplay widget: this widget handles the display of a thread of
62 * messages. The [thread_level] parameter sets the thread level number:
64 * - - sub message (parent_id = root message)
65 * - - - sub sub message (parent id = sub message)
66 * - - sub message (parent_id = root message)
67 * This widget has 2 ways of initialization, either you give records to be rendered,
68 * either it will fetch [limit] messages related to [res_model]:[res_id].
70 mail.Thread = session.web.Widget.extend({
71 template: 'mail.Thread',
74 * @param {Object} parent parent
75 * @param {Object} [params]
76 * @param {String} [params.res_model] res_model of mail.thread object
77 * @param {Number} [params.res_id] res_id of record
78 * @param {Number} [params.parent_id=false] parent_id of message
79 * @param {Number} [params.uid] user id
80 * @param {Number} [params.thread_level=0] number of levels in the thread (only 0 or 1 currently)
81 * @param {Number} [params.msg_more_limit=100] number of character to display before having a "show more" link;
82 * note that the text will not be truncated if it does not have 110% of
83 * the parameter (ex: 110 characters needed to be truncated and be displayed
84 * as a 100-characters message)
85 * @param {Number} [params.limit=10] maximum number of messages to fetch
86 * @param {Number} [params.offset=0] offset for fetching messages
87 * @param {Number} [params.records=null] records to show instead of fetching messages
89 init: function(parent, params) {
92 this.params.parent_id = this.params.parent_id || false;
93 this.params.thread_level = this.params.thread_level || 0;
94 this.params.msg_more_limit = this.params.msg_more_limit || 100;
95 this.params.limit = this.params.limit || 100;
96 this.params.offset = this.params.offset || 0;
97 this.params.records = this.params.records || null;
98 // datasets and internal vars
99 this.ds = new session.web.DataSet(this, this.params.res_model);
100 this.ds_users = new session.web.DataSet(this, 'res.users');
101 this.ds_msg = new session.web.DataSet(this, 'mail.message');
102 this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
103 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
104 // display customization vars
106 this.display.show_post_comment = this.params.show_post_comment || false;
107 this.display.show_reply = (this.params.thread_level > 0);
108 this.display.show_delete = true;
109 this.display.show_hide = this.params.show_hide || false;
110 this.display.show_more = (this.params.thread_level == 0);
111 // not used currently
112 this.intlinks_mapping = {};
118 this._super.apply(this, arguments);
120 if (! this.display.show_post_comment) {
121 this.$element.find('div.oe_mail_thread_action').hide();
126 // display user, fetch comments
127 this.display_current_user();
129 if (this.params.records) {
130 var display_done = this.display_comments_from_parameters(this.params.records);
132 var display_done = this.init_comments();
137 add_events: function() {
139 // event: click on 'more' at bottom of thread
140 this.$element.find('button.oe_mail_button_more').click(function () {
143 // event: writing in textarea
144 this.$element.find('textarea.oe_mail_action_textarea').keyup(function (event) {
145 var charCode = (event.which) ? event.which : window.event.keyCode;
146 if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
147 else if (charCode == 13) { return self.do_comment(); }
149 // event: click on 'reply' in msg
150 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
151 var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
153 event.preventDefault();
155 // event: click on 'delete' in msg
156 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
157 //console.log('deleting');
158 if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
159 var msg_id = event.srcElement.dataset.id;
160 if (! msg_id) return false;
161 var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
162 $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
163 if (self.params.thread_level > 0) {
164 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
168 // event: click on 'hide' in msg
169 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
170 //console.log('hiding');
171 if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
172 var msg_id = event.srcElement.dataset.id;
173 if (! msg_id) return false;
174 //console.log(msg_id);
175 var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
176 $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
177 if (self.params.thread_level > 0) {
178 $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
182 // event: click on an internal link
183 this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_internal_link', 'click', function (event) {
184 // lazy implementation: fetch data and try to redirect
185 if (! event.srcElement.dataset.resModel) return false;
186 else var res_model = event.srcElement.dataset.resModel;
187 var res_login = event.srcElement.dataset.resLogin;
188 var res_id = event.srcElement.dataset.resId;
189 if ((! res_login) && (! res_id)) return false;
191 var ds = new session.web.DataSet(self, res_model);
192 var defer = ds.call('search', [[['login', '=', res_login]]]).then(function (records) {
194 self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
199 else self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(res_id), views: [[false, 'form']]});
201 // event: click on 'attachment(s)' in msg
202 this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
203 var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
208 this.$element.on('click','a.oe_mail_msg_more', function (event) {
209 $(this).siblings('.oe_mail_msg_tail').show();
215 destroy: function () {
216 this._super.apply(this, arguments);
219 init_comments: function() {
221 this.params.offset = 0;
222 this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
223 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
224 this.$element.find('div.oe_mail_thread_display').empty();
225 domain = this.get_fetch_domain(this.sorted_comments);
226 return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
229 fetch_comments: function (limit, offset, domain) {
231 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'])]);
232 $.when(defer).then(function (records) {
233 if (records.length <= self.params.limit) self.display.show_more = false;
234 else { self.display.show_more = true; records.pop(); }
236 self.display_comments(records);
237 if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
238 else self.$element.find('div.oe_mail_thread_more:last').hide();
244 display_comments_from_parameters: function (records) {
245 if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
246 else this.display.show_more = false;
247 var defer = this.display_comments(records);
248 if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
249 else $('div.oe_mail_thread_more').eq(-2).hide();
253 display_comments: function (records) {
256 //build attachments download urls and compute time-relative from dates
257 for (var k in records) {
258 records[k].timerelative = $.timeago(records[k].date);
259 if (records[k].attachments) {
260 for (var l in records[k].attachments) {
261 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;
262 records[k].attachments[l].url = url;
266 this.cs = this.sort_comments_tmp(records);
267 _(records).each(function (record) {
269 if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
270 var sub_list = self.cs['tree_struct'][record.id]['direct_childs'];
271 _(records).each(function (record) {
272 //if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
273 if (_.indexOf(sub_list, record.id) != -1) {
274 sub_msgs.push(record);
277 self.display_comment(record);
278 self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
279 'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id});
280 self.$element.find('.oe_mail_thread_msg:last').append('<div class="oe_mail_thread_subthread"/>');
281 self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
283 else if (self.params.thread_level == 0) {
284 self.display_comment(record);
287 // update offset for "More" buttons
288 if (this.params.thread_level == 0) this.params.offset += records.length;
294 display_comment: function (record) {
295 record.body = this.do_text_nl2br(record.body, true);
296 if (record.type == 'email') {
297 record.mini_url = ('/mail/static/src/img/email_icon.png');
299 record.mini_url = this.thread_get_avatar('res.users', 'image_small', record.user_id[0]);
301 // body text manipulation
302 record.body = this.do_clean_text(record.body);
303 record.body = this.do_replace_internal_links(record.body);
305 // split for see more
306 var split = this.do_truncate_string(record.body, this.params.msg_more_limit);
307 record.body_head = split[0];
308 record.body_tail = split[1];
310 // format date according to the user timezone
311 record.date = session.web.format_value(record.date, {type:"datetime"});
314 var rendered = session.web.qweb.render('mail.Thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
315 $( rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
319 * Add records to sorted_comments array
320 * @param {Array} records records from mail.message sorted by date desc
321 * @returns {Object} sc sorted_comments: dict {
322 * 'root_id_list': list or root_ids
323 * 'root_id_msg_list': {'record_id': [ancestor_ids]}, still sorted by date desc
324 * 'id_to_root': {'root_id': [records]}, still sorted by date desc
327 sort_comments: function (records) {
329 sc = {'root_id_list': [], 'root_id_msg_list': {}, 'id_to_root': {}}
330 var cur_iter = 0; var max_iter = 10; var modif = true;
331 /* step1: get roots */
332 while ( modif && (cur_iter++) < max_iter) {
334 _(records).each(function (record) {
335 if ( (record.parent_id == false || record.parent_id[0] == self.params.parent_id) && (_.indexOf(sc['root_id_list'], record.id) == -1)) {
336 sc['root_id_list'].push(record.id);
337 sc['root_id_msg_list'][record.id] = [];
338 self.sorted_comments['root_ids'].push(record.id);
342 if (_.indexOf(sc['root_id_list'], record.parent_id[0]) != -1) {
343 sc['id_to_root'][record.id] = record.parent_id[0];
346 else if ( sc['id_to_root'][record.parent_id[0]] ) {
347 sc['id_to_root'][record.id] = sc['id_to_root'][record.parent_id[0]];
353 /* step2: add records */
354 _(records).each(function (record) {
355 var root_id = sc['id_to_root'][record.id];
356 if (! root_id) return;
357 sc['root_id_msg_list'][root_id].push(record);
358 //self.sorted_comments['root_id_msg_list'][root_id].push(record.id);
364 * Add records to comments_structure object: see function for details
366 sort_comments_tmp: function(records) {
367 return tools_sort_comments(this.comments_structure, records, this.params.parent_id);
370 display_current_user: function () {
371 return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'image_small', this.params.uid));
374 do_comment: function () {
375 var comment_node = this.$element.find('textarea');
376 var body_text = comment_node.val();
377 comment_node.val('');
378 return this.ds.call('message_append_note', [[this.params.res_id], 'Reply', body_text, this.params.parent_id, 'comment', 'html']).then(
379 this.proxy('init_comments'));
383 * Create a domain to fetch new comments according to
384 * comment already present in sorted_comments
385 * @param {Object} sorted_comments (see sort_comments)
386 * @returns {Array} fetch_domain (OpenERP domain style)
388 get_fetch_domain: function (sorted_comments) {
390 var ids = sorted_comments.root_ids.slice();
392 // must be child of current parent
393 if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
394 _(sorted_comments.root_ids).each(function (id) { // each record
398 if (this.params.parent_id != false) {
399 ids2.push(this.params.parent_id);
401 // must not be children of already fetched messages
402 if (ids.length > 0) {
405 domain.push(['id', 'child_of', ids]);
407 if (ids2.length > 0) {
408 domain.push(['id', 'not in', ids2]);
413 do_more: function () {
414 domain = this.get_fetch_domain(this.sorted_comments);
415 return this.fetch_comments(this.params.limit, this.params.offset, domain);
420 * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
421 * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
423 do_replace_internal_links: function (string) {
425 var icon_list = ['al', 'pinky']
426 /* shortcut to user: @login */
427 var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
428 var regex_res = regex_login.exec(string);
429 while (regex_res != null) {
430 var login = regex_res[2];
431 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>');
432 regex_res = regex_login.exec(string);
434 /* special shortcut: :name, try to find an icon if in list */
435 var regex_login = new RegExp(/(^|\s):((\w)*)/g);
436 var regex_res = regex_login.exec(string);
437 while (regex_res != null) {
438 var icon_name = regex_res[2];
439 if (_.include(icon_list, icon_name))
440 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 + '"/>');
441 regex_res = regex_login.exec(string);
446 thread_get_avatar: function(model, field, id) {
447 return this.session.prefix + '/web/binary/image?session_id=' + this.session.session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
451 * @param {String} string to truncate
452 * @param {Number} max number of chars to display
453 * @returns {String} truncated string
455 do_truncate_string: function(string, max_length) {
456 // multiply by 1.2: prevent truncating an just too little long string
457 if (string.length <= (max_length * 1.2)) {
460 return [string.slice(0, max_length), string.slice(max_length)];
464 /** Removes html tags, except b, em, br */
465 do_clean_text: function (string) {
466 var html = $('<div/>').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('<(/)?(b|em|br|br /)\\s*>', 'gi'), '<$1$2>');
470 /** Replaces line bracks by html line breaks (br) */
471 do_text_nl2br: function (str, is_xhtml) {
472 var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
473 return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
478 * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
479 * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
481 do_check_internal_links: function(string) {
482 /* shortcut to user: @login */
483 var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
484 var regex_res = regex_login.exec(string);
485 while (regex_res != null) {
486 var login = regex_res[2];
487 if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
488 this.map_hash['res.users']['login'].push(login);
489 regex_res = regex_login.exec(string);
491 /* internal links: #res.model,name */
492 var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
493 regex_res = regex_intlink.exec(string);
494 while (regex_res != null) {
495 var res_model = regex_res[2] + '.' + regex_res[3];
496 var res_name = regex_res[4];
497 if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
498 this.map_hash[res_model]['name'].push(res_name);
499 regex_res = regex_intlink.exec(string);
503 /** checks if tue current user is the message author */
504 _is_author: function (id) {
505 return (this.session.uid == id);
509 session.web.form.widgets.add( 'Thread', 'openerp.mail.Thread');
511 /** ThreadView widget: thread of comments */
512 mail.RecordThread = session.web.form.AbstractField.extend({
513 template: 'mail.RecordThread',
516 this._super.apply(this, arguments);
517 this.see_subscribers = true;
519 this.params = this.get_definition_options();
520 this.params.thread_level = this.params.thread_level || 0;
522 this.ds = new session.web.DataSet(this, this.view.model);
523 this.ds_users = new session.web.DataSet(this, 'res.users');
527 this._super.apply(this, arguments);
530 this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); }).hide();
531 this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
532 .mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
533 .mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
534 this.$element.find('button.oe_mail_button_unfollow').click(function () { self.do_unfollow(); })
535 .mouseover(function () { $(this).html('Unfollow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
536 .mouseleave(function () { $(this).html('Following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
540 destroy: function () {
541 this._super.apply(this, arguments);
545 this.see_subscribers = true;
546 this.$element.find('button.oe_mail_button_followers').html('Hide followers')
547 this.$element.find('button.oe_mail_button_follow').hide();
548 this.$element.find('button.oe_mail_button_unfollow').hide();
551 set_value: function() {
552 this._super.apply(this, arguments);
555 if (! this.view.datarecord.id) { this.$element.find('.oe_mail_thread').hide(); return; }
557 var fetch_sub_done = this.fetch_subscribers();
558 // create and render Thread widget
559 this.$element.find('div.oe_mail_recthread_left').empty();
560 if (this.thread) this.thread.destroy();
561 this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
562 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
563 var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_left'));
564 return fetch_sub_done && thread_done;
567 fetch_subscribers: function () {
568 return this.ds.call('message_get_subscribers', [[this.view.datarecord.id]]).then(this.proxy('display_subscribers'));
571 display_subscribers: function (records) {
573 this.is_subscriber = false;
574 var user_list = this.$element.find('ul.oe_mail_followers_display').empty();
575 this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
576 _(records).each(function (record) {
577 if (record.id == self.session.uid) { self.is_subscriber = true; }
578 var mini_url = self.thread_get_avatar('res.users', 'image_small', record.id);
579 $('<li><img class="oe_mail_oe_left oe_mail_msg_image" src="' + mini_url + '"/>' +
580 '<a href="#" class="oe_mail_internal_link" data-res-model="res.users" data-res-id="' + record.id + '">' + record.name + '</a></li>').appendTo(user_list);
582 if (self.is_subscriber) {
583 self.$element.find('button.oe_mail_button_follow').hide();
584 self.$element.find('button.oe_mail_button_unfollow').show(); }
586 self.$element.find('button.oe_mail_button_follow').show();
587 self.$element.find('button.oe_mail_button_unfollow').hide(); }
590 do_follow: function () {
591 return this.ds.call('message_subscribe', [[this.view.datarecord.id]]).pipe(this.proxy('fetch_subscribers'));
594 do_unfollow: function () {
596 return this.ds.call('message_unsubscribe', [[this.view.datarecord.id]]).then(function (record) {
597 if (record == false) self.do_notify("Impossible to unsubscribe", "You are automatically subscribed to this record. You cannot unsubscribe.");
598 }).pipe(this.proxy('fetch_subscribers'));
601 do_toggle_followers: function () {
602 this.see_subscribers = ! this.see_subscribers;
603 if (this.see_subscribers) { this.$element.find('button.oe_mail_button_followers').html('Hide followers'); }
604 else { this.$element.find('button.oe_mail_button_followers').html('Display followers'); }
605 this.$element.find('div.oe_mail_recthread_followers').toggle();
608 thread_get_avatar: function(model, field, id) {
609 return this.session.prefix + '/web/binary/image?session_id=' + this.session.session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
612 session.web.form.widgets.add( 'ThreadView', 'openerp.mail.RecordThread');
614 /** WallView widget: a wall of messages */
615 mail.WallView = session.web.Widget.extend({
616 template: 'mail.Wall',
619 * @param {Object} parent parent
620 * @param {Object} [params]
621 * @param {Number} [params.limit=20] number of messages to show and fetch
622 * @param {Number} [params.search_view_id=false] search view id for messages
623 * @var {Array} sorted_comments records sorted by res_model and res_id
624 * records.res_model = {res_ids}
625 * records.res_model.res_id = [records]
627 init: function (parent, params) {
630 this.params.limit = params.limit || 25;
631 this.params.domain = params.domain || [];
632 this.params.context = params.context || {};
633 this.params.search_view_id = params.search_view_id || false;
634 this.params.thread_level = params.thread_level || 1;
635 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
636 this.display_show_more = true;
637 this.thread_list = [];
638 this.search = {'domain': [], 'context': {}, 'groupby': {}}
639 this.search_results = {'domain': [], 'context': {}, 'groupby': {}}
641 this.ds_msg = new session.web.DataSet(this, 'mail.message');
642 this.ds_thread = new session.web.DataSet(this, 'mail.thread');
643 this.ds_users = new session.web.DataSet(this, 'res.users');
647 this._super.apply(this, arguments);
650 this.add_event_handlers();
651 // load mail.message search view
652 var search_view_ready = this.load_search_view(this.params.search_view_id, {}, false);
653 // fetch first threads
654 var comments_ready = this.init_and_fetch_comments(this.params.limit, 0);
655 return (search_view_ready && comments_ready);
659 this._super.apply(this, arguments);
663 add_event_handlers: function () {
666 this.$element.find('.oe_mail_wall_action button').click(function () { return self.do_comment(); });
667 // display more threads
668 this.$element.find('button.oe_mail_wall_button_more').click(function () { return self.do_more(); });
672 * Loads the mail.message search view
673 * @param {Number} view_id id of the search view to load
674 * @param {Object} defaults ??
675 * @param {Boolean} hidden some kind of trick we do not care here
677 load_search_view: function (view_id, defaults, hidden) {
679 this.searchview = new session.web.SearchView(this, this.ds_msg, view_id || false, defaults || {}, hidden || false);
680 var search_view_loaded = this.searchview.appendTo(this.$element.find('.oe_view_manager_view_search'));
681 return $.when(search_view_loaded).then(function () {
682 self.searchview.on_search.add(self.do_searchview_search);
687 * Aggregate the domains, contexts and groupbys in parameter
688 * with those from search form, and then calls fetch_comments
689 * to actually fetch comments
690 * @param {Array} domains
691 * @param {Array} contexts
692 * @param {Array} groupbys
694 do_searchview_search: function(domains, contexts, groupbys) {
696 this.rpc('/web/session/eval_domain_and_context', {
697 domains: domains || [],
698 contexts: contexts || [],
699 group_by_seq: groupbys || []
700 }, function (results) {
701 self.search_results['context'] = results.context;
702 self.search_results['domain'] = results.domain;
703 self.search_results['groupby'] = results.group_by;
704 return self.init_and_fetch_comments();
709 * Initializes the wall and calls fetch_comments
710 * @param {Number} limit: number of notifications to fetch
711 * @param {Number} offset: offset in notifications search
712 * @param {Array} domain
713 * @param {Array} context
715 init_and_fetch_comments: function() {
716 this.search['domain'] = _.union(this.params.domain, this.search_results.domain);
717 this.search['context'] = _.extend(this.params.context, this.search_results.context);
718 this.display_show_more = true;
719 this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
720 this.$element.find('ul.oe_mail_wall_threads').empty();
721 return this.fetch_comments(this.params.limit, 0);
725 * Fetches wall messages
726 * @param {Number} limit: number of notifications to fetch
727 * @param {Number} offset: offset in notifications search
728 * @param {Array} domain
729 * @param {Array} context
731 fetch_comments: function (limit, offset, additional_domain, additional_context) {
733 if (additional_domain) var fetch_domain = this.search['domain'].concat(additional_domain);
734 else var fetch_domain = this.search['domain'];
735 if (additional_context) var fetch_context = _.extend(this.search['context'], additional_context);
736 else var fetch_context = this.search['context'];
737 return this.ds_thread.call('get_pushed_messages',
738 [[this.session.uid], (limit || 0), (offset || 0), fetch_domain, true, [], fetch_context]).then(this.proxy('display_comments'));
742 * @param {Array} records records to show in threads
744 display_comments: function (records) {
746 this.do_update_show_more(records.length >= self.params.limit);
747 this.sort_comments(records);
748 _(this.comments_structure['new_root_ids']).each(function (root_id) {
749 var records = self.comments_structure.tree_struct[root_id]['for_thread_msgs'];
750 var model_name = self.comments_structure.msgs[root_id]['model'];
751 var res_id = self.comments_structure.msgs[root_id]['res_id'];
752 var render_res = session.web.qweb.render('mail.WallThreadContainer', {});
753 $('<li class="oe_mail_wall_thread">').html(render_res).appendTo(self.$element.find('ul.oe_mail_wall_threads'));
754 var thread = new mail.Thread(self, {
755 'res_model': model_name, 'res_id': res_id, 'uid': self.session.uid, 'records': records,
756 'parent_id': false, 'thread_level': self.params.thread_level, 'show_hide': true}
758 self.thread_list.push(thread);
759 return thread.appendTo(self.$element.find('li.oe_mail_wall_thread:last'));
762 this.comments_structure['root_ids'] = _.union(this.comments_structure['root_ids'], this.comments_structure['new_root_ids']);
763 this.comments_structure['new_root_ids'] = [];
767 * Add records to comments_structure object: see function for details
769 sort_comments: function(records) {
770 tools_sort_comments(this.comments_structure, records, false);
774 * Create a domain to fetch new comments according to
775 * comments already present in sorted_comments
777 * -- should not be child of already displayed ids
778 * @param {Object} sorted_comments (see sort_comments)
779 * @returns {Array} fetch_domain (OpenERP domain style)
781 get_fetch_domain: function () {
783 var model_to_root = {};
784 var fetch_domain = [];
785 _(this.comments_structure['model_to_root_ids']).each(function (sc_model, model_name) {
786 fetch_domain.push('|', ['model', '!=', model_name], '!', ['id', 'child_of', sc_model]);
791 /** Display update: show more button */
792 do_update_show_more: function (new_value) {
793 if (new_value != undefined) this.display_show_more = new_value;
794 if (this.display_show_more) this.$element.find('div.oe_mail_wall_more:last').show();
795 else this.$element.find('div.oe_mail_wall_more:last').hide();
798 /** Action: Shows more discussions */
799 do_more: function () {
800 var domain = this.get_fetch_domain();
801 return this.fetch_comments(this.params.limit, 0, domain);
804 /** Action: Posts a comment */
805 do_comment: function () {
806 var comment_node = this.$element.find('.oe_mail_wall_action textarea');
807 var body_text = comment_node.val();
808 comment_node.val('');
809 var call_done = this.ds_users.call('message_append_note', [[this.session.uid], 'Tweet', body_text, false, 'comment', 'html']).then(this.proxy('init_and_fetch_comments'));
812 session.web.client_actions.add('mail.all_feeds', 'session.mail.WallView');
816 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: