You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

507 lines
23 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. from odoo import models, fields, api, _
  3. from odoo.exceptions import ValidationError, UserError
  4. from datetime import timedelta, datetime
  5. import logging
  6. _logger = logging.getLogger(__name__)
  7. PERIOD = 28 # TODO: use system parameter
  8. def add_days_delta(date_from, days_delta):
  9. if not date_from:
  10. return date_from
  11. next_date = fields.Date.from_string(date_from) + timedelta(days=days_delta)
  12. return fields.Date.to_string(next_date)
  13. class ExemptReason(models.Model):
  14. _name = 'cooperative.exempt.reason'
  15. name = fields.Char(required=True)
  16. class HistoryStatus(models.Model):
  17. _name = 'cooperative.status.history'
  18. _order= 'create_date desc'
  19. status_id = fields.Many2one('cooperative.status')
  20. cooperator_id = fields.Many2one('res.partner')
  21. change = fields.Char()
  22. type = fields.Selection([('status', 'Status Change'), ('counter', 'Counter Change')])
  23. user_id = fields.Many2one('res.users', string="User")
  24. class CooperativeStatus(models.Model):
  25. _name = 'cooperative.status'
  26. _rec_name = 'cooperator_id'
  27. _order = 'cooperator_id'
  28. def get_status_value(self):
  29. """
  30. Workararound to get translated selection value instead of key in mail template.
  31. """
  32. state_list = self.env["cooperative.status"]._fields["status"].selection
  33. state_list = self.env["cooperative.status"]._fields['status']._description_selection(self.env)
  34. return dict(state_list)[self.status]
  35. today = fields.Date(help="Field that allow to compute field and store them even if they are based on the current date", default=fields.Date.today)
  36. cooperator_id = fields.Many2one('res.partner')
  37. active = fields.Boolean(related="cooperator_id.active", store=True, index=True)
  38. info_session = fields.Boolean('Information Session ?')
  39. info_session_date = fields.Datetime('Information Session Date')
  40. super = fields.Boolean("Super Cooperative")
  41. sr = fields.Integer("Regular shifts counter", default=0)
  42. sc = fields.Integer("Compensation shifts counter", default=0)
  43. time_extension = fields.Integer("Extension Days NB", default=0, help="Addtional days to the automatic extension, 5 mean that you have a total of 15 extension days of default one is set to 10")
  44. holiday_start_time = fields.Date("Holidays Start Day")
  45. holiday_end_time = fields.Date("Holidays End Day")
  46. alert_start_time = fields.Date("Alert Start Day")
  47. extension_start_time = fields.Date("Extension Start Day")
  48. #Champ compute
  49. working_mode = fields.Selection(
  50. [
  51. ('regular', 'Regular worker'),
  52. ('irregular', 'Irregular worker'),
  53. ('exempt', 'Exempted'),
  54. ],
  55. string="Working mode"
  56. )
  57. exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  58. status = fields.Selection([('ok', 'Up to Date'),
  59. ('holiday', 'Holidays'),
  60. ('alert', 'Alerte'),
  61. ('extension', 'Extension'),
  62. ('suspended', 'Suspended'),
  63. ('exempted', 'Exempted'),
  64. ('unsubscribed', 'Unsubscribed'),
  65. ('resigning', 'Resigning')],
  66. compute="_compute_status", string="Cooperative Status", store=True)
  67. can_shop = fields.Boolean(compute='_compute_status', store=True)
  68. history_ids = fields.One2many('cooperative.status.history', 'status_id', readonly=True)
  69. unsubscribed = fields.Boolean(default=False, help="Manually unsubscribed")
  70. resigning = fields.Boolean(default=False, help="Want to leave the beescoop")
  71. #Specific to irregular
  72. irregular_start_date = fields.Date() #TODO migration script
  73. irregular_absence_date = fields.Date()
  74. irregular_absence_counter = fields.Integer() #TODO unsubscribe when reach -2
  75. future_alert_date = fields.Date(compute='_compute_future_alert_date')
  76. next_countdown_date = fields.Date(compute='_compute_next_countdown_date')
  77. temporary_exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  78. temporary_exempt_start_date = fields.Date()
  79. temporary_exempt_end_date = fields.Date()
  80. @api.depends('today', 'sr', 'sc', 'holiday_end_time',
  81. 'holiday_start_time', 'time_extension',
  82. 'alert_start_time', 'extension_start_time',
  83. 'unsubscribed', 'irregular_absence_date',
  84. 'irregular_absence_counter', 'temporary_exempt_start_date',
  85. 'temporary_exempt_end_date', 'resigning', 'cooperator_id.subscribed_shift_ids')
  86. def _compute_status(self):
  87. alert_delay = int(self.env['ir.config_parameter'].get_param('alert_delay', 28))
  88. grace_delay = int(self.env['ir.config_parameter'].get_param('default_grace_delay', 10))
  89. update = int(self.env['ir.config_parameter'].get_param('always_update', False))
  90. for rec in self:
  91. if update or not rec.today:
  92. rec.status = 'ok'
  93. rec.can_shop = True
  94. continue
  95. if rec.resigning:
  96. rec.status = 'resigning'
  97. rec.can_shop = False
  98. continue
  99. if rec.working_mode == 'regular':
  100. rec._set_regular_status(grace_delay, alert_delay)
  101. elif rec.working_mode == 'irregular':
  102. rec._set_irregular_status(grace_delay, alert_delay)
  103. elif rec.working_mode == 'exempt':
  104. rec.status = 'ok'
  105. rec.can_shop = True
  106. @api.depends('today', 'irregular_start_date', 'sr', 'holiday_start_time',
  107. 'holiday_end_time', 'temporary_exempt_start_date',
  108. 'temporary_exempt_end_date')
  109. def _compute_future_alert_date(self):
  110. """Compute date before which the worker is up to date"""
  111. for rec in self:
  112. # Only for irregular worker
  113. if rec.working_mode != 'irregular' and not rec.irregular_start_date:
  114. rec.future_alert_date = False
  115. # Alert start time already set
  116. elif rec.alert_start_time:
  117. rec.future_alert_date = False
  118. # Holidays are not set properly
  119. elif bool(rec.holiday_start_time) != bool(rec.holiday_end_time):
  120. rec.future_alert_date = False
  121. # Exemption have not a start and end time
  122. elif (bool(rec.temporary_exempt_start_date)
  123. != bool(rec.temporary_exempt_end_date)):
  124. rec.future_alert_date = False
  125. else:
  126. date = rec.today
  127. counter = rec.sr
  128. # Simulate the countdown
  129. while counter > 0:
  130. date = add_days_delta(date, 1)
  131. date = self._next_countdown_date(rec.irregular_start_date,
  132. date)
  133. # Check holidays
  134. if (rec.holiday_start_time and rec.holiday_end_time
  135. and date >= rec.holiday_start_time
  136. and date <= rec.holiday_end_time):
  137. continue
  138. # Check temporary exemption
  139. elif (rec.temporary_exempt_start_date
  140. and rec.temporary_exempt_end_date
  141. and date >= rec.temporary_exempt_start_date
  142. and date <= rec.temporary_exempt_end_date):
  143. continue
  144. else:
  145. counter -= 1
  146. rec.future_alert_date = self._next_countdown_date(
  147. rec.irregular_start_date, date
  148. )
  149. @api.depends('today', 'irregular_start_date', 'holiday_start_time',
  150. 'holiday_end_time', 'temporary_exempt_start_date',
  151. 'temporary_exempt_end_date')
  152. def _compute_next_countdown_date(self):
  153. """
  154. Compute the following countdown date. This date is the date when
  155. the worker will see his counter changed du to the cron. This
  156. date is like the birthday date of the worker that occurred each
  157. PERIOD.
  158. """
  159. for rec in self:
  160. # Only for irregular worker
  161. if rec.working_mode != 'irregular' and not rec.irregular_start_date:
  162. rec.next_countdown_date = False
  163. # Holidays are not set properly
  164. elif bool(rec.holiday_start_time) != bool(rec.holiday_end_time):
  165. rec.next_countdown_date = False
  166. # Exemption have not a start and end time
  167. elif (bool(rec.temporary_exempt_start_date)
  168. != bool(rec.temporary_exempt_end_date)):
  169. rec.next_countdown_date = False
  170. else:
  171. date = rec.today
  172. next_countdown_date = False
  173. while not next_countdown_date:
  174. date = self._next_countdown_date(rec.irregular_start_date, date)
  175. # Check holidays
  176. if (rec.holiday_start_time and rec.holiday_end_time
  177. and date >= rec.holiday_start_time
  178. and date <= rec.holiday_end_time):
  179. date = add_days_delta(date, 1)
  180. continue
  181. # Check temporary exemption
  182. elif (rec.temporary_exempt_start_date
  183. and rec.temporary_exempt_end_date
  184. and date >= rec.temporary_exempt_start_date
  185. and date <= rec.temporary_exempt_end_date):
  186. date = add_days_delta(date, 1)
  187. continue
  188. else:
  189. next_countdown_date = date
  190. rec.next_countdown_date = next_countdown_date
  191. @api.constrains("working_mode", "irregular_start_date")
  192. def _constrains_irregular_start_date(self):
  193. if self.working_mode == "irregular" and not self.irregular_start_date:
  194. raise UserError(_("Irregular workers must have an irregular start date."))
  195. def _next_countdown_date(self, irregular_start_date, today=False):
  196. """
  197. Return the next countdown date given irregular_start_date and
  198. today dates.
  199. This does not take holiday and other status into account.
  200. """
  201. today = today or fields.Date.today()
  202. today_dt = fields.Date.from_string(today)
  203. irregular_start_dt = fields.Date.from_string(irregular_start_date)
  204. delta = (today_dt - irregular_start_dt).days
  205. if not delta % PERIOD:
  206. return today
  207. return add_days_delta(today, PERIOD - (delta % PERIOD))
  208. def _set_regular_status(self, grace_delay, alert_delay):
  209. self.ensure_one()
  210. counter_unsubscribe = int(self.env['ir.config_parameter'].get_param('regular_counter_to_unsubscribe', -4))
  211. ok = self.sr >= 0 and self.sc >= 0
  212. grace_delay = grace_delay + self.time_extension
  213. if (self.sr + self.sc) <= counter_unsubscribe or self.unsubscribed:
  214. self.status = 'unsubscribed'
  215. self.can_shop = False
  216. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  217. self.status = 'exempted'
  218. self.can_shop = True
  219. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  220. elif not ok and self.alert_start_time and self.extension_start_time and self.today <= add_days_delta(self.extension_start_time, grace_delay):
  221. self.status = 'extension'
  222. self.can_shop = True
  223. elif not ok and self.alert_start_time and self.extension_start_time and self.today > add_days_delta(self.extension_start_time, grace_delay):
  224. self.status = 'suspended'
  225. self.can_shop = False
  226. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  227. self.status = 'suspended'
  228. self.can_shop = False
  229. elif (self.sr < 0) or (not ok and self.alert_start_time):
  230. self.status = 'alert'
  231. self.can_shop = True
  232. #Check for holidays; Can be in holidays even in alert or other mode ?
  233. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  234. self.status = 'holiday'
  235. self.can_shop = False
  236. elif ok or (not self.alert_start_time and self.sr >= 0):
  237. self.status = 'ok'
  238. self.can_shop = True
  239. def _set_irregular_status(self, grace_delay, alert_delay):
  240. counter_unsubscribe = int(self.env['ir.config_parameter'].get_param('irregular_counter_to_unsubscribe', -3))
  241. self.ensure_one()
  242. ok = self.sr >= 0
  243. grace_delay = grace_delay + self.time_extension
  244. if self.sr <= counter_unsubscribe or self.unsubscribed:
  245. self.status = 'unsubscribed'
  246. self.can_shop = False
  247. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  248. self.status = 'exempted'
  249. self.can_shop = True
  250. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  251. elif not ok and self.alert_start_time and self.extension_start_time and self.today <= add_days_delta(self.extension_start_time, grace_delay):
  252. self.status = 'extension'
  253. self.can_shop = True
  254. elif not ok and self.alert_start_time and self.extension_start_time and self.today > add_days_delta(self.extension_start_time, grace_delay):
  255. self.status = 'suspended'
  256. self.can_shop = False
  257. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  258. self.status = 'suspended'
  259. self.can_shop = False
  260. elif (self.sr < 0) or (not ok and self.alert_start_time):
  261. self.status = 'alert'
  262. self.can_shop = True
  263. #Check for holidays; Can be in holidays even in alert or other mode ?
  264. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  265. self.status = 'holiday'
  266. self.can_shop = False
  267. elif ok or (not self.alert_start_time and self.sr >= 0):
  268. self.status = 'ok'
  269. self.can_shop = True
  270. @api.multi
  271. def write(self, vals):
  272. """
  273. Overwrite write to historize the change
  274. """
  275. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time', 'unsubscribed']:
  276. if not field in vals:
  277. continue
  278. for rec in self:
  279. data = {
  280. 'status_id': rec.id,
  281. 'cooperator_id': rec.cooperator_id.id,
  282. 'type': 'counter',
  283. 'user_id': self.env.context.get('real_uid', self.env.uid),
  284. }
  285. if vals.get(field, rec[field]) != rec[field]:
  286. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  287. self.env['cooperative.status.history'].sudo().create(data)
  288. return super(CooperativeStatus, self).write(vals)
  289. def _state_change(self, new_state):
  290. self.ensure_one()
  291. if new_state == 'alert':
  292. self.write({'alert_start_time': self.today, 'extension_start_time': False, 'time_extension': 0})
  293. if new_state == 'ok':
  294. data = {'extension_start_time': False, 'time_extension': 0}
  295. data['alert_start_time'] = False
  296. self.write(data)
  297. if new_state == 'unsubscribed' or new_state == 'resigning':
  298. # Remove worker from task_templates
  299. self.cooperator_id.sudo().write(
  300. {'subscribed_shift_ids': [(5, 0, 0)]})
  301. # Remove worker from supercoop in task_templates
  302. task_tpls = self.env['beesdoo.shift.template'].search(
  303. [('super_coop_id', 'in', self.cooperator_id.user_ids.ids)]
  304. )
  305. task_tpls.write({'super_coop_id': False})
  306. # Remove worker for future tasks (remove also supercoop)
  307. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today(
  308. [self.cooperator_id.id], now=fields.Datetime.now()
  309. )
  310. def _change_counter(self, data):
  311. self.sc += data.get('sc', 0)
  312. self.sr += data.get('sr', 0)
  313. self.irregular_absence_counter += data.get('irregular_absence_counter', 0)
  314. self.irregular_absence_date = data.get('irregular_absence_date', False)
  315. @api.multi
  316. def _write(self, vals):
  317. """
  318. Overwrite write to historize the change of status
  319. and make action on status change
  320. """
  321. if 'status' in vals:
  322. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  323. result = self._cr.dictfetchall()
  324. old_status_per_id = {r['id'] : r for r in result}
  325. for rec in self:
  326. if old_status_per_id[rec.id]['status'] != vals['status']:
  327. data = {
  328. 'status_id': rec.id,
  329. 'cooperator_id': rec.cooperator_id.id,
  330. 'type': 'status',
  331. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  332. 'user_id': self.env.context.get('real_uid', self.env.uid),
  333. }
  334. self.env['cooperative.status.history'].sudo().create(data)
  335. rec._state_change(vals['status'])
  336. return super(CooperativeStatus, self)._write(vals)
  337. _sql_constraints = [
  338. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  339. ]
  340. @api.model
  341. def _set_today(self):
  342. """
  343. Method call by the cron to update store value base on the date
  344. """
  345. self.search([]).write({'today': fields.Date.today()})
  346. @api.multi
  347. def clear_history(self):
  348. self.ensure_one()
  349. self.history_ids.unlink()
  350. @api.model
  351. def _cron_compute_counter_irregular(self, today=False):
  352. today = today or fields.Date.today()
  353. journal = self.env['beesdoo.shift.journal'].search([('date', '=', today)])
  354. if not journal:
  355. journal = self.env['beesdoo.shift.journal'].create({'date': today})
  356. domain = ['&',
  357. '&',
  358. '&', ('status', '!=', 'unsubscribed'),
  359. ('working_mode', '=', 'irregular'),
  360. ('irregular_start_date', '!=', False),
  361. '|',
  362. '|', ('holiday_start_time', '=', False), ('holiday_end_time', '=', False),
  363. '|', ('holiday_start_time', '>', today), ('holiday_end_time', '<', today),
  364. ]
  365. irregular = self.search(domain)
  366. today_date = fields.Date.from_string(today)
  367. for status in irregular:
  368. if status.status == 'exempted':
  369. continue
  370. delta = (today_date - fields.Date.from_string(status.irregular_start_date)).days
  371. if delta and delta % PERIOD == 0 and status not in journal.line_ids:
  372. if status.sr > 0:
  373. status.sr -= 1
  374. elif status.alert_start_time:
  375. status.sr -= 1
  376. else:
  377. status.sr -= 2
  378. journal.line_ids |= status
  379. class ShiftCronJournal(models.Model):
  380. _name = 'beesdoo.shift.journal'
  381. _order = 'date desc'
  382. _rec_name = 'date'
  383. date = fields.Date()
  384. line_ids = fields.Many2many('cooperative.status')
  385. _sql_constraints = [
  386. ('one_entry_per_day', 'unique (date)', _('You can only create one journal per day')),
  387. ]
  388. @api.multi
  389. def run(self):
  390. self.ensure_one()
  391. if not self.user_has_groups('beesdoo_shift.group_cooperative_admin'):
  392. raise ValidationError(_("You don't have the access to perform this action"))
  393. self.sudo().env['cooperative.status']._cron_compute_counter_irregular(today=self.date)
  394. class ResPartner(models.Model):
  395. _inherit = 'res.partner'
  396. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  397. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  398. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  399. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  400. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  401. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  402. state = fields.Selection(related='cooperative_status_ids.status', readonly=True, store=True)
  403. extension_start_time = fields.Date(related='cooperative_status_ids.extension_start_time', string="Extension Start Day", readonly=True, store=True)
  404. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  405. @api.multi
  406. def coop_subscribe(self):
  407. return {
  408. 'name': _('Subscribe Cooperator'),
  409. 'type': 'ir.actions.act_window',
  410. 'view_type': 'form',
  411. 'view_mode': 'form',
  412. 'res_model': 'beesdoo.shift.subscribe',
  413. 'target': 'new',
  414. }
  415. @api.multi
  416. def coop_unsubscribe(self):
  417. res = self.coop_subscribe()
  418. res['context'] = {'default_unsubscribed': True}
  419. return res
  420. @api.multi
  421. def manual_extension(self):
  422. return {
  423. 'name': _('Manual Extension'),
  424. 'type': 'ir.actions.act_window',
  425. 'view_type': 'form',
  426. 'view_mode': 'form',
  427. 'res_model': 'beesdoo.shift.extension',
  428. 'target': 'new',
  429. }
  430. @api.multi
  431. def auto_extension(self):
  432. res = self.manual_extension()
  433. res['context'] = {'default_auto': True}
  434. res['name'] = _('Trigger Grace Delay')
  435. return res
  436. @api.multi
  437. def register_holiday(self):
  438. return {
  439. 'name': _('Register Holiday'),
  440. 'type': 'ir.actions.act_window',
  441. 'view_type': 'form',
  442. 'view_mode': 'form',
  443. 'res_model': 'beesdoo.shift.holiday',
  444. 'target': 'new',
  445. }
  446. @api.multi
  447. def temporary_exempt(self):
  448. return {
  449. 'name': _('Temporary Exemption'),
  450. 'type': 'ir.actions.act_window',
  451. 'view_type': 'form',
  452. 'view_mode': 'form',
  453. 'res_model': 'beesdoo.shift.temporary_exemption',
  454. 'target': 'new',
  455. }
  456. #TODO access right + vue on res.partner
  457. #TODO can_shop : Status can_shop ou extempted ou part C