summaryrefslogtreecommitdiff
path: root/addons/mail/static/src/models/discuss/discuss.js
blob: 513b77fd5db61c86d22b19314616a5d8d46d37e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
odoo.define('mail/static/src/models/discuss.discuss.js', function (require) {
'use strict';

const { registerNewModel } = require('mail/static/src/model/model_core.js');
const { attr, many2one, one2many, one2one } = require('mail/static/src/model/model_field.js');
const { clear } = require('mail/static/src/model/model_field_command.js');

function factory(dependencies) {

    class Discuss extends dependencies['mail.model'] {

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        /**
         * @param {mail.thread} thread
         */
        cancelThreadRenaming(thread) {
            this.update({ renamingThreads: [['unlink', thread]] });
        }

        clearIsAddingItem() {
            this.update({
                addingChannelValue: "",
                isAddingChannel: false,
                isAddingChat: false,
            });
        }

        clearReplyingToMessage() {
            this.update({ replyingToMessage: [['unlink-all']] });
        }

        /**
         * Close the discuss app. Should reset its internal state.
         */
        close() {
            this.update({ isOpen: false });
        }

        focus() {
            this.update({ isDoFocus: true });
        }

        /**
         * @param {Event} ev
         * @param {Object} ui
         * @param {Object} ui.item
         * @param {integer} ui.item.id
         */
        async handleAddChannelAutocompleteSelect(ev, ui) {
            const name = this.addingChannelValue;
            this.clearIsAddingItem();
            if (ui.item.special) {
                const channel = await this.async(() =>
                    this.env.models['mail.thread'].performRpcCreateChannel({
                        name,
                        privacy: ui.item.special,
                    })
                );
                channel.open();
            } else {
                const channel = await this.async(() =>
                    this.env.models['mail.thread'].performRpcJoinChannel({
                        channelId: ui.item.id,
                    })
                );
                channel.open();
            }
        }

        /**
         * @param {Object} req
         * @param {string} req.term
         * @param {function} res
         */
        async handleAddChannelAutocompleteSource(req, res) {
            const value = req.term;
            const escapedValue = owl.utils.escape(value);
            this.update({ addingChannelValue: value });
            const domain = [
                ['channel_type', '=', 'channel'],
                ['name', 'ilike', value],
            ];
            const fields = ['channel_type', 'name', 'public', 'uuid'];
            const result = await this.async(() => this.env.services.rpc({
                model: "mail.channel",
                method: "search_read",
                kwargs: {
                    domain,
                    fields,
                },
            }));
            const items = result.map(data => {
                let escapedName = owl.utils.escape(data.name);
                return Object.assign(data, {
                    label: escapedName,
                    value: escapedName
                });
            });
            // XDU FIXME could use a component but be careful with owl's
            // renderToString https://github.com/odoo/owl/issues/708
            items.push({
                label: _.str.sprintf(
                    `<strong>${this.env._t('Create %s')}</strong>`,
                    `<em><span class="fa fa-hashtag"/>${escapedValue}</em>`,
                ),
                escapedValue,
                special: 'public'
            }, {
                label: _.str.sprintf(
                    `<strong>${this.env._t('Create %s')}</strong>`,
                    `<em><span class="fa fa-lock"/>${escapedValue}</em>`,
                ),
                escapedValue,
                special: 'private'
            });
            res(items);
        }

        /**
         * @param {Event} ev
         * @param {Object} ui
         * @param {Object} ui.item
         * @param {integer} ui.item.id
         */
        handleAddChatAutocompleteSelect(ev, ui) {
            this.env.messaging.openChat({ partnerId: ui.item.id });
            this.clearIsAddingItem();
        }

        /**
         * @param {Object} req
         * @param {string} req.term
         * @param {function} res
         */
        handleAddChatAutocompleteSource(req, res) {
            const value = owl.utils.escape(req.term);
            this.env.models['mail.partner'].imSearch({
                callback: partners => {
                    const suggestions = partners.map(partner => {
                        return {
                            id: partner.id,
                            value: partner.nameOrDisplayName,
                            label: partner.nameOrDisplayName,
                        };
                    });
                    res(_.sortBy(suggestions, 'label'));
                },
                keyword: value,
                limit: 10,
            });
        }

        /**
         * Open thread from init active id. `initActiveId` is used to refer to
         * a thread that we may not have full data yet, such as when messaging
         * is not yet initialized.
         */
        openInitThread() {
            const [model, id] = typeof this.initActiveId === 'number'
                ? ['mail.channel', this.initActiveId]
                : this.initActiveId.split('_');
            const thread = this.env.models['mail.thread'].findFromIdentifyingData({
                id: model !== 'mail.box' ? Number(id) : id,
                model,
            });
            if (!thread) {
                return;
            }
            thread.open();
            if (this.env.messaging.device.isMobile && thread.channel_type) {
                this.update({ activeMobileNavbarTabId: thread.channel_type });
            }
        }


        /**
         * Opens the given thread in Discuss, and opens Discuss if necessary.
         *
         * @param {mail.thread} thread
         */
        async openThread(thread) {
            this.update({
                thread: [['link', thread]],
            });
            this.focus();
            if (!this.isOpen) {
                this.env.bus.trigger('do-action', {
                    action: 'mail.action_discuss',
                    options: {
                        active_id: this.threadToActiveId(this),
                        clear_breadcrumbs: false,
                        on_reverse_breadcrumb: () => this.close(),
                    },
                });
            }
        }

        /**
         * @param {mail.thread} thread
         * @param {string} newName
         */
        async renameThread(thread, newName) {
            await this.async(() => thread.rename(newName));
            this.update({ renamingThreads: [['unlink', thread]] });
        }

        /**
         * Action to initiate reply to given message in Inbox. Assumes that
         * Discuss and Inbox are already opened.
         *
         * @param {mail.message} message
         */
        replyToMessage(message) {
            this.update({ replyingToMessage: [['link', message]] });
            // avoid to reply to a note by a message and vice-versa.
            // subject to change later by allowing subtype choice.
            this.replyingToMessageOriginThreadComposer.update({
                isLog: !message.is_discussion && !message.is_notification
            });
            this.focus();
        }

        /**
         * @param {mail.thread} thread
         */
        setThreadRenaming(thread) {
            this.update({ renamingThreads: [['link', thread]] });
        }

        /**
         * @param {mail.thread} thread
         * @returns {string}
         */
        threadToActiveId(thread) {
            return `${thread.model}_${thread.id}`;
        }

        //----------------------------------------------------------------------
        // Private
        //----------------------------------------------------------------------

        /**
         * @private
         * @returns {string|undefined}
         */
        _computeActiveId() {
            if (!this.thread) {
                return clear();
            }
            return this.threadToActiveId(this.thread);
        }

        /**
         * @private
         * @returns {string}
         */
        _computeAddingChannelValue() {
            if (!this.isOpen) {
                return "";
            }
            return this.addingChannelValue;
        }

        /**
         * @private
         * @returns {boolean}
         */
        _computeHasThreadView() {
            if (!this.thread || !this.isOpen) {
                return false;
            }
            if (
                this.env.messaging.device.isMobile &&
                (
                    this.activeMobileNavbarTabId !== 'mailbox' ||
                    this.thread.model !== 'mail.box'
                )
            ) {
                return false;
            }
            return true;
        }

        /**
         * @private
         * @returns {boolean}
         */
        _computeIsAddingChannel() {
            if (!this.isOpen) {
                return false;
            }
            return this.isAddingChannel;
        }

        /**
         * @private
         * @returns {boolean}
         */
        _computeIsAddingChat() {
            if (!this.isOpen) {
                return false;
            }
            return this.isAddingChat;
        }

        /**
         * @private
         * @returns {boolean}
         */
        _computeIsReplyingToMessage() {
            return !!this.replyingToMessage;
        }

        /**
         * Ensures the reply feature is disabled if discuss is not open.
         *
         * @private
         * @returns {mail.message|undefined}
         */
        _computeReplyingToMessage() {
            if (!this.isOpen) {
                return [['unlink-all']];
            }
            return [];
        }


        /**
         * Only pinned threads are allowed in discuss.
         *
         * @private
         * @returns {mail.thread|undefined}
         */
        _computeThread() {
            let thread = this.thread;
            if (this.env.messaging &&
                this.env.messaging.inbox &&
                this.env.messaging.device.isMobile &&
                this.activeMobileNavbarTabId === 'mailbox' &&
                this.initActiveId !== 'mail.box_inbox' &&
                !thread
            ) {
                // After loading Discuss from an arbitrary tab other then 'mailbox',
                // switching to 'mailbox' requires to also set its inner-tab ;
                // by default the 'inbox'.
                return [['replace', this.env.messaging.inbox]];
            }
            if (!thread || !thread.isPinned) {
                return [['unlink']];
            }
            return [];
        }

    }

    Discuss.fields = {
        activeId: attr({
            compute: '_computeActiveId',
            dependencies: [
                'thread',
                'threadId',
                'threadModel',
            ],
        }),
        /**
         * Active mobile navbar tab, either 'mailbox', 'chat', or 'channel'.
         */
        activeMobileNavbarTabId: attr({
            default: 'mailbox',
        }),
        /**
         * Value that is used to create a channel from the sidebar.
         */
        addingChannelValue: attr({
            compute: '_computeAddingChannelValue',
            default: "",
            dependencies: ['isOpen'],
        }),
        /**
         * Serves as compute dependency.
         */
        device: one2one('mail.device', {
            related: 'messaging.device',
        }),
        /**
         * Serves as compute dependency.
         */
        deviceIsMobile: attr({
            related: 'device.isMobile',
        }),
        /**
         * Determine if the moderation discard dialog is displayed.
         */
        hasModerationDiscardDialog: attr({
            default: false,
        }),
        /**
         * Determine if the moderation reject dialog is displayed.
         */
        hasModerationRejectDialog: attr({
            default: false,
        }),
        /**
         * Determines whether `this.thread` should be displayed.
         */
        hasThreadView: attr({
            compute: '_computeHasThreadView',
            dependencies: [
                'activeMobileNavbarTabId',
                'deviceIsMobile',
                'isOpen',
                'thread',
                'threadModel',
            ],
        }),
        /**
         * Formatted init thread on opening discuss for the first time,
         * when no active thread is defined. Useful to set a thread to
         * open without knowing its local id in advance.
         * Support two formats:
         *    {string} <threadModel>_<threadId>
         *    {int} <channelId> with default model of 'mail.channel'
         */
        initActiveId: attr({
            default: 'mail.box_inbox',
        }),
        /**
         * Determine whether current user is currently adding a channel from
         * the sidebar.
         */
        isAddingChannel: attr({
            compute: '_computeIsAddingChannel',
            default: false,
            dependencies: ['isOpen'],
        }),
        /**
         * Determine whether current user is currently adding a chat from
         * the sidebar.
         */
        isAddingChat: attr({
            compute: '_computeIsAddingChat',
            default: false,
            dependencies: ['isOpen'],
        }),
        /**
         * Determine whether this discuss should be focused at next render.
         */
        isDoFocus: attr({
            default: false,
        }),
        /**
         * Whether the discuss app is open or not. Useful to determine
         * whether the discuss or chat window logic should be applied.
         */
        isOpen: attr({
            default: false,
        }),
        isReplyingToMessage: attr({
            compute: '_computeIsReplyingToMessage',
            default: false,
            dependencies: ['replyingToMessage'],
        }),
        isThreadPinned: attr({
            related: 'thread.isPinned',
        }),
        /**
         * The menu_id of discuss app, received on mail/init_messaging and
         * used to open discuss from elsewhere.
         */
        menu_id: attr({
            default: null,
        }),
        messaging: one2one('mail.messaging', {
            inverse: 'discuss',
        }),
        messagingInbox: many2one('mail.thread', {
            related: 'messaging.inbox',
        }),
        renamingThreads: one2many('mail.thread'),
        /**
         * The message that is currently selected as being replied to in Inbox.
         * There is only one reply composer shown at a time, which depends on
         * this selected message.
         */
        replyingToMessage: many2one('mail.message', {
            compute: '_computeReplyingToMessage',
            dependencies: [
                'isOpen',
                'replyingToMessage',
            ],
        }),
        /**
         * The thread concerned by the reply feature in Inbox. It depends on the
         * message set to be replied, and should be considered read-only.
         */
        replyingToMessageOriginThread: many2one('mail.thread', {
            related: 'replyingToMessage.originThread',
        }),
        /**
         * The composer to display for the reply feature in Inbox. It depends
         * on the message set to be replied, and should be considered read-only.
         */
        replyingToMessageOriginThreadComposer: one2one('mail.composer', {
            inverse: 'discussAsReplying',
            related: 'replyingToMessageOriginThread.composer',
        }),
        /**
         * Quick search input value in the discuss sidebar (desktop). Useful
         * to filter channels and chats based on this input content.
         */
        sidebarQuickSearchValue: attr({
            default: "",
        }),
        /**
         * Determines the domain to apply when fetching messages for `this.thread`.
         * This value should only be written by the control panel.
         */
        stringifiedDomain: attr({
            default: '[]',
        }),
        /**
         * Determines the `mail.thread` that should be displayed by `this`.
         */
        thread: many2one('mail.thread', {
            compute: '_computeThread',
            dependencies: [
                'activeMobileNavbarTabId',
                'deviceIsMobile',
                'isThreadPinned',
                'messaging',
                'messagingInbox',
                'thread',
                'threadModel',
            ],
        }),
        threadId: attr({
            related: 'thread.id',
        }),
        threadModel: attr({
            related: 'thread.model',
        }),
        /**
         * States the `mail.thread_view` displaying `this.thread`.
         */
        threadView: one2one('mail.thread_view', {
            related: 'threadViewer.threadView',
        }),
        /**
         * Determines the `mail.thread_viewer` managing the display of `this.thread`.
         */
        threadViewer: one2one('mail.thread_viewer', {
            default: [['create']],
            inverse: 'discuss',
            isCausal: true,
        }),
    };

    Discuss.modelName = 'mail.discuss';

    return Discuss;
}

registerNewModel('mail.discuss', factory);

});