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.

494 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
  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 = add_days_delta(date, 1)
  125. date = self._next_countdown_date(rec.irregular_start_date,
  126. date)
  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. rec.future_alert_date = self._next_countdown_date(
  141. rec.irregular_start_date, date
  142. )
  143. @api.depends('today', 'irregular_start_date', 'holiday_start_time',
  144. 'holiday_end_time', 'temporary_exempt_start_date',
  145. 'temporary_exempt_end_date')
  146. def _compute_next_countdown_date(self):
  147. """
  148. Compute the following countdown date. This date is the date when
  149. the worker will see his counter changed du to the cron. This
  150. date is like the birthday date of the worker that occurred each
  151. PERIOD.
  152. """
  153. for rec in self:
  154. # Only for irregular worker
  155. if rec.working_mode != 'irregular' and not rec.irregular_start_date:
  156. rec.next_countdown_date = False
  157. # Holidays are not set properly
  158. elif bool(rec.holiday_start_time) != bool(rec.holiday_end_time):
  159. rec.next_countdown_date = False
  160. # Exemption have not a start and end time
  161. elif (bool(rec.temporary_exempt_start_date)
  162. != bool(rec.temporary_exempt_end_date)):
  163. rec.next_countdown_date = False
  164. else:
  165. date = rec.today
  166. next_countdown_date = False
  167. while not next_countdown_date:
  168. date = self._next_countdown_date(rec.irregular_start_date, date)
  169. # Check holidays
  170. if (rec.holiday_start_time and rec.holiday_end_time
  171. and date >= rec.holiday_start_time
  172. and date <= rec.holiday_end_time):
  173. date = add_days_delta(date, 1)
  174. continue
  175. # Check temporary exemption
  176. elif (rec.temporary_exempt_start_date
  177. and rec.temporary_exempt_end_date
  178. and date >= rec.temporary_exempt_start_date
  179. and date <= rec.temporary_exempt_end_date):
  180. date = add_days_delta(date, 1)
  181. continue
  182. else:
  183. next_countdown_date = date
  184. rec.next_countdown_date = next_countdown_date
  185. def _next_countdown_date(self, irregular_start_date, today=False):
  186. """
  187. Return the next countdown date given irregular_start_date and
  188. today dates.
  189. This does not take holiday and other status into account.
  190. """
  191. today = today or fields.Date.today()
  192. today_dt = fields.Date.from_string(today)
  193. irregular_start_dt = fields.Date.from_string(irregular_start_date)
  194. delta = (today_dt - irregular_start_dt).days
  195. if not delta % PERIOD:
  196. return today
  197. return add_days_delta(today, PERIOD - (delta % PERIOD))
  198. def _set_regular_status(self, grace_delay, alert_delay):
  199. self.ensure_one()
  200. counter_unsubscribe = int(self.env['ir.config_parameter'].get_param('regular_counter_to_unsubscribe', -4))
  201. ok = self.sr >= 0 and self.sc >= 0
  202. grace_delay = grace_delay + self.time_extension
  203. if (self.sr + self.sc) <= counter_unsubscribe or self.unsubscribed:
  204. self.status = 'unsubscribed'
  205. self.can_shop = False
  206. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  207. self.status = 'exempted'
  208. self.can_shop = True
  209. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  210. 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):
  211. self.status = 'extension'
  212. self.can_shop = True
  213. 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):
  214. self.status = 'suspended'
  215. self.can_shop = False
  216. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  217. self.status = 'suspended'
  218. self.can_shop = False
  219. elif (self.sr < 0) or (not ok and self.alert_start_time):
  220. self.status = 'alert'
  221. self.can_shop = True
  222. #Check for holidays; Can be in holidays even in alert or other mode ?
  223. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  224. self.status = 'holiday'
  225. self.can_shop = False
  226. elif ok or (not self.alert_start_time and self.sr >= 0):
  227. self.status = 'ok'
  228. self.can_shop = True
  229. def _set_irregular_status(self, grace_delay, alert_delay):
  230. counter_unsubscribe = int(self.env['ir.config_parameter'].get_param('irregular_counter_to_unsubscribe', -3))
  231. self.ensure_one()
  232. ok = self.sr >= 0
  233. grace_delay = grace_delay + self.time_extension
  234. if self.sr <= counter_unsubscribe or self.unsubscribed:
  235. self.status = 'unsubscribed'
  236. self.can_shop = False
  237. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  238. self.status = 'exempted'
  239. self.can_shop = True
  240. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  241. 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):
  242. self.status = 'extension'
  243. self.can_shop = True
  244. 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):
  245. self.status = 'suspended'
  246. self.can_shop = False
  247. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  248. self.status = 'suspended'
  249. self.can_shop = False
  250. elif (self.sr < 0) or (not ok and self.alert_start_time):
  251. self.status = 'alert'
  252. self.can_shop = True
  253. #Check for holidays; Can be in holidays even in alert or other mode ?
  254. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  255. self.status = 'holiday'
  256. self.can_shop = False
  257. elif ok or (not self.alert_start_time and self.sr >= 0):
  258. self.status = 'ok'
  259. self.can_shop = True
  260. @api.multi
  261. def write(self, vals):
  262. """
  263. Overwrite write to historize the change
  264. """
  265. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time', 'unsubscribed']:
  266. if not field in vals:
  267. continue
  268. for rec in self:
  269. data = {
  270. 'status_id': rec.id,
  271. 'cooperator_id': rec.cooperator_id.id,
  272. 'type': 'counter',
  273. 'user_id': self.env.context.get('real_uid', self.env.uid),
  274. }
  275. if vals.get(field, rec[field]) != rec[field]:
  276. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  277. self.env['cooperative.status.history'].sudo().create(data)
  278. return super(CooperativeStatus, self).write(vals)
  279. def _state_change(self, new_state):
  280. self.ensure_one()
  281. if new_state == 'alert':
  282. self.write({'alert_start_time': self.today, 'extension_start_time': False, 'time_extension': 0})
  283. if new_state == 'ok':
  284. data = {'extension_start_time': False, 'time_extension': 0}
  285. data['alert_start_time'] = False
  286. self.write(data)
  287. if new_state == 'unsubscribed' or new_state == 'resigning':
  288. # Remove worker from task_templates
  289. self.cooperator_id.sudo().write(
  290. {'subscribed_shift_ids': [(5, 0, 0)]})
  291. # Remove worker from supercoop in task_templates
  292. task_tpls = self.env['beesdoo.shift.template'].search(
  293. [('super_coop_id', 'in', self.cooperator_id.user_ids.ids)]
  294. )
  295. task_tpls.write({'super_coop_id': False})
  296. # Remove worker for future task (remove also supercoop)
  297. # TODO: Add one day otherwise unsubscribed from the shift you were absent
  298. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today(
  299. [self.cooperator_id.id], today=fields.Date.today())
  300. def _change_counter(self, data):
  301. self.sc += data.get('sc', 0)
  302. self.sr += data.get('sr', 0)
  303. self.irregular_absence_counter += data.get('irregular_absence_counter', 0)
  304. self.irregular_absence_date = data.get('irregular_absence_date', False)
  305. @api.multi
  306. def _write(self, vals):
  307. """
  308. Overwrite write to historize the change of status
  309. and make action on status change
  310. """
  311. if 'status' in vals:
  312. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  313. result = self._cr.dictfetchall()
  314. old_status_per_id = {r['id'] : r for r in result}
  315. for rec in self:
  316. if old_status_per_id[rec.id]['status'] != vals['status']:
  317. data = {
  318. 'status_id': rec.id,
  319. 'cooperator_id': rec.cooperator_id.id,
  320. 'type': 'status',
  321. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  322. 'user_id': self.env.context.get('real_uid', self.env.uid),
  323. }
  324. self.env['cooperative.status.history'].sudo().create(data)
  325. rec._state_change(vals['status'])
  326. return super(CooperativeStatus, self)._write(vals)
  327. _sql_constraints = [
  328. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  329. ]
  330. @api.model
  331. def _set_today(self):
  332. """
  333. Method call by the cron to update store value base on the date
  334. """
  335. self.search([]).write({'today': fields.Date.today()})
  336. @api.multi
  337. def clear_history(self):
  338. self.ensure_one()
  339. self.history_ids.unlink()
  340. @api.model
  341. def _cron_compute_counter_irregular(self, today=False):
  342. today = today or fields.Date.today()
  343. journal = self.env['beesdoo.shift.journal'].search([('date', '=', today)])
  344. if not journal:
  345. journal = self.env['beesdoo.shift.journal'].create({'date': today})
  346. domain = ['&',
  347. '&',
  348. '&', ('status', '!=', 'unsubscribed'),
  349. ('working_mode', '=', 'irregular'),
  350. ('irregular_start_date', '!=', False),
  351. '|',
  352. '|', ('holiday_start_time', '=', False), ('holiday_end_time', '=', False),
  353. '|', ('holiday_start_time', '>', today), ('holiday_end_time', '<', today),
  354. ]
  355. irregular = self.search(domain)
  356. today_date = fields.Date.from_string(today)
  357. for status in irregular:
  358. if status.status == 'exempted':
  359. continue
  360. delta = (today_date - fields.Date.from_string(status.irregular_start_date)).days
  361. if delta and delta % PERIOD == 0 and status not in journal.line_ids:
  362. if status.sr > 0:
  363. status.sr -= 1
  364. elif status.alert_start_time:
  365. status.sr -= 1
  366. else:
  367. status.sr -= 2
  368. journal.line_ids |= status
  369. class ShiftCronJournal(models.Model):
  370. _name = 'beesdoo.shift.journal'
  371. _order = 'date desc'
  372. _rec_name = 'date'
  373. date = fields.Date()
  374. line_ids = fields.Many2many('cooperative.status')
  375. _sql_constraints = [
  376. ('one_entry_per_day', 'unique (date)', _('You can only create one journal per day')),
  377. ]
  378. @api.multi
  379. def run(self):
  380. self.ensure_one()
  381. if not self.user_has_groups('beesdoo_shift.group_cooperative_admin'):
  382. raise ValidationError(_("You don't have the access to perform this action"))
  383. self.sudo().env['cooperative.status']._cron_compute_counter_irregular(today=self.date)
  384. class ResPartner(models.Model):
  385. _inherit = 'res.partner'
  386. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  387. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  388. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  389. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  390. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  391. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  392. state = fields.Selection(related='cooperative_status_ids.status', readonly=True, store=True)
  393. extension_start_time = fields.Date(related='cooperative_status_ids.extension_start_time', string="Extension Start Day", readonly=True, store=True)
  394. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  395. @api.multi
  396. def coop_subscribe(self):
  397. return {
  398. 'name': _('Subscribe Cooperator'),
  399. 'type': 'ir.actions.act_window',
  400. 'view_type': 'form',
  401. 'view_mode': 'form',
  402. 'res_model': 'beesdoo.shift.subscribe',
  403. 'target': 'new',
  404. }
  405. @api.multi
  406. def coop_unsubscribe(self):
  407. res = self.coop_subscribe()
  408. res['context'] = {'default_unsubscribed': True}
  409. return res
  410. @api.multi
  411. def manual_extension(self):
  412. return {
  413. 'name': _('Manual Extension'),
  414. 'type': 'ir.actions.act_window',
  415. 'view_type': 'form',
  416. 'view_mode': 'form',
  417. 'res_model': 'beesdoo.shift.extension',
  418. 'target': 'new',
  419. }
  420. @api.multi
  421. def auto_extension(self):
  422. res = self.manual_extension()
  423. res['context'] = {'default_auto': True}
  424. res['name'] = _('Trigger Grace Delay')
  425. return res
  426. @api.multi
  427. def register_holiday(self):
  428. return {
  429. 'name': _('Register Holiday'),
  430. 'type': 'ir.actions.act_window',
  431. 'view_type': 'form',
  432. 'view_mode': 'form',
  433. 'res_model': 'beesdoo.shift.holiday',
  434. 'target': 'new',
  435. }
  436. @api.multi
  437. def temporary_exempt(self):
  438. return {
  439. 'name': _('Temporary Exemption'),
  440. 'type': 'ir.actions.act_window',
  441. 'view_type': 'form',
  442. 'view_mode': 'form',
  443. 'res_model': 'beesdoo.shift.temporary_exemption',
  444. 'target': 'new',
  445. }
  446. #TODO access right + vue on res.partner
  447. #TODO can_shop : Status can_shop ou extempted ou part C