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.

500 lines
22 KiB

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