Debian Codegraph @

addons/mail/static/tests/mock_server/mock_models/discuss_channel.js

raw symbols SCIP
1 import { mailDataHelpers } from "@mail/../tests/mock_server/mail_mock_server";
2 import { convertBrToLineBreak } from "@mail/utils/common/format";
3
4 import { markup } from "@odoo/owl";
5
6 import {
7 Command,
8 fields,
9 getKwArgs,
10 makeKwArgs,
11 models,
12 serverState,
13 } from "@web/../tests/web_test_helpers";
14 import { serializeDateTime, today } from "@web/core/l10n/dates";
15 import { ensureArray } from "@web/core/utils/arrays";
16 import { uniqueId } from "@web/core/utils/functions";
17
18 const { DateTime } = luxon;
19
20 export class DiscussChannel extends models.ServerModel {
21 _name = "discuss.channel";
22 _inherit = ["mail.thread"];
23 _mail_post_access = "read";
24
25 author_id = fields.Many2one({
26 relation: "res.partner",
27 default: () => serverState.partnerId,
28 });
29 avatar_cache_key = fields.Char({ string: "Avatar Cache Key" });
30 channel_member_ids = fields.One2many({
31 relation: "discuss.channel.member",
32 relation_field: "channel_id",
33 string: "Members",
34 default: () => [Command.create({ partner_id: serverState.partnerId })],
35 });
36 channel_name_member_ids = fields.One2many({
37 relation: "discuss.channel.member",
38 compute: "_compute_channel_name_member_ids",
39 });
40 channel_type = fields.Generic({ default: "channel" });
41 group_public_id = fields.Generic({
42 default: () => serverState.groupId,
43 });
44 uuid = fields.Generic({
45 default: () => uniqueId("discuss.channel_uuid-"),
46 });
47 last_interest_dt = fields.Datetime({ string: "Last Interest" });
48
49 _compute_channel_name_member_ids() {
50 for (const channel of this) {
51 const members = channel.channel_member_ids ?? [];
52 members.sort();
53 channel.channel_name_member_ids = members.slice(0, 3);
54 }
55 }
56
57 /** @param {number[]} ids */
58 action_unfollow(ids) {
59 const kwargs = getKwArgs(arguments, "ids");
60 ids = kwargs.ids;
61 delete kwargs.ids;
62
63 /** @type {import("mock_models").BusBus} */
64 const BusBus = this.env["bus.bus"];
65 /** @type {import("mock_models").DiscussChannelMember} */
66 const DiscussChannelMember = this.env["discuss.channel.member"];
67 /** @type {import("mock_models").ResPartner} */
68 const ResPartner = this.env["res.partner"];
69
70 const [channel] = this.browse(ids);
71 const custom_store = new mailDataHelpers.Store(this.browse(channel.id), {
72 close_chat_window: true,
73 isLocallyPinned: false,
74 });
75 const [partner] = ResPartner.read(this.env.user.partner_id);
76 const [channelMember] = DiscussChannelMember._filter([
77 ["channel_id", "in", ids],
78 ["partner_id", "=", this.env.user.partner_id],
79 ]);
80 BusBus._sendone(partner, "mail.record/insert", custom_store.get_result());
81 if (!channelMember) {
82 return true;
83 }
84 this.write([channel.id], {
85 channel_member_ids: [Command.delete(channelMember.id)],
86 });
87 this.message_post(
88 channel.id,
89 makeKwArgs({
90 author_id: serverState.partnerId,
91 body: '<div class="o_mail_notification">left the channel</div>',
92 subtype_xmlid: "mail.mt_comment",
93 })
94 );
95 const store = new mailDataHelpers.Store(this.browse(channel.id), {
96 channel_member_ids: mailDataHelpers.Store.many(
97 DiscussChannelMember.browse(channelMember.id),
98 makeKwArgs({ only_id: true, mode: "DELETE" })
99 ),
100 member_count: DiscussChannelMember.search_count([["channel_id", "=", channel.id]]),
101 });
102 BusBus._sendone(channel, "mail.record/insert", store.get_result());
103 // limitation of mock server, partner already unsubscribed from channel
104 BusBus._sendone(partner, "mail.record/insert", store.get_result());
105 }
106
107 /**
108 * @param {number[]} ids
109 * @param {number[]} partner_ids
110 * @param {boolean} [invite_to_rtc_call=undefined]
111 */
112 add_members(ids, partner_ids, invite_to_rtc_call) {
113 const kwargs = getKwArgs(arguments, "ids", "partner_ids", "invite_to_rtc_call");
114 ids = kwargs.ids;
115 delete kwargs.ids;
116 partner_ids = kwargs.partner_ids || [];
117
118 /** @type {import("mock_models").BusBus} */
119 const BusBus = this.env["bus.bus"];
120 /** @type {import("mock_models").DiscussChannelMember} */
121 const DiscussChannelMember = this.env["discuss.channel.member"];
122 /** @type {import("mock_models").ResPartner} */
123 const ResPartner = this.env["res.partner"];
124
125 const [channel] = this.browse(ids);
126 const partners = ResPartner.browse(partner_ids);
127 for (const partner of partners) {
128 if (partner.id === this.env.user.partner_id) {
129 continue; // adding 'yourself' to the conversation is handled below
130 }
131 const body = `<div class="o_mail_notification">invited ${partner.name} to the channel</div>`;
132 const message_type = "notification";
133 const subtype_xmlid = "mail.mt_comment";
134 this.message_post(channel.id, makeKwArgs({ body, message_type, subtype_xmlid }));
135 }
136 const insertedChannelMembers = [];
137 for (const partner of partners) {
138 const channelMember = DiscussChannelMember.create({
139 channel_id: channel.id,
140 partner_id: partner.id,
141 create_uid: this.env.uid,
142 });
143 insertedChannelMembers.push(channelMember);
144 BusBus._sendone(partner, "discuss.channel/joined", {
145 channel_id: channel.id,
146 data: new mailDataHelpers.Store(this.browse(channel.id), {
147 ...this._channel_basic_info([channel.id]),
148 model: "discuss.channel",
149 })
150 .add(DiscussChannelMember.browse(channelMember), "unpin_dt")
151 .get_result(),
152 invited_by_user_id: this.env.uid,
153 });
154 }
155 const selfPartner = partners.find((partner) => partner.id === this.env.user.partner_id);
156 if (selfPartner) {
157 // needs to be done after adding 'self' as a member
158 const body = `<div class="o_mail_notification">${selfPartner.name} joined the channel</div>`;
159 const message_type = "notification";
160 const subtype_xmlid = "mail.mt_comment";
161 this.message_post(channel.id, makeKwArgs({ body, message_type, subtype_xmlid }));
162 }
163 const isSelfMember =
164 DiscussChannelMember.search_count([
165 ["partner_id", "=", this.env.user.partner_id],
166 ["channel_id", "=", channel.id],
167 ]) > 0;
168 if (isSelfMember) {
169 BusBus._sendone(
170 channel,
171 "mail.record/insert",
172 new mailDataHelpers.Store(this.browse(channel.id), {
173 invited_member_ids: kwargs.invite_to_rtc_call
174 ? [["ADD", insertedChannelMembers]]
175 : false,
176 member_count: DiscussChannelMember.search_count([
177 ["channel_id", "=", channel.id],
178 ]),
179 })
180 .add(DiscussChannelMember.browse(insertedChannelMembers))
181 .get_result()
182 );
183 }
184 return DiscussChannelMember.browse(insertedChannelMembers);
185 }
186
187 /**
188 * @param {number[]} ids
189 * @param {string} description
190 */
191 channel_change_description(ids, description) {
192 const kwargs = getKwArgs(arguments, "ids", "description");
193 ids = kwargs.ids;
194 delete kwargs.ids;
195 description = kwargs.description || "";
196
197 const [channel] = this.browse(ids);
198 this.write([channel.id], { description });
199 }
200
201 unlink(ids) {
202 /** @type {import("mock_models").BusBus} */
203 const BusBus = this.env["bus.bus"];
204
205 const channels = this.browse(ids);
206 for (const channel of channels) {
207 BusBus._sendone(channel, "discuss.channel/delete", { id: channel.id });
208 }
209 return super.unlink(...arguments);
210 }
211
212 /**
213 * @param {string} name
214 * @param {string} [group_id]
215 */
216 _create_channel(name, group_id) {
217 const kwargs = getKwArgs(arguments, "name", "group_id");
218 name = kwargs.name;
219 group_id = kwargs.group_id;
220
221 /** @type {import("mock_models").DiscussChannel} */
222 const DiscussChannel = this.env["discuss.channel"];
223 /** @type {import("mock_models").ResPartner} */
224 const ResPartner = this.env["res.partner"];
225
226 const id = this.create({
227 channel_member_ids: [Command.create({ partner_id: this.env.user.partner_id })],
228 channel_type: "channel",
229 name,
230 group_public_id: group_id,
231 });
232 this.write([id], { group_public_id: group_id });
233 this.message_post(
234 id,
235 makeKwArgs({
236 body: `<div class="o_mail_notification">created <a href="#" class="o_channel_redirect" data-oe-id="${id}">#${name}</a></div>`,
237 message_type: "notification",
238 })
239 );
240 const [partner] = ResPartner.read(this.env.user.partner_id);
241 this._broadcast([id], [partner]);
242 return DiscussChannel.browse(id);
243 }
244
245 _channel_basic_info_fields() {
246 return [
247 "avatar_cache_key",
248 "channel_type",
249 "create_uid",
250 "default_display_mode",
251 "description",
252 "group_public_id",
253 "last_interest_dt",
254 "name",
255 "uuid",
256 ];
257 }
258
259 /** @param {number[]} ids */
260 _channel_basic_info(ids) {
261 const kwargs = getKwArgs(arguments, "ids");
262 ids = kwargs.ids;
263 delete kwargs.ids;
264
265 /** @type {import("mock_models").DiscussChannelMember} */
266 const DiscussChannelMember = this.env["discuss.channel.member"];
267
268 const [data] = this._read_format(ids, this._channel_basic_info_fields(), false);
269 const [channel] = this.browse(ids);
270 const memberOfCurrentUser = this._find_or_create_member_for_self(channel.id);
271 Object.assign(data, {
272 is_editable: (() => {
273 if (channel.channel_type === "channel") {
274 // Match the ACL rules
275 return (
276 !channel.group_public_id ||
277 this.env.user.group_ids.includes(channel.group_public_id)
278 );
279 }
280 return Boolean(memberOfCurrentUser);
281 })(),
282 group_ids: channel.group_ids,
283 member_count: DiscussChannelMember.search_count([["channel_id", "=", channel.id]]),
284 });
285 return data;
286 }
287
288 /** @param {number[]} ids */
289 channel_fetched(ids) {
290 const kwargs = getKwArgs(arguments, "ids");
291 ids = kwargs.ids;
292 delete kwargs.ids;
293
294 /** @type {import("mock_models").BusBus} */
295 const BusBus = this.env["bus.bus"];
296 /** @type {import("mock_models").DiscussChannelMember} */
297 const DiscussChannelMember = this.env["discuss.channel.member"];
298 /** @type {import("mock_models").MailMessage} */
299 const MailMessage = this.env["mail.message"];
300
301 const channels = this.browse(ids);
302 for (const channel of channels) {
303 if (!["chat", "whatsapp"].includes(channel.channel_type)) {
304 continue;
305 }
306 const channelMessages = MailMessage._filter([
307 ["model", "=", "discuss.channel"],
308 ["res_id", "=", channel.id],
309 ]);
310 const lastMessage = channelMessages.reduce((lastMessage, message) => {
311 if (message.id > lastMessage.id) {
312 return message;
313 }
314 return lastMessage;
315 }, channelMessages[0]);
316 if (!lastMessage) {
317 continue;
318 }
319 const memberOfCurrentUser = this._find_or_create_member_for_self(channel.id);
320 DiscussChannelMember.write([memberOfCurrentUser.id], {
321 fetched_message_id: lastMessage.id,
322 });
323 BusBus._sendone(channel, "discuss.channel.member/fetched", {
324 channel_id: channel.id,
325 id: memberOfCurrentUser.id,
326 last_message_id: lastMessage.id,
327 partner_id: this.env.user.partner_id,
328 });
329 }
330 }
331
332 /**
333 * @param {number[]} partners_to
334 * @param {boolean} [pin=true]
335 */
336 _get_or_create_chat(partners_to, pin) {
337 const kwargs = getKwArgs(arguments, "partners_to", "pin");
338 partners_to = kwargs.partners_to || [];
339 pin = kwargs.pin ?? true;
340
341 /** @type {import("mock_models").DiscussChannel} */
342 const DiscussChannel = this.env["discuss.channel"];
343 /** @type {import("mock_models").DiscussChannelMember} */
344 const DiscussChannelMember = this.env["discuss.channel.member"];
345 /** @type {import("mock_models").ResPartner} */
346 const ResPartner = this.env["res.partner"];
347
348 if (!partners_to.includes(this.env.user.partner_id)) {
349 partners_to.push(this.env.user.partner_id);
350 }
351 const partners = ResPartner.browse(partners_to);
352 const channels = this.search_read([["channel_type", "=", "chat"]]);
353 for (const channel of channels) {
354 const channelMemberIds = DiscussChannelMember.search([
355 ["channel_id", "=", channel.id],
356 ["partner_id", "in", partners_to],
357 ]);
358 if (
359 channelMemberIds.length === partners.length &&
360 channel.channel_member_ids.length === partners.length
361 ) {
362 return DiscussChannel.browse(channel.id);
363 }
364 }
365 const id = this.create({
366 channel_member_ids: partners.map((partner) =>
367 Command.create({
368 partner_id: partner.id,
369 unpin_dt:
370 partner.id == serverState.partnerId ? false : serializeDateTime(today()),
371 })
372 ),
373 channel_type: "chat",
374 name: partners.map((partner) => partner.name).join(", "),
375 });
376 this._broadcast(
377 [id],
378 partners.map(({ id }) => id)
379 );
380 return DiscussChannel.browse(id);
381 }
382
383 /** @param {number[]} ids */
384 _to_store(store, fields) {
385 const kwargs = getKwArgs(arguments, "store", "fields");
386 store = kwargs.store;
387 fields = kwargs.fields;
388
389 if (fields && Array.isArray(fields) && fields.length) {
390 store._add_record_fields(this, fields);
391 } else {
392 const bus_last_id = this.env["bus.bus"].lastBusNotificationId;
393 /** @type {import("mock_models").DiscussChannelMember} */
394 const DiscussChannelMember = this.env["discuss.channel.member"];
395 /** @type {import("mock_models").DiscussChannelRtcSession} */
396 const DiscussChannelRtcSession = this.env["discuss.channel.rtc.session"];
397 /** @type {import("mock_models").MailMessage} */
398 const MailMessage = this.env["mail.message"];
399 /** @type {import("mock_models").MailNotification} */
400 const MailNotification = this.env["mail.notification"];
401 /** @type {import("mock_models").ResGroups}*/
402 const ResGroups = this.env["res.groups"];
403
404 for (const channel of this) {
405 const members = DiscussChannelMember.browse(channel.channel_member_ids);
406 const messages = MailMessage._filter([
407 ["model", "=", "discuss.channel"],
408 ["res_id", "=", channel.id],
409 ]);
410 const res = this._channel_basic_info([channel.id]);
411 res.fetchChannelInfoState = "fetched";
412 res.parent_channel_id = mailDataHelpers.Store.one(
413 this.env["discuss.channel"].browse(channel.parent_channel_id)
414 );
415 res.from_message_id = mailDataHelpers.Store.one(
416 MailMessage.browse(channel.from_message_id)
417 );
418 res.group_public_id = mailDataHelpers.Store.one(
419 ResGroups.browse(channel.group_public_id),
420 makeKwArgs({ fields: ["full_name"] })
421 );
422 if (this.env.user) {
423 const message_needaction_counter = MailNotification._filter([
424 ["res_partner_id", "=", this.env.user.partner_id],
425 ["is_read", "=", false],
426 ["mail_message_id", "in", messages.map((message) => message.id)],
427 ]).length;
428 Object.assign(res, {
429 message_needaction_counter,
430 message_needaction_counter_bus_id: bus_last_id,
431 });
432 }
433 const memberOfCurrentUser = this._find_or_create_member_for_self(channel.id);
434 if (memberOfCurrentUser) {
435 const message_unread_counter = this.env[
436 "discuss.channel.member"
437 ]._compute_message_unread_counter([memberOfCurrentUser.id]);
438 DiscussChannelMember.write([memberOfCurrentUser.id], {
439 message_unread_counter,
440 });
441 store.add(
442 DiscussChannelMember.browse(memberOfCurrentUser.id),
443 makeKwArgs({
444 extra_fields: [
445 "custom_channel_name",
446 "last_interest_dt",
447 "message_unread_counter",
448 mailDataHelpers.Store.one("rtc_inviting_session_id"),
449 "unpin_dt",
450 ],
451 })
452 );
453 }
454 if (channel.channel_type !== "channel") {
455 const otherMembers = members.filter(
456 (member) => member.id !== memberOfCurrentUser?.id
457 );
458 store.add(otherMembers);
459 }
460 if (this._member_based_naming_channel_types().includes(channel.channel_type)) {
461 res.channel_name_member_ids = mailDataHelpers.Store.many(
462 this.env["discuss.channel.member"].browse(channel.channel_name_member_ids)
463 );
464 }
465 res.rtc_session_ids = mailDataHelpers.Store.many(
466 DiscussChannelRtcSession.browse(channel.rtc_session_ids),
467 makeKwArgs({ extra: true, mode: "ADD" })
468 );
469 store._add_record_fields(this.browse(channel.id), res);
470 }
471 }
472 }
473
474 _member_based_naming_channel_types() {
475 return ["group"];
476 }
477
478 /**
479 * @param {number[]} ids
480 * @param {boolean} [pinned=false]
481 */
482 channel_pin(ids, pinned) {
483 const kwargs = getKwArgs(arguments, "ids", "pinned");
484 ids = kwargs.ids;
485 delete kwargs.ids;
486 pinned = kwargs.pinned ?? false;
487
488 /** @type {import("mock_models").BusBus} */
489 const BusBus = this.env["bus.bus"];
490 /** @type {import("mock_models").DiscussChannel} */
491 const DiscussChannel = this.env["discuss.channel"];
492 /** @type {import("mock_models").DiscussChannelMember} */
493 const DiscussChannelMember = this.env["discuss.channel.member"];
494 /** @type {import("mock_models").ResPartner} */
495 const ResPartner = this.env["res.partner"];
496
497 const [channel] = this.browse(ids);
498 const memberOfCurrentUser = this._find_or_create_member_for_self(channel.id);
499 if (memberOfCurrentUser && memberOfCurrentUser.is_pinned !== pinned) {
500 DiscussChannelMember.write([memberOfCurrentUser.id], {
501 unpin_dt: pinned ? false : serializeDateTime(today()),
502 });
503 }
504 const [partner] = ResPartner.read(this.env.user.partner_id);
505 if (!pinned) {
506 BusBus._sendone(
507 partner,
508 "mail.record/insert",
509 new mailDataHelpers.Store(DiscussChannel.browse(channel.id), {
510 close_chat_window: true,
511 id: channel.id,
512 }).get_result()
513 );
514 } else {
515 BusBus._sendone(
516 partner,
517 "mail.record/insert",
518 new mailDataHelpers.Store(DiscussChannel.browse(channel.id)).get_result()
519 );
520 }
521 }
522
523 /**
524 * @param {number[]} ids
525 * @param {string} name
526 */
527 channel_rename(ids, name) {
528 const kwargs = getKwArgs(arguments, "ids", "name");
529 ids = kwargs.ids;
530 delete kwargs.ids;
531 name = kwargs.name || "";
532
533 const [channel] = this.browse(ids);
534 this.write([channel.id], { name });
535 this.message_post(
536 channel.id,
537 makeKwArgs({
538 body: `<div data-oe-type="channel_rename" class="o_mail_notification">${name}</div>`,
539 message_type: "notification",
540 subtype_xmlid: "mail.mt_comment",
541 })
542 );
543 }
544
545 /**
546 * @param {number[]} ids
547 * @param {string} name
548 */
549 channel_set_custom_name(ids, name) {
550 const kwargs = getKwArgs(arguments, "ids", "name");
551 ids = kwargs.ids;
552 delete kwargs.ids;
553 name = kwargs.name || "";
554
555 /** @type {import("mock_models").BusBus} */
556 const BusBus = this.env["bus.bus"];
557 /** @type {import("mock_models").DiscussChannelMember} */
558 const DiscussChannelMember = this.env["discuss.channel.member"];
559 /** @type {import("mock_models").ResPartner} */
560 const ResPartner = this.env["res.partner"];
561
562 const channelId = ids[0]; // simulate ensure_one.
563 const [memberIdOfCurrentUser] = DiscussChannelMember.search([
564 ["partner_id", "=", this.env.user.partner_id],
565 ["channel_id", "=", channelId],
566 ]);
567 DiscussChannelMember.write([memberIdOfCurrentUser], {
568 custom_channel_name: name,
569 });
570 const [partner] = ResPartner.read(this.env.user.partner_id);
571 BusBus._sendone(
572 partner,
573 "mail.record/insert",
574 new mailDataHelpers.Store(DiscussChannelMember.browse(memberIdOfCurrentUser), {
575 custom_channel_name: name,
576 }).get_result()
577 );
578 }
579
580 /**
581 * @param {number[]} partners_to
582 * @param {string} [default_display_mode=undefined]
583 * @param {string} name
584 * */
585 _create_group(partners_to, default_display_mode, name) {
586 const kwargs = getKwArgs(arguments, "partners_to", "default_display_mode", "name");
587 partners_to = kwargs.partners_to || [];
588 default_display_mode = kwargs.default_display_mode;
589 name = kwargs.name || "";
590
591 /** @type {import("mock_models").DiscussChannel} */
592 const DiscussChannel = this.env["discuss.channel"];
593 /** @type {import("mock_models").ResPartner} */
594 const ResPartner = this.env["res.partner"];
595
596 const partners = ResPartner.browse(partners_to);
597 const id = this.create({
598 channel_type: "group",
599 channel_member_ids: partners.map((partner) =>
600 Command.create({ partner_id: partner.id })
601 ),
602 default_display_mode: default_display_mode,
603 name,
604 });
605 this._broadcast(
606 [id],
607 partners.map((partner) => partner.id)
608 );
609 return DiscussChannel.browse(id);
610 }
611
612 _create_sub_channel(ids, from_message_id, name) {
613 const kwargs = getKwArgs(arguments, "ids", "from_message_id", "name");
614 ids = kwargs.ids;
615 from_message_id = kwargs.from_message_id;
616 name = kwargs.name;
617 delete kwargs.name;
618 delete kwargs.ids;
619 delete kwargs.from_message_id;
620 /** @type {import("mock_models").MailMessage} */
621 const MailMessage = this.env["mail.message"];
622 /** @type {import("mock_models").BusBus} */
623 const BusBus = this.env["bus.bus"];
624 /** @type {import {"mock_model"}.ResPartner} */
625 const ResPartner = this.env["res.partner"];
626 const self = this.browse(ids)[0];
627 let message;
628 if (from_message_id) {
629 [message] = MailMessage.browse(from_message_id);
630 }
631 const [partner] = ResPartner._get_current_persona();
632 const subChannels = this.browse(
633 this.create({
634 channel_member_ids: [Command.create({ partner_id: partner.id })],
635 channel_type: "channel",
636 group_public_id: self.group_public_id,
637 from_message_id: message?.id,
638 name: message
639 ? convertBrToLineBreak(markup(message.body)).substring(0, 30)
640 : name || "New Thread",
641 parent_channel_id: self.id,
642 })
643 );
644 const store = new mailDataHelpers.Store(subChannels);
645 BusBus._sendone(partner, "mail.record/insert", store.get_result());
646 this.message_post(
647 self.id,
648 makeKwArgs({
649 body: `${partner.display_name} started a thread: <a href='#' class='o_channel_redirect' data-oe-id='${subChannels[0].id}' data-oe-model='discuss.channel'>${subChannels[0].name}</a>.`,
650 message_type: "notification",
651 subtype_xmlid: "mail.mt_comment",
652 })
653 );
654 return {
655 store_data: store.get_result(),
656 sub_channel: subChannels[0].id,
657 };
658 }
659
660 /** @param {number} id */
661 execute_command_help(ids) {
662 const kwargs = getKwArgs(arguments, "ids");
663 ids = kwargs.ids;
664 delete kwargs.ids;
665
666 /** @type {import("mock_models").BusBus} */
667 const BusBus = this.env["bus.bus"];
668 /** @type {import("mock_models").DiscussChannelMember} */
669 const DiscussChannelMember = this.env["discuss.channel.member"];
670 /** @type {import("mock_models").ResPartner} */
671 const ResPartner = this.env["res.partner"];
672
673 const id = ids[0];
674 const [channel] = this.search_read([["id", "=", id]]);
675 const notifBody = /* html */ `
676 <span class="o_mail_notification">You are in ${
677 channel.channel_type === "channel" ? "channel" : "a private conversation with"
678 }
679 <b>${
680 channel.channel_type === "channel"
681 ? `#${channel.name}`
682 : channel.channel_member_ids.map(
683 (id) => DiscussChannelMember.search_read([["id", "=", id]])[0].name
684 )
685 }</b>.<br><br>
686
687 Type <b>@username</b> to mention someone, and grab their attention.<br>
688 Type <b>#channel</b> to mention a channel.<br>
689 Type <b>/command</b> to execute a command.<br></span>
690 `;
691 const [partner] = ResPartner.read(this.env.user.partner_id);
692 BusBus._sendone(partner, "discuss.channel/transient_message", {
693 body: notifBody,
694 channel_id: channel.id,
695 });
696 return true;
697 }
698
699 /** @param {number[]} ids */
700 execute_command_leave(ids) {
701 const kwargs = getKwArgs(arguments, "ids");
702 ids = kwargs.ids;
703 delete kwargs.ids;
704
705 const [channel] = this.browse(ids);
706 if (channel.channel_type === "channel") {
707 this.action_unfollow([channel.id]);
708 } else {
709 this.channel_pin([channel.id], false);
710 }
711 }
712
713 /** @param {number[]} ids */
714 execute_command_who(ids) {
715 const kwargs = getKwArgs(arguments, "ids");
716 ids = kwargs.ids;
717 delete kwargs.ids;
718
719 /** @type {import("mock_models").BusBus} */
720 const BusBus = this.env["bus.bus"];
721 /** @type {import("mock_models").DiscussChannelMember} */
722 const DiscussChannelMember = this.env["discuss.channel.member"];
723 /** @type {import("mock_models").ResPartner} */
724 const ResPartner = this.env["res.partner"];
725
726 const channels = this.browse(ids);
727 for (const channel of channels) {
728 const members = DiscussChannelMember.browse(channel.channel_member_ids);
729 const otherPartnerIds = members
730 .filter(
731 (member) => member.partner_id && member.partner_id !== this.env.user.partner_id
732 )
733 .map((member) => member.partner_id);
734 const otherPartners = ResPartner.browse(otherPartnerIds);
735 let message = "You are alone in this channel.";
736 if (otherPartners.length > 0) {
737 message = `Users in this channel: ${otherPartners
738 .map((partner) => partner.name)
739 .join(", ")} and you`;
740 }
741 const [partner] = ResPartner.read(this.env.user.partner_id);
742 BusBus._sendone(partner, "discuss.channel/transient_message", {
743 body: `<span class="o_mail_notification">${message}</span>`,
744 channel_id: channel.id,
745 });
746 }
747 }
748
749 get_channels_as_member() {
750 /** @type {import("mock_models").DiscussChannelMember} */
751 const DiscussChannelMember = this.env["discuss.channel.member"];
752 /** @type {import("mock_models").MailGuest} */
753 const MailGuest = this.env["mail.guest"];
754
755 const guest = MailGuest._get_guest_from_context();
756 const memberDomain = guest
757 ? [["guest_id", "=", guest.id]]
758 : [["partner_id", "=", this.env.user.partner_id]];
759 const members = DiscussChannelMember._filter(memberDomain);
760 const pinnedMembers = members.filter((member) => member.is_pinned);
761 const channels = this._filter([
762 ["channel_type", "in", ["channel", "group"]],
763 ["channel_member_ids", "in", members.map((member) => member.id)],
764 ]);
765 const pinnedChannels = this._filter([
766 ["channel_type", "not in", ["channel", "group"]],
767 ["channel_member_ids", "in", pinnedMembers.map((member) => member.id)],
768 ]);
769 return [...channels, ...pinnedChannels];
770 }
771
772 /**
773 * @param {string} search
774 * @param {limit} number
775 */
776 get_mention_suggestions(search, limit) {
777 const kwargs = getKwArgs(arguments, "search", "limit");
778 search = kwargs.search || "";
779 limit = kwargs.limit || 8;
780
781 /**
782 * Returns the given list of channels after filtering it according to
783 * the logic of the Python method `get_mention_suggestions` for the
784 * given search term. The result is truncated to the given limit and
785 * formatted as expected by the original method.
786 *
787 * @param {this[]} channels
788 * @param {string} search
789 * @param {number} limit
790 * @returns {Object[]}
791 */
792 const mentionSuggestionsFilter = (channels, search, limit) => {
793 const matchingChannels = channels.filter((channel) => {
794 // no search term is considered as return all
795 if (!search) {
796 return true;
797 }
798 // otherwise name or email must match search term
799 if (channel.name && channel.name.includes(search)) {
800 return true;
801 }
802 return false;
803 });
804 matchingChannels.length = Math.min(matchingChannels.length, limit);
805 return matchingChannels;
806 };
807 const mentionSuggestions = mentionSuggestionsFilter(this, search, limit);
808 const store = new mailDataHelpers.Store(
809 mentionSuggestions,
810 makeKwArgs({
811 fields: [
812 "name",
813 "channel_type",
814 "group_public_id",
815 mailDataHelpers.Store.one("parent_channel_id"),
816 ],
817 })
818 );
819 return store.get_result();
820 }
821
822 /**
823 * @param {number[]} ids
824 * @param {number[]} known_member_ids
825 */
826 _load_more_members(ids, known_member_ids) {
827 const kwargs = getKwArgs(arguments, "ids", "known_member_ids");
828 ids = kwargs.ids;
829 delete kwargs.ids;
830 known_member_ids = kwargs.known_member_ids || [];
831
832 /** @type {import("mock_models").DiscussChannelMember} */
833 const DiscussChannelMember = this.env["discuss.channel.member"];
834
835 const members = DiscussChannelMember.search(
836 [
837 ["id", "not in", known_member_ids],
838 ["channel_id", "in", ids],
839 ],
840 makeKwArgs({ limit: 100 })
841 );
842 const member_count = DiscussChannelMember.search_count([["channel_id", "in", ids]]);
843 return new mailDataHelpers.Store(this.browse(ids[0]), { member_count })
844 .add(DiscussChannelMember.browse(members))
845 .get_result();
846 }
847
848 /** @param {number} id */
849 message_post(id) {
850 const kwargs = getKwArgs(arguments, "id");
851 id = kwargs.id;
852 delete kwargs.id;
853
854 /** @type {import("mock_models").DiscussChannelMember} */
855 const DiscussChannelMember = this.env["discuss.channel.member"];
856 /** @type {import("mock_models").MailThread} */
857 const MailThread = this.env["mail.thread"];
858
859 kwargs.message_type ||= "notification";
860 const [channel] = this.browse(id);
861 this.write([id], {
862 last_interest_dt: serializeDateTime(DateTime.now()),
863 });
864 if (kwargs.special_mentions?.includes("everyone")) {
865 kwargs["partner_ids"] = DiscussChannelMember._filter([
866 ["channel_id", "=", channel.id],
867 ]).map((member) => member.partner_id);
868 }
869 delete kwargs.special_mentions;
870 const messageIds = MailThread.message_post.call(this, [id], kwargs);
871 // simulate compute of message_unread_counter
872 const memberOfCurrentUser = this._find_or_create_member_for_self(channel.id);
873 const otherMembers = DiscussChannelMember._filter([
874 ["channel_id", "=", channel.id],
875 ["id", "!=", memberOfCurrentUser?.id || false],
876 ]);
877 for (const member of otherMembers) {
878 DiscussChannelMember.write([member.id], {
879 message_unread_counter: member.message_unread_counter + 1,
880 });
881 }
882 return messageIds;
883 }
884
885 /**
886 * @param {number} id
887 * @param {number} message_id
888 * @param {boolean} pinned
889 */
890 set_message_pin(id, message_id, pinned) {
891 const kwargs = getKwArgs(arguments, "id", "message_id", "pinned");
892 id = kwargs.id;
893 delete kwargs.id;
894 message_id = kwargs.message_id;
895 pinned = kwargs.pinned;
896
897 /** @type {import("mock_models").BusBus} */
898 const BusBus = this.env["bus.bus"];
899 /** @type {import("mock_models").MailMessage} */
900 const MailMessage = this.env["mail.message"];
901 /** @type {import("mock_models").ResPartner} */
902 const ResPartner = this.env["res.partner"];
903
904 const pinned_at = pinned && serializeDateTime(DateTime.now());
905 MailMessage.write([message_id], { pinned_at });
906 const [partner] = ResPartner.read(this.env.user.partner_id);
907 const notification = `<div data-oe-type="pin" class="o_mail_notification">
908 ${partner.display_name} pinned a
909 <a href="#" data-oe-type="highlight" data-oe-id='${message_id}'>message</a> to this channel.
910 <a href="#" data-oe-type="pin-menu">See all pinned messages</a>
911 </div>`;
912 this.message_post(
913 id,
914 makeKwArgs({
915 body: notification,
916 message_type: "notification",
917 subtype_xmlid: "mail.mt_comment",
918 })
919 );
920 const [channel] = this.read(id);
921 BusBus._sendone(
922 channel,
923 "mail.record/insert",
924 new mailDataHelpers.Store(MailMessage.browse(message_id), { pinned_at }).get_result()
925 );
926 }
927
928 /** @type {typeof models.Model["prototype"]["write"]} */
929 write(idOrIds, values) {
930 const kwargs = getKwArgs(arguments, "ids", "vals");
931 ({ ids: idOrIds, vals: values } = kwargs);
932
933 /** @type {import("mock_models").BusBus} */
934 const BusBus = this.env["bus.bus"];
935
936 const channels = this.browse(ensureArray(idOrIds));
937 const basicInfoByChannelId = Object.fromEntries(
938 channels.map((channel) => [channel.id, this._channel_basic_info(channel.id)])
939 );
940 for (const channel of channels) {
941 if ("image_128" in values) {
942 super.write(channel.id, {
943 avatar_cache_key: DateTime.utc().toFormat("yyyyMMddHHmmss"),
944 });
945 }
946 }
947 const result = super.write(...arguments);
948 const notifications = [];
949 for (const channel of channels) {
950 const basicInfo = this._channel_basic_info(channel.id);
951 const previousBasicInfo = basicInfoByChannelId[channel.id];
952 const changes = [];
953 for (const key of Object.keys(basicInfo)) {
954 if (basicInfo[key] !== previousBasicInfo[key]) {
955 changes.push([key, basicInfo[key]]);
956 }
957 }
958 if (changes.length) {
959 notifications.push([
960 channel,
961 "mail.record/insert",
962 new mailDataHelpers.Store(
963 this.browse(channel.id),
964 Object.fromEntries(changes)
965 ).get_result(),
966 ]);
967 }
968 }
969 if (notifications.length) {
970 BusBus._sendmany(notifications);
971 }
972 return result;
973 }
974
975 /**
976 * @param {number[]} ids
977 * @param {number[]} partner_ids
978 */
979 _broadcast(ids, partner_ids) {
980 const kwargs = getKwArgs(arguments, "ids", "partner_ids");
981 ids = kwargs.ids;
982 delete kwargs.ids;
983 partner_ids = kwargs.partner_ids;
984
985 /** @type {import("mock_models").BusBus} */
986 const BusBus = this.env["bus.bus"];
987
988 const notifications = this._channel_channel_notifications(ids, partner_ids);
989 BusBus._sendmany(notifications);
990 }
991
992 /**
993 * @param {number} id
994 * @param {number[]} partner_ids
995 */
996 _channel_channel_notifications(ids, partner_ids) {
997 const kwargs = getKwArgs(arguments, "ids", "partner_ids");
998 ids = kwargs.ids;
999 delete kwargs.ids;
1000 partner_ids = kwargs.partner_ids;
1001
1002 /** @type {import("mock_models").DiscussChannel} */
1003 const DiscussChannel = this.env["discuss.channel"];
1004 /** @type {import("mock_models").ResPartner} */
1005 const ResPartner = this.env["res.partner"];
1006 /** @type {import("mock_models").ResUsers} */
1007 const ResUsers = this.env["res.users"];
1008
1009 const notifications = [];
1010 for (const partner_id of partner_ids) {
1011 const user = ResUsers._filter([["partner_id", "in", partner_id]])[0];
1012 if (!user) {
1013 continue;
1014 }
1015 // Note: `_to_store` on the server is supposed to be called with
1016 // the proper user context but this is not done here for simplicity.
1017 const [relatedPartner] = ResPartner.search_read([["id", "=", partner_id]]);
1018 for (const channelId of ids) {
1019 notifications.push([
1020 relatedPartner,
1021 "mail.record/insert",
1022 new mailDataHelpers.Store(DiscussChannel.browse(channelId)).get_result(),
1023 ]);
1024 }
1025 }
1026 return notifications;
1027 }
1028
1029 _types_allowing_seen_infos() {
1030 return ["chat", "group"];
1031 }
1032
1033 _get_channels_as_member() {
1034 /** @type {import("mock_models").DiscussChannelMember} */
1035 const DiscussChannelMember = this.env["discuss.channel.member"];
1036 /** @type {import("mock_models").MailGuest} */
1037 const MailGuest = this.env["mail.guest"];
1038
1039 const guest = MailGuest._get_guest_from_context();
1040 const memberDomain = guest
1041 ? [["guest_id", "=", guest.id]]
1042 : [["partner_id", "=", this.env.user.partner_id]];
1043 const members = DiscussChannelMember._filter(memberDomain);
1044 const pinnedMembers = members.filter((member) => member.is_pinned);
1045 const channels = this._filter([
1046 ["channel_type", "in", ["channel", "group"]],
1047 ["channel_member_ids", "in", members.map((member) => member.id)],
1048 ]);
1049 const pinnedChannels = this._filter([
1050 ["channel_type", "not in", ["channel", "group"]],
1051 ["channel_member_ids", "in", pinnedMembers.map((member) => member.id)],
1052 ]);
1053 return channels.concat(pinnedChannels);
1054 }
1055
1056 /**
1057 * @param {number} id
1058 * @returns {import("mock_models").DiscussChannelMember}
1059 */
1060 _find_or_create_member_for_self(id) {
1061 /** @type {import("mock_models").DiscussChannelMember} */
1062 const DiscussChannelMember = this.env["discuss.channel.member"];
1063 /** @type {import("mock_models").ResPartner} */
1064 const ResPartner = this.env["res.partner"];
1065
1066 const [partner, guest] = ResPartner._get_current_persona();
1067 if (!partner && !guest) {
1068 return;
1069 }
1070 return DiscussChannelMember._filter([
1071 ["channel_id", "=", id],
1072 guest ? ["guest_id", "=", guest.id] : ["partner_id", "=", partner.id],
1073 ])[0];
1074 }
1075
1076 _find_or_create_persona_for_channel(id, guest_name) {
1077 const kwargs = getKwArgs(arguments, "id", "guest_name");
1078 id = kwargs.id;
1079 delete kwargs.id;
1080 guest_name = kwargs.guest_name;
1081
1082 /** @type {import("mock_models").MailGuest} */
1083 const MailGuest = this.env["mail.guest"];
1084
1085 if (this._find_or_create_member_for_self(id)) {
1086 return;
1087 }
1088 const guestId =
1089 MailGuest._get_guest_from_context()?.id ?? MailGuest.create({ name: guest_name });
1090 this.write([id], {
1091 channel_member_ids: [Command.create({ guest_id: guestId })],
1092 });
1093 MailGuest._set_auth_cookie(guestId);
1094 }
1095 }