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.

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