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.

398 lines
18 KiB

7 years ago
7 years ago
7 years ago
7 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. temporary_exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  71. temporary_exempt_start_date = fields.Date()
  72. temporary_exempt_end_date = fields.Date()
  73. @api.depends('today', 'sr', 'sc', 'holiday_end_time',
  74. 'holiday_start_time', 'time_extension',
  75. 'alert_start_time', 'extension_start_time',
  76. 'unsubscribed', 'irregular_absence_date',
  77. 'irregular_absence_counter', 'temporary_exempt_start_date',
  78. 'temporary_exempt_end_date', 'resigning', 'cooperator_id.subscribed_shift_ids')
  79. def _compute_status(self):
  80. alert_delay = int(self.env['ir.config_parameter'].get_param('alert_delay', 28))
  81. grace_delay = int(self.env['ir.config_parameter'].get_param('default_grace_delay', 10))
  82. update = int(self.env['ir.config_parameter'].get_param('always_update', False))
  83. for rec in self:
  84. if update or not rec.today:
  85. rec.status = 'ok'
  86. rec.can_shop = True
  87. continue
  88. if rec.resigning:
  89. rec.status = 'resigning'
  90. rec.can_shop = False
  91. continue
  92. if rec.working_mode == 'regular':
  93. rec._set_regular_status(grace_delay, alert_delay)
  94. elif rec.working_mode == 'irregular':
  95. rec._set_irregular_status(grace_delay, alert_delay)
  96. elif rec.working_mode == 'exempt':
  97. rec.status = 'ok'
  98. rec.can_shop = True
  99. @api.depends('today', 'irregular_start_date', 'sr')
  100. def _compute_future_alert_date(self):
  101. """Compute date before which the worker is up to date"""
  102. for rec in self:
  103. future_alert_date = False
  104. if not rec.alert_start_time and rec.irregular_start_date:
  105. today_date = fields.Date.from_string(rec.today)
  106. delta = (today_date - fields.Date.from_string(rec.irregular_start_date)).days
  107. future_alert_date = today_date + timedelta(days=(rec.sr + 1) * PERIOD - delta % PERIOD)
  108. future_alert_date = future_alert_date.strftime('%Y-%m-%d')
  109. rec.future_alert_date = future_alert_date
  110. def _set_regular_status(self, grace_delay, alert_delay):
  111. self.ensure_one()
  112. ok = self.sr >= 0 and self.sc >= 0
  113. grace_delay = grace_delay + self.time_extension
  114. if self.sr < -1 or self.unsubscribed:
  115. self.status = 'unsubscribed'
  116. self.can_shop = False
  117. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  118. self.status = 'exempted'
  119. self.can_shop = True
  120. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  121. 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):
  122. self.status = 'extension'
  123. self.can_shop = True
  124. 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):
  125. self.status = 'suspended'
  126. self.can_shop = False
  127. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  128. self.status = 'suspended'
  129. self.can_shop = False
  130. elif (self.sr < 0) or (not ok and self.alert_start_time):
  131. self.status = 'alert'
  132. self.can_shop = True
  133. #Check for holidays; Can be in holidays even in alert or other mode ?
  134. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  135. self.status = 'holiday'
  136. self.can_shop = False
  137. elif ok or (not self.alert_start_time and self.sr >= 0):
  138. self.status = 'ok'
  139. self.can_shop = True
  140. def _set_irregular_status(self, grace_delay, alert_delay):
  141. counter_unsubscribe = int(self.env['ir.config_parameter'].get_param('irregular_counter_to_unsubscribe', -3))
  142. self.ensure_one()
  143. ok = self.sr >= 0
  144. grace_delay = grace_delay + self.time_extension
  145. if self.sr <= counter_unsubscribe or self.unsubscribed:
  146. self.status = 'unsubscribed'
  147. self.can_shop = False
  148. elif self.today >= self.temporary_exempt_start_date and self.today <= self.temporary_exempt_end_date:
  149. self.status = 'exempted'
  150. self.can_shop = True
  151. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  152. 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):
  153. self.status = 'extension'
  154. self.can_shop = True
  155. 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):
  156. self.status = 'suspended'
  157. self.can_shop = False
  158. elif not ok and self.alert_start_time and self.today > add_days_delta(self.alert_start_time, alert_delay):
  159. self.status = 'suspended'
  160. self.can_shop = False
  161. elif (self.sr < 0) or (not ok and self.alert_start_time):
  162. self.status = 'alert'
  163. self.can_shop = True
  164. #Check for holidays; Can be in holidays even in alert or other mode ?
  165. elif self.today >= self.holiday_start_time and self.today <= self.holiday_end_time:
  166. self.status = 'holiday'
  167. self.can_shop = False
  168. elif ok or (not self.alert_start_time and self.sr >= 0):
  169. self.status = 'ok'
  170. self.can_shop = True
  171. @api.multi
  172. def write(self, vals):
  173. """
  174. Overwrite write to historize the change
  175. """
  176. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time', 'unsubscribed']:
  177. if not field in vals:
  178. continue
  179. for rec in self:
  180. data = {
  181. 'status_id': rec.id,
  182. 'cooperator_id': rec.cooperator_id.id,
  183. 'type': 'counter',
  184. 'user_id': self.env.context.get('real_uid', self.env.uid),
  185. }
  186. if vals.get(field, rec[field]) != rec[field]:
  187. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  188. self.env['cooperative.status.history'].sudo().create(data)
  189. return super(CooperativeStatus, self).write(vals)
  190. def _state_change(self, new_state):
  191. self.ensure_one()
  192. if new_state == 'alert':
  193. self.write({'alert_start_time': self.today, 'extension_start_time': False, 'time_extension': 0})
  194. if new_state == 'ok':
  195. data = {'extension_start_time': False, 'time_extension': 0}
  196. if self.working_mode != 'irregular': # Don't reset alert time for irregular
  197. data['alert_start_time'] = False
  198. self.write(data)
  199. if new_state == 'unsubscribed' or new_state == 'resigning':
  200. self.cooperator_id.sudo().write(
  201. {'subscribed_shift_ids': [(5, 0, 0)]})
  202. # TODO: Add one day otherwise unsubscribed from the shift you were absent
  203. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today(
  204. [self.cooperator_id.id], today=fields.Date.today())
  205. def _change_counter(self, data):
  206. self.sc += data.get('sc', 0)
  207. self.sr += data.get('sr', 0)
  208. self.irregular_absence_counter += data.get('irregular_absence_counter', 0)
  209. self.irregular_absence_date = data.get('irregular_absence_date', False)
  210. @api.multi
  211. def _write(self, vals):
  212. """
  213. Overwrite write to historize the change of status
  214. and make action on status change
  215. """
  216. if 'status' in vals:
  217. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  218. result = self._cr.dictfetchall()
  219. old_status_per_id = {r['id'] : r for r in result}
  220. for rec in self:
  221. if old_status_per_id[rec.id]['status'] != vals['status']:
  222. data = {
  223. 'status_id': rec.id,
  224. 'cooperator_id': rec.cooperator_id.id,
  225. 'type': 'status',
  226. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  227. 'user_id': self.env.context.get('real_uid', self.env.uid),
  228. }
  229. self.env['cooperative.status.history'].sudo().create(data)
  230. rec._state_change(vals['status'])
  231. return super(CooperativeStatus, self)._write(vals)
  232. _sql_constraints = [
  233. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  234. ]
  235. @api.model
  236. def _set_today(self):
  237. """
  238. Method call by the cron to update store value base on the date
  239. """
  240. self.search([]).write({'today': fields.Date.today()})
  241. @api.multi
  242. def clear_history(self):
  243. self.ensure_one()
  244. self.history_ids.unlink()
  245. @api.model
  246. def _cron_compute_counter_irregular(self, today=False):
  247. today = today or fields.Date.today()
  248. journal = self.env['beesdoo.shift.journal'].search([('date', '=', today)])
  249. if not journal:
  250. journal = self.env['beesdoo.shift.journal'].create({'date': today})
  251. domain = ['&',
  252. '&',
  253. '&', ('status', '!=', 'unsubscribed'),
  254. ('working_mode', '=', 'irregular'),
  255. ('irregular_start_date', '!=', False),
  256. '|',
  257. '|', ('holiday_start_time', '=', False), ('holiday_end_time', '=', False),
  258. '|', ('holiday_start_time', '>', today), ('holiday_end_time', '<', today),
  259. ]
  260. irregular = self.search(domain)
  261. today_date = fields.Date.from_string(today)
  262. for status in irregular:
  263. if status.status == 'exempted':
  264. continue
  265. delta = (today_date - fields.Date.from_string(status.irregular_start_date)).days
  266. if delta and delta % PERIOD == 0 and status not in journal.line_ids:
  267. if status.sr > 0:
  268. status.sr -= 1
  269. status.alert_start_time = False
  270. elif status.alert_start_time:
  271. status.sr -= 1
  272. else:
  273. status.sr -= 2
  274. journal.line_ids |= status
  275. class ShiftCronJournal(models.Model):
  276. _name = 'beesdoo.shift.journal'
  277. _order = 'date desc'
  278. _rec_name = 'date'
  279. date = fields.Date()
  280. line_ids = fields.Many2many('cooperative.status')
  281. _sql_constraints = [
  282. ('one_entry_per_day', 'unique (date)', _('You can only create one journal per day')),
  283. ]
  284. @api.multi
  285. def run(self):
  286. self.ensure_one()
  287. if not self.user_has_groups('beesdoo_shift.group_cooperative_admin'):
  288. raise ValidationError(_("You don't have the access to perform this action"))
  289. self.sudo().env['cooperative.status']._cron_compute_counter_irregular(today=self.date)
  290. class ResPartner(models.Model):
  291. _inherit = 'res.partner'
  292. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  293. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  294. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  295. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  296. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  297. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  298. state = fields.Selection(related='cooperative_status_ids.status', readonly=True, store=True)
  299. extension_start_time = fields.Date(related='cooperative_status_ids.extension_start_time', string="Extension Start Day", readonly=True, store=True)
  300. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  301. @api.multi
  302. def coop_subscribe(self):
  303. return {
  304. 'name': _('Subscribe Cooperator'),
  305. 'type': 'ir.actions.act_window',
  306. 'view_type': 'form',
  307. 'view_mode': 'form',
  308. 'res_model': 'beesdoo.shift.subscribe',
  309. 'target': 'new',
  310. }
  311. @api.multi
  312. def coop_unsubscribe(self):
  313. res = self.coop_subscribe()
  314. res['context'] = {'default_unsubscribed': True}
  315. return res
  316. @api.multi
  317. def manual_extension(self):
  318. return {
  319. 'name': _('Manual Extension'),
  320. 'type': 'ir.actions.act_window',
  321. 'view_type': 'form',
  322. 'view_mode': 'form',
  323. 'res_model': 'beesdoo.shift.extension',
  324. 'target': 'new',
  325. }
  326. @api.multi
  327. def auto_extension(self):
  328. res = self.manual_extension()
  329. res['context'] = {'default_auto': True}
  330. res['name'] = _('Trigger Grace Delay')
  331. return res
  332. @api.multi
  333. def register_holiday(self):
  334. return {
  335. 'name': _('Register Holiday'),
  336. 'type': 'ir.actions.act_window',
  337. 'view_type': 'form',
  338. 'view_mode': 'form',
  339. 'res_model': 'beesdoo.shift.holiday',
  340. 'target': 'new',
  341. }
  342. @api.multi
  343. def temporary_exempt(self):
  344. return {
  345. 'name': _('Temporary Exemption'),
  346. 'type': 'ir.actions.act_window',
  347. 'view_type': 'form',
  348. 'view_mode': 'form',
  349. 'res_model': 'beesdoo.shift.temporary_exemption',
  350. 'target': 'new',
  351. }
  352. #TODO access right + vue on res.partner
  353. #TODO can_shop : Status can_shop ou extempted ou part C