resource.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from collections import defaultdict
  4. import itertools
  5. import math
  6. from datetime import datetime, time, timedelta
  7. from dateutil.relativedelta import relativedelta
  8. from dateutil.rrule import rrule, DAILY, WEEKLY
  9. from functools import partial
  10. from itertools import chain
  11. from pytz import timezone, utc
  12. from odoo import api, fields, models, _
  13. from odoo.addons.base.models.res_partner import _tz_get
  14. from odoo.exceptions import ValidationError
  15. from odoo.osv import expression
  16. from odoo.tools.float_utils import float_round
  17. from odoo.tools import date_utils, float_utils
  18. from .resource_mixin import timezone_datetime
  19. # Default hour per day value. The one should
  20. # only be used when the one from the calendar
  21. # is not available.
  22. HOURS_PER_DAY = 8
  23. # This will generate 16th of days
  24. ROUNDING_FACTOR = 16
  25. def make_aware(dt):
  26. """ Return ``dt`` with an explicit timezone, together with a function to
  27. convert a datetime to the same (naive or aware) timezone as ``dt``.
  28. """
  29. if dt.tzinfo:
  30. return dt, lambda val: val.astimezone(dt.tzinfo)
  31. else:
  32. return dt.replace(tzinfo=utc), lambda val: val.astimezone(utc).replace(tzinfo=None)
  33. def string_to_datetime(value):
  34. """ Convert the given string value to a datetime in UTC. """
  35. return utc.localize(fields.Datetime.from_string(value))
  36. def datetime_to_string(dt):
  37. """ Convert the given datetime (converted in UTC) to a string value. """
  38. return fields.Datetime.to_string(dt.astimezone(utc))
  39. def float_to_time(hours):
  40. """ Convert a number of hours into a time object. """
  41. if hours == 24.0:
  42. return time.max
  43. fractional, integral = math.modf(hours)
  44. return time(int(integral), int(float_round(60 * fractional, precision_digits=0)), 0)
  45. def _boundaries(intervals, opening, closing):
  46. """ Iterate on the boundaries of intervals. """
  47. for start, stop, recs in intervals:
  48. if start < stop:
  49. yield (start, opening, recs)
  50. yield (stop, closing, recs)
  51. class Intervals(object):
  52. """ Collection of ordered disjoint intervals with some associated records.
  53. Each interval is a triple ``(start, stop, records)``, where ``records``
  54. is a recordset.
  55. """
  56. def __init__(self, intervals=()):
  57. self._items = []
  58. if intervals:
  59. # normalize the representation of intervals
  60. append = self._items.append
  61. starts = []
  62. recses = []
  63. for value, flag, recs in sorted(_boundaries(intervals, 'start', 'stop')):
  64. if flag == 'start':
  65. starts.append(value)
  66. recses.append(recs)
  67. else:
  68. start = starts.pop()
  69. if not starts:
  70. append((start, value, recses[0].union(*recses)))
  71. recses.clear()
  72. def __bool__(self):
  73. return bool(self._items)
  74. def __len__(self):
  75. return len(self._items)
  76. def __iter__(self):
  77. return iter(self._items)
  78. def __reversed__(self):
  79. return reversed(self._items)
  80. def __or__(self, other):
  81. """ Return the union of two sets of intervals. """
  82. return Intervals(chain(self._items, other._items))
  83. def __and__(self, other):
  84. """ Return the intersection of two sets of intervals. """
  85. return self._merge(other, False)
  86. def __sub__(self, other):
  87. """ Return the difference of two sets of intervals. """
  88. return self._merge(other, True)
  89. def _merge(self, other, difference):
  90. """ Return the difference or intersection of two sets of intervals. """
  91. result = Intervals()
  92. append = result._items.append
  93. # using 'self' and 'other' below forces normalization
  94. bounds1 = _boundaries(self, 'start', 'stop')
  95. bounds2 = _boundaries(other, 'switch', 'switch')
  96. start = None # set by start/stop
  97. recs1 = None # set by start
  98. enabled = difference # changed by switch
  99. for value, flag, recs in sorted(chain(bounds1, bounds2)):
  100. if flag == 'start':
  101. start = value
  102. recs1 = recs
  103. elif flag == 'stop':
  104. if enabled and start < value:
  105. append((start, value, recs1))
  106. start = None
  107. else:
  108. if not enabled and start is not None:
  109. start = value
  110. if enabled and start is not None and start < value:
  111. append((start, value, recs1))
  112. enabled = not enabled
  113. return result
  114. def sum_intervals(intervals):
  115. """ Sum the intervals duration (unit : hour)"""
  116. return sum(
  117. (stop - start).total_seconds() / 3600
  118. for start, stop, meta in intervals
  119. )
  120. class ResourceCalendar(models.Model):
  121. """ Calendar model for a resource. It has
  122. - attendance_ids: list of resource.calendar.attendance that are a working
  123. interval in a given weekday.
  124. - leave_ids: list of leaves linked to this calendar. A leave can be general
  125. or linked to a specific resource, depending on its resource_id.
  126. All methods in this class use intervals. An interval is a tuple holding
  127. (begin_datetime, end_datetime). A list of intervals is therefore a list of
  128. tuples, holding several intervals of work or leaves. """
  129. _name = "resource.calendar"
  130. _description = "Resource Working Time"
  131. @api.model
  132. def default_get(self, fields):
  133. res = super(ResourceCalendar, self).default_get(fields)
  134. if not res.get('name') and res.get('company_id'):
  135. res['name'] = _('Working Hours of %s', self.env['res.company'].browse(res['company_id']).name)
  136. if 'attendance_ids' in fields and not res.get('attendance_ids'):
  137. company_id = res.get('company_id', self.env.company.id)
  138. company = self.env['res.company'].browse(company_id)
  139. company_attendance_ids = company.resource_calendar_id.attendance_ids
  140. if not company.resource_calendar_id.two_weeks_calendar and company_attendance_ids:
  141. res['attendance_ids'] = [
  142. (0, 0, {
  143. 'name': attendance.name,
  144. 'dayofweek': attendance.dayofweek,
  145. 'hour_from': attendance.hour_from,
  146. 'hour_to': attendance.hour_to,
  147. 'day_period': attendance.day_period,
  148. })
  149. for attendance in company_attendance_ids
  150. ]
  151. else:
  152. res['attendance_ids'] = [
  153. (0, 0, {'name': _('Monday Morning'), 'dayofweek': '0', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
  154. (0, 0, {'name': _('Monday Afternoon'), 'dayofweek': '0', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
  155. (0, 0, {'name': _('Tuesday Morning'), 'dayofweek': '1', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
  156. (0, 0, {'name': _('Tuesday Afternoon'), 'dayofweek': '1', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
  157. (0, 0, {'name': _('Wednesday Morning'), 'dayofweek': '2', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
  158. (0, 0, {'name': _('Wednesday Afternoon'), 'dayofweek': '2', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
  159. (0, 0, {'name': _('Thursday Morning'), 'dayofweek': '3', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
  160. (0, 0, {'name': _('Thursday Afternoon'), 'dayofweek': '3', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
  161. (0, 0, {'name': _('Friday Morning'), 'dayofweek': '4', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
  162. (0, 0, {'name': _('Friday Afternoon'), 'dayofweek': '4', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'})
  163. ]
  164. return res
  165. name = fields.Char(required=True)
  166. active = fields.Boolean("Active", default=True,
  167. help="If the active field is set to false, it will allow you to hide the Working Time without removing it.")
  168. company_id = fields.Many2one(
  169. 'res.company', 'Company',
  170. default=lambda self: self.env.company)
  171. attendance_ids = fields.One2many(
  172. 'resource.calendar.attendance', 'calendar_id', 'Working Time',
  173. compute='_compute_attendance_ids', store=True, readonly=False, copy=True)
  174. leave_ids = fields.One2many(
  175. 'resource.calendar.leaves', 'calendar_id', 'Time Off')
  176. global_leave_ids = fields.One2many(
  177. 'resource.calendar.leaves', 'calendar_id', 'Global Time Off',
  178. compute='_compute_global_leave_ids', store=True, readonly=False,
  179. domain=[('resource_id', '=', False)], copy=True,
  180. )
  181. hours_per_day = fields.Float("Average Hour per Day", default=HOURS_PER_DAY,
  182. help="Average hours per day a resource is supposed to work with this calendar.")
  183. tz = fields.Selection(
  184. _tz_get, string='Timezone', required=True,
  185. default=lambda self: self._context.get('tz') or self.env.user.tz or self.env.ref('base.user_admin').tz or 'UTC',
  186. help="This field is used in order to define in which timezone the resources will work.")
  187. tz_offset = fields.Char(compute='_compute_tz_offset', string='Timezone offset', invisible=True)
  188. two_weeks_calendar = fields.Boolean(string="Calendar in 2 weeks mode")
  189. two_weeks_explanation = fields.Char('Explanation', compute="_compute_two_weeks_explanation")
  190. @api.depends('company_id')
  191. def _compute_attendance_ids(self):
  192. for calendar in self.filtered(lambda c: not c._origin or c._origin.company_id != c.company_id):
  193. company_calendar = calendar.company_id.resource_calendar_id
  194. calendar.update({
  195. 'two_weeks_calendar': company_calendar.two_weeks_calendar,
  196. 'hours_per_day': company_calendar.hours_per_day,
  197. 'tz': company_calendar.tz,
  198. 'attendance_ids': [(5, 0, 0)] + [
  199. (0, 0, attendance._copy_attendance_vals()) for attendance in company_calendar.attendance_ids if not attendance.resource_id]
  200. })
  201. @api.depends('company_id')
  202. def _compute_global_leave_ids(self):
  203. for calendar in self.filtered(lambda c: not c._origin or c._origin.company_id != c.company_id):
  204. calendar.update({
  205. 'global_leave_ids': [(5, 0, 0)] + [
  206. (0, 0, leave._copy_leave_vals()) for leave in calendar.company_id.resource_calendar_id.global_leave_ids]
  207. })
  208. @api.depends('tz')
  209. def _compute_tz_offset(self):
  210. for calendar in self:
  211. calendar.tz_offset = datetime.now(timezone(calendar.tz or 'GMT')).strftime('%z')
  212. @api.returns('self', lambda value: value.id)
  213. def copy(self, default=None):
  214. self.ensure_one()
  215. if default is None:
  216. default = {}
  217. if not default.get('name'):
  218. default.update(name=_('%s (copy)') % (self.name))
  219. return super(ResourceCalendar, self).copy(default)
  220. @api.constrains('attendance_ids')
  221. def _check_attendance_ids(self):
  222. for resource in self:
  223. if (resource.two_weeks_calendar and
  224. resource.attendance_ids.filtered(lambda a: a.display_type == 'line_section') and
  225. not resource.attendance_ids.sorted('sequence')[0].display_type):
  226. raise ValidationError(_("In a calendar with 2 weeks mode, all periods need to be in the sections."))
  227. @api.depends('two_weeks_calendar')
  228. def _compute_two_weeks_explanation(self):
  229. today = fields.Date.today()
  230. week_type = self.env['resource.calendar.attendance'].get_week_type(today)
  231. week_type_str = _("second") if week_type else _("first")
  232. first_day = date_utils.start_of(today, 'week')
  233. last_day = date_utils.end_of(today, 'week')
  234. self.two_weeks_explanation = _("The current week (from %s to %s) correspond to the %s one.", first_day,
  235. last_day, week_type_str)
  236. def _get_global_attendances(self):
  237. return self.attendance_ids.filtered(lambda attendance:
  238. not attendance.date_from and not attendance.date_to
  239. and not attendance.resource_id and not attendance.display_type)
  240. def _compute_hours_per_day(self, attendances):
  241. if not attendances:
  242. return 0
  243. hour_count = 0.0
  244. for attendance in attendances:
  245. hour_count += attendance.hour_to - attendance.hour_from
  246. if self.two_weeks_calendar:
  247. number_of_days = len(set(attendances.filtered(lambda cal: cal.week_type == '1').mapped('dayofweek')))
  248. number_of_days += len(set(attendances.filtered(lambda cal: cal.week_type == '0').mapped('dayofweek')))
  249. else:
  250. number_of_days = len(set(attendances.mapped('dayofweek')))
  251. return float_round(hour_count / float(number_of_days), precision_digits=2)
  252. @api.onchange('attendance_ids', 'two_weeks_calendar')
  253. def _onchange_hours_per_day(self):
  254. attendances = self._get_global_attendances()
  255. self.hours_per_day = self._compute_hours_per_day(attendances)
  256. def switch_calendar_type(self):
  257. if not self.two_weeks_calendar:
  258. self.attendance_ids.unlink()
  259. self.attendance_ids = [
  260. (0, 0, {
  261. 'name': 'First week',
  262. 'dayofweek': '0',
  263. 'sequence': '0',
  264. 'hour_from': 0,
  265. 'day_period': 'morning',
  266. 'week_type': '0',
  267. 'hour_to': 0,
  268. 'display_type':
  269. 'line_section'}),
  270. (0, 0, {
  271. 'name': 'Second week',
  272. 'dayofweek': '0',
  273. 'sequence': '25',
  274. 'hour_from': 0,
  275. 'day_period': 'morning',
  276. 'week_type': '1',
  277. 'hour_to': 0,
  278. 'display_type': 'line_section'}),
  279. ]
  280. self.two_weeks_calendar = True
  281. default_attendance = self.default_get('attendance_ids')['attendance_ids']
  282. for idx, att in enumerate(default_attendance):
  283. att[2]["week_type"] = '0'
  284. att[2]["sequence"] = idx + 1
  285. self.attendance_ids = default_attendance
  286. for idx, att in enumerate(default_attendance):
  287. att[2]["week_type"] = '1'
  288. att[2]["sequence"] = idx + 26
  289. self.attendance_ids = default_attendance
  290. else:
  291. self.two_weeks_calendar = False
  292. self.attendance_ids.unlink()
  293. self.attendance_ids = self.default_get('attendance_ids')['attendance_ids']
  294. self._onchange_hours_per_day()
  295. @api.onchange('attendance_ids')
  296. def _onchange_attendance_ids(self):
  297. if not self.two_weeks_calendar:
  298. return
  299. even_week_seq = self.attendance_ids.filtered(lambda att: att.display_type == 'line_section' and att.week_type == '0')
  300. odd_week_seq = self.attendance_ids.filtered(lambda att: att.display_type == 'line_section' and att.week_type == '1')
  301. if len(even_week_seq) != 1 or len(odd_week_seq) != 1:
  302. raise ValidationError(_("You can't delete section between weeks."))
  303. even_week_seq = even_week_seq.sequence
  304. odd_week_seq = odd_week_seq.sequence
  305. for line in self.attendance_ids.filtered(lambda att: att.display_type is False):
  306. if even_week_seq > odd_week_seq:
  307. line.week_type = '1' if even_week_seq > line.sequence else '0'
  308. else:
  309. line.week_type = '0' if odd_week_seq > line.sequence else '1'
  310. def _check_overlap(self, attendance_ids):
  311. """ attendance_ids correspond to attendance of a week,
  312. will check for each day of week that there are no superimpose. """
  313. result = []
  314. for attendance in attendance_ids.filtered(lambda att: not att.date_from and not att.date_to):
  315. # 0.000001 is added to each start hour to avoid to detect two contiguous intervals as superimposing.
  316. # Indeed Intervals function will join 2 intervals with the start and stop hour corresponding.
  317. result.append((int(attendance.dayofweek) * 24 + attendance.hour_from + 0.000001, int(attendance.dayofweek) * 24 + attendance.hour_to, attendance))
  318. if len(Intervals(result)) != len(result):
  319. raise ValidationError(_("Attendances can't overlap."))
  320. @api.constrains('attendance_ids')
  321. def _check_attendance(self):
  322. # Avoid superimpose in attendance
  323. for calendar in self:
  324. attendance_ids = calendar.attendance_ids.filtered(lambda attendance: not attendance.resource_id and attendance.display_type is False)
  325. if calendar.two_weeks_calendar:
  326. calendar._check_overlap(attendance_ids.filtered(lambda attendance: attendance.week_type == '0'))
  327. calendar._check_overlap(attendance_ids.filtered(lambda attendance: attendance.week_type == '1'))
  328. else:
  329. calendar._check_overlap(attendance_ids)
  330. # --------------------------------------------------
  331. # Computation API
  332. # --------------------------------------------------
  333. def _attendance_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
  334. assert start_dt.tzinfo and end_dt.tzinfo
  335. self.ensure_one()
  336. if not resources:
  337. resources = self.env['resource.resource']
  338. resources_list = [resources]
  339. else:
  340. resources_list = list(resources) + [self.env['resource.resource']]
  341. resource_ids = [r.id for r in resources_list]
  342. domain = domain if domain is not None else []
  343. domain = expression.AND([domain, [
  344. ('calendar_id', '=', self.id),
  345. ('resource_id', 'in', resource_ids),
  346. ('display_type', '=', False),
  347. ]])
  348. attendances = self.env['resource.calendar.attendance'].search(domain)
  349. # Since we only have one calendar to take in account
  350. # Group resources per tz they will all have the same result
  351. resources_per_tz = defaultdict(list)
  352. for resource in resources_list:
  353. resources_per_tz[tz or timezone((resource or self).tz)].append(resource)
  354. # Resource specific attendances
  355. attendance_per_resource = defaultdict(lambda: self.env['resource.calendar.attendance'])
  356. # Calendar attendances per day of the week
  357. # * 7 days per week * 2 for two week calendars
  358. attendances_per_day = [self.env['resource.calendar.attendance']] * 7 * 2
  359. weekdays = set()
  360. for attendance in attendances:
  361. if attendance.resource_id:
  362. attendance_per_resource[attendance.resource_id] |= attendance
  363. weekday = int(attendance.dayofweek)
  364. weekdays.add(weekday)
  365. if self.two_weeks_calendar:
  366. weektype = int(attendance.week_type)
  367. attendances_per_day[weekday + 7 * weektype] |= attendance
  368. else:
  369. attendances_per_day[weekday] |= attendance
  370. attendances_per_day[weekday + 7] |= attendance
  371. start = start_dt.astimezone(utc)
  372. end = end_dt.astimezone(utc)
  373. bounds_per_tz = {
  374. tz: (start_dt.astimezone(tz), end_dt.astimezone(tz))
  375. for tz in resources_per_tz.keys()
  376. }
  377. # Use the outer bounds from the requested timezones
  378. for tz, bounds in bounds_per_tz.items():
  379. start = min(start, bounds[0].replace(tzinfo=utc))
  380. end = max(end, bounds[1].replace(tzinfo=utc))
  381. # Generate once with utc as timezone
  382. days = rrule(DAILY, start.date(), until=end.date(), byweekday=weekdays)
  383. ResourceCalendarAttendance = self.env['resource.calendar.attendance']
  384. base_result = []
  385. per_resource_result = defaultdict(list)
  386. for day in days:
  387. week_type = ResourceCalendarAttendance.get_week_type(day)
  388. attendances = attendances_per_day[day.weekday() + 7 * week_type]
  389. for attendance in attendances:
  390. if (attendance.date_from and day.date() < attendance.date_from) or\
  391. (attendance.date_to and attendance.date_to < day.date()):
  392. continue
  393. day_from = datetime.combine(day, float_to_time(attendance.hour_from))
  394. day_to = datetime.combine(day, float_to_time(attendance.hour_to))
  395. if attendance.resource_id:
  396. per_resource_result[attendance.resource_id].append((day_from, day_to, attendance))
  397. else:
  398. base_result.append((day_from, day_to, attendance))
  399. # Copy the result localized once per necessary timezone
  400. # Strictly speaking comparing start_dt < time or start_dt.astimezone(tz) < time
  401. # should always yield the same result. however while working with dates it is easier
  402. # if all dates have the same format
  403. result_per_tz = {
  404. tz: [(max(bounds_per_tz[tz][0], tz.localize(val[0])),
  405. min(bounds_per_tz[tz][1], tz.localize(val[1])),
  406. val[2])
  407. for val in base_result]
  408. for tz in resources_per_tz.keys()
  409. }
  410. result_per_resource_id = dict()
  411. for tz, resources in resources_per_tz.items():
  412. res = result_per_tz[tz]
  413. res_intervals = Intervals(res)
  414. for resource in resources:
  415. if resource in per_resource_result:
  416. resource_specific_result = [(max(bounds_per_tz[tz][0], tz.localize(val[0])), min(bounds_per_tz[tz][1], tz.localize(val[1])), val[2])
  417. for val in per_resource_result[resource]]
  418. result_per_resource_id[resource.id] = Intervals(itertools.chain(res, resource_specific_result))
  419. else:
  420. result_per_resource_id[resource.id] = res_intervals
  421. return result_per_resource_id
  422. def _leave_intervals(self, start_dt, end_dt, resource=None, domain=None, tz=None):
  423. if resource is None:
  424. resource = self.env['resource.resource']
  425. return self._leave_intervals_batch(
  426. start_dt, end_dt, resources=resource, domain=domain, tz=tz
  427. )[resource.id]
  428. def _leave_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None, any_calendar=False):
  429. """ Return the leave intervals in the given datetime range.
  430. The returned intervals are expressed in specified tz or in the calendar's timezone.
  431. """
  432. assert start_dt.tzinfo and end_dt.tzinfo
  433. self.ensure_one()
  434. if not resources:
  435. resources = self.env['resource.resource']
  436. resources_list = [resources]
  437. else:
  438. resources_list = list(resources) + [self.env['resource.resource']]
  439. resource_ids = [r.id for r in resources_list]
  440. if domain is None:
  441. domain = [('time_type', '=', 'leave')]
  442. if not any_calendar:
  443. domain = domain + [('calendar_id', 'in', [False, self.id])]
  444. # for the computation, express all datetimes in UTC
  445. domain = domain + [
  446. ('resource_id', 'in', resource_ids),
  447. ('date_from', '<=', datetime_to_string(end_dt)),
  448. ('date_to', '>=', datetime_to_string(start_dt)),
  449. ]
  450. # retrieve leave intervals in (start_dt, end_dt)
  451. result = defaultdict(lambda: [])
  452. tz_dates = {}
  453. for leave in self.env['resource.calendar.leaves'].search(domain):
  454. for resource in resources_list:
  455. if leave.resource_id.id not in [False, resource.id]:
  456. continue
  457. tz = tz if tz else timezone((resource or self).tz)
  458. if (tz, start_dt) in tz_dates:
  459. start = tz_dates[(tz, start_dt)]
  460. else:
  461. start = start_dt.astimezone(tz)
  462. tz_dates[(tz, start_dt)] = start
  463. if (tz, end_dt) in tz_dates:
  464. end = tz_dates[(tz, end_dt)]
  465. else:
  466. end = end_dt.astimezone(tz)
  467. tz_dates[(tz, end_dt)] = end
  468. dt0 = string_to_datetime(leave.date_from).astimezone(tz)
  469. dt1 = string_to_datetime(leave.date_to).astimezone(tz)
  470. result[resource.id].append((max(start, dt0), min(end, dt1), leave))
  471. return {r.id: Intervals(result[r.id]) for r in resources_list}
  472. def _work_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None, compute_leaves=True):
  473. """ Return the effective work intervals between the given datetimes. """
  474. if not resources:
  475. resources = self.env['resource.resource']
  476. resources_list = [resources]
  477. else:
  478. resources_list = list(resources) + [self.env['resource.resource']]
  479. attendance_intervals = self._attendance_intervals_batch(start_dt, end_dt, resources, tz=tz)
  480. if compute_leaves:
  481. leave_intervals = self._leave_intervals_batch(start_dt, end_dt, resources, domain, tz=tz)
  482. return {
  483. r.id: (attendance_intervals[r.id] - leave_intervals[r.id]) for r in resources_list
  484. }
  485. else:
  486. return {
  487. r.id: attendance_intervals[r.id] for r in resources_list
  488. }
  489. def _unavailable_intervals(self, start_dt, end_dt, resource=None, domain=None, tz=None):
  490. if resource is None:
  491. resource = self.env['resource.resource']
  492. return self._unavailable_intervals_batch(
  493. start_dt, end_dt, resources=resource, domain=domain, tz=tz
  494. )[resource.id]
  495. def _unavailable_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
  496. """ Return the unavailable intervals between the given datetimes. """
  497. if not resources:
  498. resources = self.env['resource.resource']
  499. resources_list = [resources]
  500. else:
  501. resources_list = list(resources)
  502. resources_work_intervals = self._work_intervals_batch(start_dt, end_dt, resources, domain, tz)
  503. result = {}
  504. for resource in resources_list:
  505. work_intervals = [(start, stop) for start, stop, meta in resources_work_intervals[resource.id]]
  506. # start + flatten(intervals) + end
  507. work_intervals = [start_dt] + list(chain.from_iterable(work_intervals)) + [end_dt]
  508. # put it back to UTC
  509. work_intervals = list(map(lambda dt: dt.astimezone(utc), work_intervals))
  510. # pick groups of two
  511. work_intervals = list(zip(work_intervals[0::2], work_intervals[1::2]))
  512. result[resource.id] = work_intervals
  513. return result
  514. # --------------------------------------------------
  515. # Private Methods / Helpers
  516. # --------------------------------------------------
  517. def _get_days_data(self, intervals, day_total):
  518. """
  519. helper function to compute duration of `intervals`
  520. expressed in days and hours.
  521. `day_total` is a dict {date: n_hours} with the number of hours for each day.
  522. """
  523. day_hours = defaultdict(float)
  524. for start, stop, meta in intervals:
  525. day_hours[start.date()] += (stop - start).total_seconds() / 3600
  526. # compute number of days as quarters
  527. days = sum(
  528. float_utils.round(ROUNDING_FACTOR * day_hours[day] / day_total[day]) / ROUNDING_FACTOR if day_total[day] else 0
  529. for day in day_hours
  530. )
  531. return {
  532. 'days': days,
  533. 'hours': sum(day_hours.values()),
  534. }
  535. def _get_resources_day_total(self, from_datetime, to_datetime, resources=None):
  536. """
  537. @return dict with hours of attendance in each day between `from_datetime` and `to_datetime`
  538. """
  539. self.ensure_one()
  540. if not resources:
  541. resources = self.env['resource.resource']
  542. resources_list = [resources]
  543. else:
  544. resources_list = list(resources) + [self.env['resource.resource']]
  545. # total hours per day: retrieve attendances with one extra day margin,
  546. # in order to compute the total hours on the first and last days
  547. from_full = from_datetime - timedelta(days=1)
  548. to_full = to_datetime + timedelta(days=1)
  549. intervals = self._attendance_intervals_batch(from_full, to_full, resources=resources)
  550. result = defaultdict(lambda: defaultdict(float))
  551. for resource in resources_list:
  552. day_total = result[resource.id]
  553. for start, stop, meta in intervals[resource.id]:
  554. day_total[start.date()] += (stop - start).total_seconds() / 3600
  555. return result
  556. def _get_closest_work_time(self, dt, match_end=False, resource=None, search_range=None, compute_leaves=True):
  557. """Return the closest work interval boundary within the search range.
  558. Consider only starts of intervals unless `match_end` is True. It will then only consider
  559. ends of intervals.
  560. :param dt: reference datetime
  561. :param match_end: wether to search for the begining of an interval or the end.
  562. :param search_range: time interval considered. Defaults to the entire day of `dt`
  563. :rtype: datetime | None
  564. """
  565. def interval_dt(interval):
  566. return interval[1 if match_end else 0]
  567. tz = resource.tz if resource else self.tz
  568. if resource is None:
  569. resource = self.env['resource.resource']
  570. if not dt.tzinfo or search_range and not (search_range[0].tzinfo and search_range[1].tzinfo):
  571. raise ValueError('Provided datetimes needs to be timezoned')
  572. dt = dt.astimezone(timezone(tz))
  573. if not search_range:
  574. range_start = dt + relativedelta(hour=0, minute=0, second=0)
  575. range_end = dt + relativedelta(days=1, hour=0, minute=0, second=0)
  576. else:
  577. range_start, range_end = search_range
  578. if not range_start <= dt <= range_end:
  579. return None
  580. work_intervals = sorted(
  581. self._work_intervals_batch(range_start, range_end, resource, compute_leaves=compute_leaves)[resource.id],
  582. key=lambda i: abs(interval_dt(i) - dt),
  583. )
  584. return interval_dt(work_intervals[0]) if work_intervals else None
  585. def _get_unusual_days(self, start_dt, end_dt):
  586. if not self:
  587. return {}
  588. self.ensure_one()
  589. if not start_dt.tzinfo:
  590. start_dt = start_dt.replace(tzinfo=utc)
  591. if not end_dt.tzinfo:
  592. end_dt = end_dt.replace(tzinfo=utc)
  593. works = {d[0].date() for d in self._work_intervals_batch(start_dt, end_dt)[False]}
  594. return {fields.Date.to_string(day.date()): (day.date() not in works) for day in rrule(DAILY, start_dt, until=end_dt)}
  595. # --------------------------------------------------
  596. # External API
  597. # --------------------------------------------------
  598. def get_work_hours_count(self, start_dt, end_dt, compute_leaves=True, domain=None):
  599. """
  600. `compute_leaves` controls whether or not this method is taking into
  601. account the global leaves.
  602. `domain` controls the way leaves are recognized.
  603. None means default value ('time_type', '=', 'leave')
  604. Counts the number of work hours between two datetimes.
  605. """
  606. self.ensure_one()
  607. # Set timezone in UTC if no timezone is explicitly given
  608. if not start_dt.tzinfo:
  609. start_dt = start_dt.replace(tzinfo=utc)
  610. if not end_dt.tzinfo:
  611. end_dt = end_dt.replace(tzinfo=utc)
  612. if compute_leaves:
  613. intervals = self._work_intervals_batch(start_dt, end_dt, domain=domain)[False]
  614. else:
  615. intervals = self._attendance_intervals_batch(start_dt, end_dt)[False]
  616. return sum(
  617. (stop - start).total_seconds() / 3600
  618. for start, stop, meta in intervals
  619. )
  620. def get_work_duration_data(self, from_datetime, to_datetime, compute_leaves=True, domain=None):
  621. """
  622. Get the working duration (in days and hours) for a given period, only
  623. based on the current calendar. This method does not use resource to
  624. compute it.
  625. `domain` is used in order to recognise the leaves to take,
  626. None means default value ('time_type', '=', 'leave')
  627. Returns a dict {'days': n, 'hours': h} containing the
  628. quantity of working time expressed as days and as hours.
  629. """
  630. # naive datetimes are made explicit in UTC
  631. from_datetime, dummy = make_aware(from_datetime)
  632. to_datetime, dummy = make_aware(to_datetime)
  633. day_total = self._get_resources_day_total(from_datetime, to_datetime)[False]
  634. # actual hours per day
  635. if compute_leaves:
  636. intervals = self._work_intervals_batch(from_datetime, to_datetime, domain=domain)[False]
  637. else:
  638. intervals = self._attendance_intervals_batch(from_datetime, to_datetime, domain=domain)[False]
  639. return self._get_days_data(intervals, day_total)
  640. def plan_hours(self, hours, day_dt, compute_leaves=False, domain=None, resource=None):
  641. """
  642. `compute_leaves` controls whether or not this method is taking into
  643. account the global leaves.
  644. `domain` controls the way leaves are recognized.
  645. None means default value ('time_type', '=', 'leave')
  646. Return datetime after having planned hours
  647. """
  648. day_dt, revert = make_aware(day_dt)
  649. if resource is None:
  650. resource = self.env['resource.resource']
  651. # which method to use for retrieving intervals
  652. if compute_leaves:
  653. get_intervals = partial(self._work_intervals_batch, domain=domain, resources=resource)
  654. resource_id = resource.id
  655. else:
  656. get_intervals = self._attendance_intervals_batch
  657. resource_id = False
  658. if hours >= 0:
  659. delta = timedelta(days=14)
  660. for n in range(100):
  661. dt = day_dt + delta * n
  662. for start, stop, meta in get_intervals(dt, dt + delta)[resource_id]:
  663. interval_hours = (stop - start).total_seconds() / 3600
  664. if hours <= interval_hours:
  665. return revert(start + timedelta(hours=hours))
  666. hours -= interval_hours
  667. return False
  668. else:
  669. hours = abs(hours)
  670. delta = timedelta(days=14)
  671. for n in range(100):
  672. dt = day_dt - delta * n
  673. for start, stop, meta in reversed(get_intervals(dt - delta, dt)[resource_id]):
  674. interval_hours = (stop - start).total_seconds() / 3600
  675. if hours <= interval_hours:
  676. return revert(stop - timedelta(hours=hours))
  677. hours -= interval_hours
  678. return False
  679. def plan_days(self, days, day_dt, compute_leaves=False, domain=None):
  680. """
  681. `compute_leaves` controls whether or not this method is taking into
  682. account the global leaves.
  683. `domain` controls the way leaves are recognized.
  684. None means default value ('time_type', '=', 'leave')
  685. Returns the datetime of a days scheduling.
  686. """
  687. day_dt, revert = make_aware(day_dt)
  688. # which method to use for retrieving intervals
  689. if compute_leaves:
  690. get_intervals = partial(self._work_intervals_batch, domain=domain)
  691. else:
  692. get_intervals = self._attendance_intervals_batch
  693. if days > 0:
  694. found = set()
  695. delta = timedelta(days=14)
  696. for n in range(100):
  697. dt = day_dt + delta * n
  698. for start, stop, meta in get_intervals(dt, dt + delta)[False]:
  699. found.add(start.date())
  700. if len(found) == days:
  701. return revert(stop)
  702. return False
  703. elif days < 0:
  704. days = abs(days)
  705. found = set()
  706. delta = timedelta(days=14)
  707. for n in range(100):
  708. dt = day_dt - delta * n
  709. for start, stop, meta in reversed(get_intervals(dt - delta, dt)[False]):
  710. found.add(start.date())
  711. if len(found) == days:
  712. return revert(start)
  713. return False
  714. else:
  715. return revert(day_dt)
  716. def _get_max_number_of_hours(self, start, end):
  717. self.ensure_one()
  718. if not self.attendance_ids:
  719. return 0
  720. mapped_data = defaultdict(lambda: 0)
  721. for attendance in self.attendance_ids.filtered(lambda a: (not a.date_from or not a.date_to) or (a.date_from <= end.date() and a.date_to >= start.date())):
  722. mapped_data[(attendance.week_type, attendance.dayofweek)] += attendance.hour_to - attendance.hour_from
  723. return max(mapped_data.values())
  724. class ResourceCalendarAttendance(models.Model):
  725. _name = "resource.calendar.attendance"
  726. _description = "Work Detail"
  727. _order = 'week_type, dayofweek, hour_from'
  728. name = fields.Char(required=True)
  729. dayofweek = fields.Selection([
  730. ('0', 'Monday'),
  731. ('1', 'Tuesday'),
  732. ('2', 'Wednesday'),
  733. ('3', 'Thursday'),
  734. ('4', 'Friday'),
  735. ('5', 'Saturday'),
  736. ('6', 'Sunday')
  737. ], 'Day of Week', required=True, index=True, default='0')
  738. date_from = fields.Date(string='Starting Date')
  739. date_to = fields.Date(string='End Date')
  740. hour_from = fields.Float(string='Work from', required=True, index=True,
  741. help="Start and End time of working.\n"
  742. "A specific value of 24:00 is interpreted as 23:59:59.999999.")
  743. hour_to = fields.Float(string='Work to', required=True)
  744. calendar_id = fields.Many2one("resource.calendar", string="Resource's Calendar", required=True, ondelete='cascade')
  745. day_period = fields.Selection([('morning', 'Morning'), ('afternoon', 'Afternoon')], required=True, default='morning')
  746. resource_id = fields.Many2one('resource.resource', 'Resource')
  747. week_type = fields.Selection([
  748. ('1', 'Second'),
  749. ('0', 'First')
  750. ], 'Week Number', default=False)
  751. two_weeks_calendar = fields.Boolean("Calendar in 2 weeks mode", related='calendar_id.two_weeks_calendar')
  752. display_type = fields.Selection([
  753. ('line_section', "Section")], default=False, help="Technical field for UX purpose.")
  754. sequence = fields.Integer(default=10,
  755. help="Gives the sequence of this line when displaying the resource calendar.")
  756. @api.onchange('hour_from', 'hour_to')
  757. def _onchange_hours(self):
  758. # avoid negative or after midnight
  759. self.hour_from = min(self.hour_from, 23.99)
  760. self.hour_from = max(self.hour_from, 0.0)
  761. self.hour_to = min(self.hour_to, 24)
  762. self.hour_to = max(self.hour_to, 0.0)
  763. # avoid wrong order
  764. self.hour_to = max(self.hour_to, self.hour_from)
  765. @api.model
  766. def get_week_type(self, date):
  767. # week_type is defined by
  768. # * counting the number of days from January 1 of year 1
  769. # (extrapolated to dates prior to the first adoption of the Gregorian calendar)
  770. # * converted to week numbers and then the parity of this number is asserted.
  771. # It ensures that an even week number always follows an odd week number. With classical week number,
  772. # some years have 53 weeks. Therefore, two consecutive odd week number follow each other (53 --> 1).
  773. return int(math.floor((date.toordinal() - 1) / 7) % 2)
  774. def _compute_display_name(self):
  775. super()._compute_display_name()
  776. this_week_type = str(self.get_week_type(fields.Date.context_today(self)))
  777. section_names = {'0': _('First week'), '1': _('Second week')}
  778. section_info = {True: _('this week'), False: _('other week')}
  779. for record in self.filtered(lambda l: l.display_type == 'line_section'):
  780. section_name = "%s (%s)" % (section_names[record.week_type], section_info[this_week_type == record.week_type])
  781. record.display_name = section_name
  782. def _copy_attendance_vals(self):
  783. self.ensure_one()
  784. return {
  785. 'name': self.name,
  786. 'dayofweek': self.dayofweek,
  787. 'date_from': self.date_from,
  788. 'date_to': self.date_to,
  789. 'hour_from': self.hour_from,
  790. 'hour_to': self.hour_to,
  791. 'day_period': self.day_period,
  792. 'week_type': self.week_type,
  793. 'display_type': self.display_type,
  794. 'sequence': self.sequence,
  795. }
  796. class ResourceResource(models.Model):
  797. _name = "resource.resource"
  798. _description = "Resources"
  799. _order = "name"
  800. @api.model
  801. def default_get(self, fields):
  802. res = super(ResourceResource, self).default_get(fields)
  803. if not res.get('calendar_id') and res.get('company_id'):
  804. company = self.env['res.company'].browse(res['company_id'])
  805. res['calendar_id'] = company.resource_calendar_id.id
  806. return res
  807. name = fields.Char(required=True)
  808. active = fields.Boolean(
  809. 'Active', default=True,
  810. help="If the active field is set to False, it will allow you to hide the resource record without removing it.")
  811. company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company)
  812. resource_type = fields.Selection([
  813. ('user', 'Human'),
  814. ('material', 'Material')], string='Type',
  815. default='user', required=True)
  816. user_id = fields.Many2one('res.users', string='User', help='Related user name for the resource to manage its access.')
  817. time_efficiency = fields.Float(
  818. 'Efficiency Factor', default=100, required=True,
  819. help="This field is used to calculate the expected duration of a work order at this work center. For example, if a work order takes one hour and the efficiency factor is 100%, then the expected duration will be one hour. If the efficiency factor is 200%, however the expected duration will be 30 minutes.")
  820. calendar_id = fields.Many2one(
  821. "resource.calendar", string='Working Time',
  822. default=lambda self: self.env.company.resource_calendar_id,
  823. required=True, domain="[('company_id', '=', company_id)]")
  824. tz = fields.Selection(
  825. _tz_get, string='Timezone', required=True,
  826. default=lambda self: self._context.get('tz') or self.env.user.tz or 'UTC')
  827. _sql_constraints = [
  828. ('check_time_efficiency', 'CHECK(time_efficiency>0)', 'Time efficiency must be strictly positive'),
  829. ]
  830. @api.model_create_multi
  831. def create(self, vals_list):
  832. for values in vals_list:
  833. if values.get('company_id') and not values.get('calendar_id'):
  834. values['calendar_id'] = self.env['res.company'].browse(values['company_id']).resource_calendar_id.id
  835. if not values.get('tz'):
  836. # retrieve timezone on user or calendar
  837. tz = (self.env['res.users'].browse(values.get('user_id')).tz or
  838. self.env['resource.calendar'].browse(values.get('calendar_id')).tz)
  839. if tz:
  840. values['tz'] = tz
  841. return super(ResourceResource, self).create(vals_list)
  842. @api.returns('self', lambda value: value.id)
  843. def copy(self, default=None):
  844. self.ensure_one()
  845. if default is None:
  846. default = {}
  847. if not default.get('name'):
  848. default.update(name=_('%s (copy)') % (self.name))
  849. return super(ResourceResource, self).copy(default)
  850. def write(self, values):
  851. if self.env.context.get('check_idempotence') and len(self) == 1:
  852. values = {
  853. fname: value
  854. for fname, value in values.items()
  855. if self._fields[fname].convert_to_write(self[fname], self) != value
  856. }
  857. if not values:
  858. return True
  859. return super().write(values)
  860. @api.onchange('company_id')
  861. def _onchange_company_id(self):
  862. if self.company_id:
  863. self.calendar_id = self.company_id.resource_calendar_id.id
  864. @api.onchange('user_id')
  865. def _onchange_user_id(self):
  866. if self.user_id:
  867. self.tz = self.user_id.tz
  868. def _get_work_interval(self, start, end):
  869. # Deprecated method. Use `_adjust_to_calendar` instead
  870. return self._adjust_to_calendar(start, end)
  871. def _adjust_to_calendar(self, start, end, compute_leaves=True):
  872. """Adjust the given start and end datetimes to the closest effective hours encoded
  873. in the resource calendar. Only attendances in the same day as `start` and `end` are
  874. considered (respectively). If no attendance is found during that day, the closest hour
  875. is None.
  876. e.g. simplified example:
  877. given two attendances: 8am-1pm and 2pm-5pm, given start=9am and end=6pm
  878. resource._adjust_to_calendar(start, end)
  879. >>> {resource: (8am, 5pm)}
  880. :return: Closest matching start and end of working periods for each resource
  881. :rtype: dict(resource, tuple(datetime | None, datetime | None))
  882. """
  883. start, revert_start_tz = make_aware(start)
  884. end, revert_end_tz = make_aware(end)
  885. result = {}
  886. for resource in self:
  887. resource_tz = timezone(resource.tz)
  888. start, end = start.astimezone(resource_tz), end.astimezone(resource_tz)
  889. search_range = [
  890. start + relativedelta(hour=0, minute=0, second=0),
  891. end + relativedelta(days=1, hour=0, minute=0, second=0),
  892. ]
  893. calendar_start = resource.calendar_id._get_closest_work_time(start, resource=resource, search_range=search_range,
  894. compute_leaves=compute_leaves)
  895. search_range[0] = start
  896. calendar_end = resource.calendar_id._get_closest_work_time(end if end > start else start, match_end=True,
  897. resource=resource, search_range=search_range,
  898. compute_leaves=compute_leaves)
  899. result[resource] = (
  900. calendar_start and revert_start_tz(calendar_start),
  901. calendar_end and revert_end_tz(calendar_end),
  902. )
  903. return result
  904. def _get_unavailable_intervals(self, start, end):
  905. """ Compute the intervals during which employee is unavailable with hour granularity between start and end
  906. Note: this method is used in enterprise (forecast and planning)
  907. """
  908. start_datetime = timezone_datetime(start)
  909. end_datetime = timezone_datetime(end)
  910. resource_mapping = {}
  911. calendar_mapping = defaultdict(lambda: self.env['resource.resource'])
  912. for resource in self:
  913. calendar_mapping[resource.calendar_id] |= resource
  914. for calendar, resources in calendar_mapping.items():
  915. resources_unavailable_intervals = calendar._unavailable_intervals_batch(start_datetime, end_datetime, resources, tz=timezone(calendar.tz))
  916. resource_mapping.update(resources_unavailable_intervals)
  917. return resource_mapping
  918. def _get_calendars_validity_within_period(self, start, end, default_company=None):
  919. """ Gets a dict of dict with resource's id as first key and resource's calendar as secondary key
  920. The value is the validity interval of the calendar for the given resource.
  921. Here the validity interval for each calendar is the whole interval but it's meant to be overriden in further modules
  922. handling resource's employee contracts.
  923. """
  924. assert start.tzinfo and end.tzinfo
  925. resource_calendars_within_period = defaultdict(lambda: defaultdict(Intervals)) # keys are [resource id:integer][calendar:self.env['resource.calendar']]
  926. default_calendar = default_company and default_company.resource_calendar_id or self.env.company.resource_calendar_id
  927. if not self:
  928. # if no resource, add the company resource calendar.
  929. resource_calendars_within_period[False][default_calendar] = Intervals([(start, end, self.env['resource.calendar.attendance'])])
  930. for resource in self:
  931. calendar = resource.calendar_id or resource.company_id.resource_calendar_id or default_calendar
  932. resource_calendars_within_period[resource.id][calendar] = Intervals([(start, end, self.env['resource.calendar.attendance'])])
  933. return resource_calendars_within_period
  934. def _get_valid_work_intervals(self, start, end, calendars=None):
  935. """ Gets the valid work intervals of the resource following their calendars between ``start`` and ``end``
  936. This methods handle the eventuality of a resource having multiple resource calendars, see _get_calendars_validity_within_period method
  937. for further explanation.
  938. """
  939. assert start.tzinfo and end.tzinfo
  940. resource_calendar_validity_intervals = {}
  941. calendar_resources = defaultdict(lambda: self.env['resource.resource'])
  942. resource_work_intervals = defaultdict(Intervals)
  943. calendar_work_intervals = dict()
  944. resource_calendar_validity_intervals = self.sudo()._get_calendars_validity_within_period(start, end)
  945. for resource in self:
  946. # For each resource, retrieve its calendar and their validity intervals
  947. for calendar in resource_calendar_validity_intervals[resource.id]:
  948. calendar_resources[calendar] |= resource
  949. for calendar in (calendars or []):
  950. calendar_resources[calendar] |= self.env['resource.resource']
  951. for calendar, resources in calendar_resources.items():
  952. # For each calendar used by the resources, retrieve the work intervals for every resources using it
  953. work_intervals_batch = calendar._work_intervals_batch(start, end, resources=resources)
  954. for resource in resources:
  955. # Make the conjunction between work intervals and calendar validity
  956. resource_work_intervals[resource.id] |= work_intervals_batch[resource.id] & resource_calendar_validity_intervals[resource.id][calendar]
  957. calendar_work_intervals[calendar.id] = work_intervals_batch[False]
  958. return resource_work_intervals, calendar_work_intervals
  959. class ResourceCalendarLeaves(models.Model):
  960. _name = "resource.calendar.leaves"
  961. _description = "Resource Time Off Detail"
  962. _order = "date_from"
  963. def default_get(self, fields_list):
  964. res = super().default_get(fields_list)
  965. if 'date_from' in fields_list and 'date_to' in fields_list and not res.get('date_from') and not res.get('date_to'):
  966. # Then we give the current day and we search the begin and end hours for this day in resource.calendar of the current company
  967. today = fields.Datetime.now()
  968. user_tz = timezone(self.env.user.tz or self._context.get('tz') or self.company_id.resource_calendar_id.tz or 'UTC')
  969. date_from = user_tz.localize(datetime.combine(today, time.min))
  970. date_to = user_tz.localize(datetime.combine(today, time.max))
  971. intervals = self.env.company.resource_calendar_id._work_intervals_batch(date_from.replace(tzinfo=utc), date_to.replace(tzinfo=utc))[False]
  972. if intervals: # Then we stop and return the dates given in parameter
  973. list_intervals = [(start, stop) for start, stop, records in intervals] # Convert intervals in interval list
  974. date_from = list_intervals[0][0] # We take the first date in the interval list
  975. date_to = list_intervals[-1][1] # We take the last date in the interval list
  976. res.update(
  977. date_from=date_from.astimezone(utc).replace(tzinfo=None),
  978. date_to=date_to.astimezone(utc).replace(tzinfo=None)
  979. )
  980. return res
  981. name = fields.Char('Reason')
  982. company_id = fields.Many2one(
  983. 'res.company', string="Company", readonly=True, store=True,
  984. default=lambda self: self.env.company, compute='_compute_company_id')
  985. calendar_id = fields.Many2one('resource.calendar', 'Working Hours', domain="[('company_id', 'in', [company_id, False])]", check_company=True, index=True)
  986. date_from = fields.Datetime('Start Date', required=True)
  987. date_to = fields.Datetime('End Date', required=True)
  988. resource_id = fields.Many2one(
  989. "resource.resource", 'Resource', index=True,
  990. help="If empty, this is a generic time off for the company. If a resource is set, the time off is only for this resource")
  991. time_type = fields.Selection([('leave', 'Time Off'), ('other', 'Other')], default='leave',
  992. help="Whether this should be computed as a time off or as work time (eg: formation)")
  993. @api.depends('calendar_id')
  994. def _compute_company_id(self):
  995. for leave in self:
  996. leave.company_id = leave.calendar_id.company_id or leave.company_id or self.env.company
  997. @api.constrains('date_from', 'date_to')
  998. def check_dates(self):
  999. if self.filtered(lambda leave: leave.date_from > leave.date_to):
  1000. raise ValidationError(_('The start date of the time off must be earlier than the end date.'))
  1001. @api.onchange('resource_id')
  1002. def onchange_resource(self):
  1003. if self.resource_id:
  1004. self.calendar_id = self.resource_id.calendar_id
  1005. def _copy_leave_vals(self):
  1006. self.ensure_one()
  1007. return {
  1008. 'name': self.name,
  1009. 'date_from': self.date_from,
  1010. 'date_to': self.date_to,
  1011. 'time_type': self.time_type,
  1012. }