calendar_recurrence.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from datetime import datetime, time
  4. import pytz
  5. from dateutil import rrule
  6. from dateutil.relativedelta import relativedelta
  7. from odoo import api, fields, models, _
  8. from odoo.exceptions import UserError
  9. from odoo.addons.base.models.res_partner import _tz_get
  10. MAX_RECURRENT_EVENT = 720
  11. SELECT_FREQ_TO_RRULE = {
  12. 'daily': rrule.DAILY,
  13. 'weekly': rrule.WEEKLY,
  14. 'monthly': rrule.MONTHLY,
  15. 'yearly': rrule.YEARLY,
  16. }
  17. RRULE_FREQ_TO_SELECT = {
  18. rrule.DAILY: 'daily',
  19. rrule.WEEKLY: 'weekly',
  20. rrule.MONTHLY: 'monthly',
  21. rrule.YEARLY: 'yearly',
  22. }
  23. RRULE_WEEKDAY_TO_FIELD = {
  24. rrule.MO.weekday: 'mon',
  25. rrule.TU.weekday: 'tue',
  26. rrule.WE.weekday: 'wed',
  27. rrule.TH.weekday: 'thu',
  28. rrule.FR.weekday: 'fri',
  29. rrule.SA.weekday: 'sat',
  30. rrule.SU.weekday: 'sun',
  31. }
  32. RRULE_WEEKDAYS = {'SUN': 'SU', 'MON': 'MO', 'TUE': 'TU', 'WED': 'WE', 'THU': 'TH', 'FRI': 'FR', 'SAT': 'SA'}
  33. RRULE_TYPE_SELECTION = [
  34. ('daily', 'Days'),
  35. ('weekly', 'Weeks'),
  36. ('monthly', 'Months'),
  37. ('yearly', 'Years'),
  38. ]
  39. END_TYPE_SELECTION = [
  40. ('count', 'Number of repetitions'),
  41. ('end_date', 'End date'),
  42. ('forever', 'Forever'),
  43. ]
  44. MONTH_BY_SELECTION = [
  45. ('date', 'Date of month'),
  46. ('day', 'Day of month'),
  47. ]
  48. WEEKDAY_SELECTION = [
  49. ('MON', 'Monday'),
  50. ('TUE', 'Tuesday'),
  51. ('WED', 'Wednesday'),
  52. ('THU', 'Thursday'),
  53. ('FRI', 'Friday'),
  54. ('SAT', 'Saturday'),
  55. ('SUN', 'Sunday'),
  56. ]
  57. BYDAY_SELECTION = [
  58. ('1', 'First'),
  59. ('2', 'Second'),
  60. ('3', 'Third'),
  61. ('4', 'Fourth'),
  62. ('-1', 'Last'),
  63. ]
  64. def freq_to_select(rrule_freq):
  65. return RRULE_FREQ_TO_SELECT[rrule_freq]
  66. def freq_to_rrule(freq):
  67. return SELECT_FREQ_TO_RRULE[freq]
  68. def weekday_to_field(weekday_index):
  69. return RRULE_WEEKDAY_TO_FIELD.get(weekday_index)
  70. class RecurrenceRule(models.Model):
  71. _name = 'calendar.recurrence'
  72. _description = 'Event Recurrence Rule'
  73. name = fields.Char(compute='_compute_name', store=True)
  74. base_event_id = fields.Many2one(
  75. 'calendar.event', ondelete='set null', copy=False) # store=False ?
  76. calendar_event_ids = fields.One2many('calendar.event', 'recurrence_id')
  77. event_tz = fields.Selection(
  78. _tz_get, string='Timezone',
  79. default=lambda self: self.env.context.get('tz') or self.env.user.tz)
  80. rrule = fields.Char(compute='_compute_rrule', inverse='_inverse_rrule', store=True)
  81. dtstart = fields.Datetime(compute='_compute_dtstart')
  82. rrule_type = fields.Selection(RRULE_TYPE_SELECTION, default='weekly')
  83. end_type = fields.Selection(END_TYPE_SELECTION, default='count')
  84. interval = fields.Integer(default=1)
  85. count = fields.Integer(default=1)
  86. mon = fields.Boolean()
  87. tue = fields.Boolean()
  88. wed = fields.Boolean()
  89. thu = fields.Boolean()
  90. fri = fields.Boolean()
  91. sat = fields.Boolean()
  92. sun = fields.Boolean()
  93. month_by = fields.Selection(MONTH_BY_SELECTION, default='date')
  94. day = fields.Integer(default=1)
  95. weekday = fields.Selection(WEEKDAY_SELECTION, string='Weekday')
  96. byday = fields.Selection(BYDAY_SELECTION, string='By day')
  97. until = fields.Date('Repeat Until')
  98. _sql_constraints = [
  99. ('month_day',
  100. "CHECK (rrule_type != 'monthly' "
  101. "OR month_by != 'day' "
  102. "OR day >= 1 AND day <= 31 "
  103. "OR weekday in %s AND byday in %s)"
  104. % (tuple(wd[0] for wd in WEEKDAY_SELECTION), tuple(bd[0] for bd in BYDAY_SELECTION)),
  105. "The day must be between 1 and 31"),
  106. ]
  107. @api.depends('rrule')
  108. def _compute_name(self):
  109. for recurrence in self:
  110. period = dict(RRULE_TYPE_SELECTION)[recurrence.rrule_type]
  111. every = _("Every %(count)s %(period)s", count=recurrence.interval, period=period)
  112. if recurrence.end_type == 'count':
  113. end = _("for %s events", recurrence.count)
  114. elif recurrence.end_type == 'end_date':
  115. end = _("until %s", recurrence.until)
  116. else:
  117. end = ''
  118. if recurrence.rrule_type == 'weekly':
  119. weekdays = recurrence._get_week_days()
  120. # Convert Weekday object
  121. weekdays = [str(w) for w in weekdays]
  122. # We need to get the day full name from its three first letters.
  123. week_map = {v: k for k, v in RRULE_WEEKDAYS.items()}
  124. weekday_short = [week_map[w] for w in weekdays]
  125. day_strings = [d[1] for d in WEEKDAY_SELECTION if d[0] in weekday_short]
  126. on = _("on %s") % ", ".join([day_name for day_name in day_strings])
  127. elif recurrence.rrule_type == 'monthly':
  128. if recurrence.month_by == 'day':
  129. position_label = dict(BYDAY_SELECTION)[recurrence.byday]
  130. weekday_label = dict(WEEKDAY_SELECTION)[recurrence.weekday]
  131. on = _("on the %(position)s %(weekday)s", position=position_label, weekday=weekday_label)
  132. else:
  133. on = _("day %s", recurrence.day)
  134. else:
  135. on = ''
  136. recurrence.name = ' '.join(filter(lambda s: s, [every, on, end]))
  137. @api.depends('calendar_event_ids.start')
  138. def _compute_dtstart(self):
  139. groups = self.env['calendar.event'].read_group([('recurrence_id', 'in', self.ids)], ['start:min'], ['recurrence_id'])
  140. start_mapping = {
  141. group['recurrence_id'][0]: group['start']
  142. for group in groups
  143. }
  144. for recurrence in self:
  145. recurrence.dtstart = start_mapping.get(recurrence.id)
  146. @api.depends(
  147. 'byday', 'until', 'rrule_type', 'month_by', 'interval', 'count', 'end_type',
  148. 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'day', 'weekday')
  149. def _compute_rrule(self):
  150. for recurrence in self:
  151. current_rule = recurrence._rrule_serialize()
  152. if recurrence.rrule != current_rule:
  153. recurrence.write({'rrule': current_rule})
  154. def _inverse_rrule(self):
  155. for recurrence in self:
  156. if recurrence.rrule:
  157. values = self._rrule_parse(recurrence.rrule, recurrence.dtstart)
  158. recurrence.with_context(dont_notify=True).write(values)
  159. def _reconcile_events(self, ranges):
  160. """
  161. :param ranges: iterable of tuples (datetime_start, datetime_stop)
  162. :return: tuple (events of the recurrence already in sync with ranges,
  163. and ranges not covered by any events)
  164. """
  165. ranges = set(ranges)
  166. synced_events = self.calendar_event_ids.filtered(lambda e: e._range() in ranges)
  167. existing_ranges = set(event._range() for event in synced_events)
  168. ranges_to_create = (event_range for event_range in ranges if event_range not in existing_ranges)
  169. return synced_events, ranges_to_create
  170. def _select_new_base_event(self):
  171. """
  172. when the base event is no more available (archived, deleted, etc.), a new one should be selected
  173. """
  174. for recurrence in self:
  175. recurrence.base_event_id = recurrence._get_first_event()
  176. def _apply_recurrence(self, specific_values_creation=None, no_send_edit=False, generic_values_creation=None):
  177. """Create missing events in the recurrence and detach events which no longer
  178. follow the recurrence rules.
  179. :return: detached events
  180. """
  181. event_vals = []
  182. keep = self.env['calendar.event']
  183. if specific_values_creation is None:
  184. specific_values_creation = {}
  185. for recurrence in self.filtered('base_event_id'):
  186. recurrence.calendar_event_ids |= recurrence.base_event_id
  187. event = recurrence.base_event_id or recurrence._get_first_event(include_outliers=False)
  188. duration = event.stop - event.start
  189. if specific_values_creation:
  190. ranges = set([(x[1], x[2]) for x in specific_values_creation if x[0] == recurrence.id])
  191. else:
  192. ranges = recurrence._range_calculation(event, duration)
  193. events_to_keep, ranges = recurrence._reconcile_events(ranges)
  194. keep |= events_to_keep
  195. [base_values] = event.copy_data()
  196. values = []
  197. for start, stop in ranges:
  198. value = dict(base_values, start=start, stop=stop, recurrence_id=recurrence.id, follow_recurrence=True)
  199. if (recurrence.id, start, stop) in specific_values_creation:
  200. value.update(specific_values_creation[(recurrence.id, start, stop)])
  201. if generic_values_creation and recurrence.id in generic_values_creation:
  202. value.update(generic_values_creation[recurrence.id])
  203. values += [value]
  204. event_vals += values
  205. events = self.calendar_event_ids - keep
  206. detached_events = self._detach_events(events)
  207. self.env['calendar.event'].with_context(no_mail_to_attendees=True, mail_create_nolog=True).create(event_vals)
  208. return detached_events
  209. def _split_from(self, event, recurrence_values=None):
  210. """Stops the current recurrence at the given event and creates a new one starting
  211. with the event.
  212. :param event: starting point of the new recurrence
  213. :param recurrence_values: values applied to the new recurrence
  214. :return: new recurrence
  215. """
  216. if recurrence_values is None:
  217. recurrence_values = {}
  218. event.ensure_one()
  219. if not self:
  220. return
  221. [values] = self.copy_data()
  222. detached_events = self._stop_at(event)
  223. count = recurrence_values.get('count', 0) or len(detached_events)
  224. return self.create({
  225. **values,
  226. **recurrence_values,
  227. 'base_event_id': event.id,
  228. 'calendar_event_ids': [(6, 0, detached_events.ids)],
  229. 'count': max(count, 1),
  230. })
  231. def _stop_at(self, event):
  232. """Stops the recurrence at the given event. Detach the event and all following
  233. events from the recurrence.
  234. :return: detached events from the recurrence
  235. """
  236. self.ensure_one()
  237. events = self._get_events_from(event.start)
  238. detached_events = self._detach_events(events)
  239. if not self.calendar_event_ids:
  240. self.with_context(archive_on_error=True).unlink()
  241. return detached_events
  242. if event.allday:
  243. until = self._get_start_of_period(event.start_date)
  244. else:
  245. until_datetime = self._get_start_of_period(event.start)
  246. until_timezoned = pytz.utc.localize(until_datetime).astimezone(self._get_timezone())
  247. until = until_timezoned.date()
  248. self.write({
  249. 'end_type': 'end_date',
  250. 'until': until - relativedelta(days=1),
  251. })
  252. return detached_events
  253. @api.model
  254. def _detach_events(self, events):
  255. events.with_context(dont_notify=True).write({
  256. 'recurrence_id': False,
  257. 'recurrency': False,
  258. })
  259. return events
  260. def _write_events(self, values, dtstart=None):
  261. """
  262. Write values on events in the recurrence.
  263. :param values: event values
  264. :param dstart: if provided, only write events starting from this point in time
  265. """
  266. events = self._get_events_from(dtstart) if dtstart else self.calendar_event_ids
  267. return events.with_context(no_mail_to_attendees=True, dont_notify=True).write(dict(values, recurrence_update='self_only'))
  268. def _rrule_serialize(self):
  269. """
  270. Compute rule string according to value type RECUR of iCalendar
  271. :return: string containing recurring rule (empty if no rule)
  272. """
  273. if self.interval <= 0:
  274. raise UserError(_('The interval cannot be negative.'))
  275. if self.end_type == 'count' and self.count <= 0:
  276. raise UserError(_('The number of repetitions cannot be negative.'))
  277. return str(self._get_rrule()) if self.rrule_type else ''
  278. @api.model
  279. def _rrule_parse(self, rule_str, date_start):
  280. # LUL TODO clean this mess
  281. data = {}
  282. day_list = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
  283. if 'Z' in rule_str and date_start and not date_start.tzinfo:
  284. date_start = pytz.utc.localize(date_start)
  285. rule = rrule.rrulestr(rule_str, dtstart=date_start)
  286. data['rrule_type'] = freq_to_select(rule._freq)
  287. data['count'] = rule._count
  288. data['interval'] = rule._interval
  289. data['until'] = rule._until
  290. # Repeat weekly
  291. if rule._byweekday:
  292. for weekday in day_list:
  293. data[weekday] = False # reset
  294. for weekday_index in rule._byweekday:
  295. weekday = rrule.weekday(weekday_index)
  296. data[weekday_to_field(weekday.weekday)] = True
  297. data['rrule_type'] = 'weekly'
  298. # Repeat monthly by nweekday ((weekday, weeknumber), )
  299. if rule._bynweekday:
  300. data['weekday'] = day_list[list(rule._bynweekday)[0][0]].upper()
  301. data['byday'] = str(list(rule._bynweekday)[0][1])
  302. data['month_by'] = 'day'
  303. data['rrule_type'] = 'monthly'
  304. if rule._bymonthday:
  305. data['day'] = list(rule._bymonthday)[0]
  306. data['month_by'] = 'date'
  307. data['rrule_type'] = 'monthly'
  308. # Repeat yearly but for odoo it's monthly, take same information as monthly but interval is 12 times
  309. if rule._bymonth:
  310. data['interval'] *= 12
  311. if data.get('until'):
  312. data['end_type'] = 'end_date'
  313. elif data.get('count'):
  314. data['end_type'] = 'count'
  315. else:
  316. data['end_type'] = 'forever'
  317. return data
  318. def _get_lang_week_start(self):
  319. lang = self.env['res.lang']._lang_get(self.env.user.lang)
  320. week_start = int(lang.week_start) # lang.week_start ranges from '1' to '7'
  321. return rrule.weekday(week_start - 1) # rrule expects an int from 0 to 6
  322. def _get_start_of_period(self, dt):
  323. if self.rrule_type == 'weekly':
  324. week_start = self._get_lang_week_start()
  325. start = dt + relativedelta(weekday=week_start(-1))
  326. elif self.rrule_type == 'monthly':
  327. start = dt + relativedelta(day=1)
  328. else:
  329. start = dt
  330. # Comparaison of DST (to manage the case of going too far back in time).
  331. # If we detect a change in the DST between the creation date of an event
  332. # and the date used for the occurrence period, we use the creation date of the event.
  333. # This is a hack to avoid duplication of events (for example on google calendar).
  334. if isinstance(dt, datetime):
  335. timezone = self._get_timezone()
  336. dst_dt = timezone.localize(dt).dst()
  337. dst_start = timezone.localize(start).dst()
  338. if dst_dt != dst_start:
  339. start = dt
  340. return start
  341. def _get_first_event(self, include_outliers=False):
  342. if not self.calendar_event_ids:
  343. return self.env['calendar.event']
  344. events = self.calendar_event_ids.sorted('start')
  345. if not include_outliers:
  346. events -= self._get_outliers()
  347. return events[:1]
  348. def _get_outliers(self):
  349. synced_events = self.env['calendar.event']
  350. for recurrence in self:
  351. if recurrence.calendar_event_ids:
  352. start = min(recurrence.calendar_event_ids.mapped('start'))
  353. starts = set(recurrence._get_occurrences(start))
  354. synced_events |= recurrence.calendar_event_ids.filtered(lambda e: e.start in starts)
  355. return self.calendar_event_ids - synced_events
  356. def _range_calculation(self, event, duration):
  357. """ Calculate the range of recurrence when applying the recurrence
  358. The following issues are taken into account:
  359. start of period is sometimes in the past (weekly or monthly rule).
  360. We can easily filter these range values but then the count value may be wrong...
  361. In that case, we just increase the count value, recompute the ranges and dismiss the useless values
  362. """
  363. self.ensure_one()
  364. original_count = self.end_type == 'count' and self.count
  365. ranges = set(self._get_ranges(event.start, duration))
  366. future_events = set((x, y) for x, y in ranges if x.date() >= event.start.date() and y.date() >= event.start.date())
  367. if original_count and len(future_events) < original_count:
  368. # Rise count number because some past values will be dismissed.
  369. self.count = (2*original_count) - len(future_events)
  370. ranges = set(self._get_ranges(event.start, duration))
  371. # We set back the occurrence number to its original value
  372. self.count = original_count
  373. # Remove ranges of events occurring in the past
  374. ranges = set((x, y) for x, y in ranges if x.date() >= event.start.date() and y.date() >= event.start.date())
  375. return ranges
  376. def _get_ranges(self, start, event_duration):
  377. starts = self._get_occurrences(start)
  378. return ((start, start + event_duration) for start in starts)
  379. def _get_timezone(self):
  380. return pytz.timezone(self.event_tz or self.env.context.get('tz') or 'UTC')
  381. def _get_occurrences(self, dtstart):
  382. """
  383. Get ocurrences of the rrule
  384. :param dtstart: start of the recurrence
  385. :return: iterable of datetimes
  386. """
  387. self.ensure_one()
  388. dtstart = self._get_start_of_period(dtstart)
  389. if self._is_allday():
  390. return self._get_rrule(dtstart=dtstart)
  391. timezone = self._get_timezone()
  392. # Localize the starting datetime to avoid missing the first occurrence
  393. dtstart = pytz.utc.localize(dtstart).astimezone(timezone)
  394. # dtstart is given as a naive datetime, but it actually represents a timezoned datetime
  395. # (rrule package expects a naive datetime)
  396. occurences = self._get_rrule(dtstart=dtstart.replace(tzinfo=None))
  397. # Special timezoning is needed to handle DST (Daylight Saving Time) changes.
  398. # Given the following recurrence:
  399. # - monthly
  400. # - 1st of each month
  401. # - timezone US/Eastern (UTC−05:00)
  402. # - at 6am US/Eastern = 11am UTC
  403. # - from 2019/02/01 to 2019/05/01.
  404. # The naive way would be to store:
  405. # 2019/02/01 11:00 - 2019/03/01 11:00 - 2019/04/01 11:00 - 2019/05/01 11:00 (UTC)
  406. #
  407. # But a DST change occurs on 2019/03/10 in US/Eastern timezone. US/Eastern is now UTC−04:00.
  408. # From this point in time, 11am (UTC) is actually converted to 7am (US/Eastern) instead of the expected 6am!
  409. # What should be stored is:
  410. # 2019/02/01 11:00 - 2019/03/01 11:00 - 2019/04/01 10:00 - 2019/05/01 10:00 (UTC)
  411. # ***** *****
  412. return (timezone.localize(occurrence, is_dst=False).astimezone(pytz.utc).replace(tzinfo=None) for occurrence in occurences)
  413. def _get_events_from(self, dtstart):
  414. return self.env['calendar.event'].search([
  415. ('id', 'in', self.calendar_event_ids.ids),
  416. ('start', '>=', dtstart)
  417. ])
  418. def _get_week_days(self):
  419. """
  420. :return: tuple of rrule weekdays for this recurrence.
  421. """
  422. return tuple(
  423. rrule.weekday(weekday_index)
  424. for weekday_index, weekday in {
  425. rrule.MO.weekday: self.mon,
  426. rrule.TU.weekday: self.tue,
  427. rrule.WE.weekday: self.wed,
  428. rrule.TH.weekday: self.thu,
  429. rrule.FR.weekday: self.fri,
  430. rrule.SA.weekday: self.sat,
  431. rrule.SU.weekday: self.sun,
  432. }.items() if weekday
  433. )
  434. def _is_allday(self):
  435. """Returns whether a majority of events are allday or not (there might be some outlier events)
  436. """
  437. score = sum(1 if e.allday else -1 for e in self.calendar_event_ids)
  438. return score >= 0
  439. def _get_rrule(self, dtstart=None):
  440. self.ensure_one()
  441. freq = self.rrule_type
  442. rrule_params = dict(
  443. dtstart=dtstart,
  444. interval=self.interval,
  445. )
  446. if freq == 'monthly' and self.month_by == 'date': # e.g. every 15th of the month
  447. rrule_params['bymonthday'] = self.day
  448. elif freq == 'monthly' and self.month_by == 'day': # e.g. every 2nd Monday in the month
  449. rrule_params['byweekday'] = getattr(rrule, RRULE_WEEKDAYS[self.weekday])(int(self.byday)) # e.g. MO(+2) for the second Monday of the month
  450. elif freq == 'weekly':
  451. weekdays = self._get_week_days()
  452. if not weekdays:
  453. raise UserError(_("You have to choose at least one day in the week"))
  454. rrule_params['byweekday'] = weekdays
  455. rrule_params['wkst'] = self._get_lang_week_start()
  456. if self.end_type == 'count': # e.g. stop after X occurence
  457. rrule_params['count'] = min(self.count, MAX_RECURRENT_EVENT)
  458. elif self.end_type == 'forever':
  459. rrule_params['count'] = MAX_RECURRENT_EVENT
  460. elif self.end_type == 'end_date': # e.g. stop after 12/10/2020
  461. rrule_params['until'] = datetime.combine(self.until, time.max)
  462. return rrule.rrule(
  463. freq_to_rrule(freq), **rrule_params
  464. )