import pytz
from datetime import timedelta
from odoo import models, fields, api, _
class EventEvent(models.Model):
_inherit = "event.event"
meeting_ids = fields.One2many(
comodel_name="calendar.event",
inverse_name="res_id",
string="Linked meetings",
)
meeting_count = fields.Integer(
string="Meeting count",
compute="_count_meetings",
)
in_user_agenda = fields.Boolean(
"In User agenda",
compute="_get_in_user_agenda",
)
def _count_meetings(self):
for event in self:
event.meeting_count = len(event.meeting_ids)
def _get_in_user_agenda(self):
uid = self.env.uid
for event in self:
event.in_user_agenda = uid in event.meeting_ids.mapped("user_id").ids
def add_to_agenda(self, user_id=False):
vals_list = []
self_model_id = self.env["ir.model"]._get_id(self._name)
uid = user_id or self.env.uid
to_add = self.filtered(
lambda ee: uid not in ee.meeting_ids.mapped("user_id.id")
)
for event in to_add:
groupped_tags = {}
for tag in event.tag_ids:
categ = tag.category_id.name
if categ in groupped_tags:
groupped_tags[categ] += ", {}".format(tag.name)
else:
groupped_tags[categ] = tag.name
event_tz = pytz.timezone(event.date_tz)
vals_list.append(
{
"name": event.name + " (event Odoo)",
"description": _("
Organizer: {}{}
Note:\n
").format(
event.organizer_id.display_name,
"".join(
[
"
{} : {}".format(tag_group[0], tag_group[1])
for tag_group in groupped_tags.items()
]
),
event.note,
),
"user_id": uid,
"location": event.address_inline,
"start": event_tz.localize(event.date_begin)
.astimezone(pytz.timezone(self.env.user.tz))
.replace(tzinfo=None),
"stop": event_tz.localize(event.date_end)
.astimezone(pytz.timezone(self.env.user.tz))
.replace(tzinfo=None),
"res_id": event.id,
"res_model_id": self_model_id,
# "event_tz": event.date_tz,
}
)
if vals_list:
self.env["calendar.event"].create(vals_list)
def remove_from_agenda(self, user_id=False):
to_unlink = self.mapped("meeting_ids").filtered(
lambda meeting: meeting.user_id.id == user_id or self.env.uid
)
if to_unlink:
to_unlink.unlink()
def display_meetings(self):
self.ensure_one()
date_begin = self.date_begin.date()
return {
"name": _("Meetings"),
"type": "ir.actions.act_window",
"res_model": "calendar.event",
"views": [(False, "tree"), (False, "calendar"), (False, "form")],
"domain": [("res_id", "=", self.id), ("res_model", "=", self._name)],
"context": {
"calendar_mode": "week",
"initial_date": fields.Date.to_string(
date_begin - timedelta(days=-date_begin.weekday())
),
},
}
@api.model
def agenda_fields(self):
return [
"name",
"date_begin_located",
"date_end_located",
"date_tz",
"tag_ids",
"organizer_id",
"adress_inline",
"note",
]
def write(self, vals):
res = super().write(vals)
agenda_fields = self.agenda_fields()
meetings = self.mapped("meeting_ids")
if any(field in agenda_fields for field in vals.keys()) and meetings:
meetings.write(
dict([(field, vals[field]) for field in agenda_fields & vals.keys()])
)
return res