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.

390 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 or not self.cooperator_id.subscribed_shift_ids:
  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, old_stage):
  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': #reset alert start time if back to ok
  195. self.write({'alert_start_time': False, 'extension_start_time': False, 'time_extension': 0})
  196. if new_state == 'unsubscribed':
  197. self.cooperator_id.sudo().write({'subscribed_shift_ids' : [(5,0,0)]})
  198. #TODO: Add one day othertwise unsubscribed from the shift you were absent
  199. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today([self.cooperator_id.id], today=self.today)
  200. def _change_counter(self, data):
  201. self.sc += data.get('sc', 0)
  202. self.sr += data.get('sr', 0)
  203. self.irregular_absence_counter += data.get('irregular_absence_counter', 0)
  204. self.irregular_absence_date = data.get('irregular_absence_date', False)
  205. @api.multi
  206. def _write(self, vals):
  207. """
  208. Overwrite write to historize the change of status
  209. and make action on status change
  210. """
  211. if 'status' in vals:
  212. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  213. result = self._cr.dictfetchall()
  214. old_status_per_id = {r['id'] : r for r in result}
  215. for rec in self:
  216. if old_status_per_id[rec.id]['status'] != vals['status']:
  217. data = {
  218. 'status_id': rec.id,
  219. 'cooperator_id': rec.cooperator_id.id,
  220. 'type': 'status',
  221. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  222. 'user_id': self.env.context.get('real_uid', self.env.uid),
  223. }
  224. self.env['cooperative.status.history'].sudo().create(data)
  225. rec._state_change(vals['status'], old_status_per_id[rec.id]['status'])
  226. return super(CooperativeStatus, self)._write(vals)
  227. _sql_constraints = [
  228. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  229. ]
  230. @api.model
  231. def _set_today(self):
  232. """
  233. Method call by the cron to update store value base on the date
  234. """
  235. self.search([]).write({'today': fields.Date.today()})
  236. @api.multi
  237. def clear_history(self):
  238. self.ensure_one()
  239. self.history_ids.unlink()
  240. @api.model
  241. def _cron_compute_counter_irregular(self, today=False):
  242. today = today or fields.Date.today()
  243. journal = self.env['beesdoo.shift.journal'].search([('date', '=', today)])
  244. if not journal:
  245. journal = self.env['beesdoo.shift.journal'].create({'date': today})
  246. domain = ['&',
  247. '&',
  248. '&', ('status', '!=', 'unsubscribed'),
  249. ('working_mode', '=', 'irregular'),
  250. ('irregular_start_date', '!=', False),
  251. '|',
  252. '|', ('holiday_start_time', '=', False), ('holiday_end_time', '=', False),
  253. '|', ('holiday_start_time', '>', today), ('holiday_end_time', '<', today),
  254. ]
  255. irregular = self.search(domain)
  256. today_date = fields.Date.from_string(today)
  257. for status in irregular:
  258. if status.status == 'exempted':
  259. continue
  260. delta = (today_date - fields.Date.from_string(status.irregular_start_date)).days
  261. if delta and delta % PERIOD == 0 and status not in journal.line_ids:
  262. if status.sr > 0:
  263. status.sr -= 1
  264. else:
  265. status.sr -= 2
  266. journal.line_ids |= status
  267. class ShiftCronJournal(models.Model):
  268. _name = 'beesdoo.shift.journal'
  269. _order = 'date desc'
  270. _rec_name = 'date'
  271. date = fields.Date()
  272. line_ids = fields.Many2many('cooperative.status')
  273. _sql_constraints = [
  274. ('one_entry_per_day', 'unique (date)', _('You can only create one journal per day')),
  275. ]
  276. @api.multi
  277. def run(self):
  278. self.ensure_one()
  279. if not self.user_has_groups('beesdoo_shift.group_cooperative_admin'):
  280. raise ValidationError(_("You don't have the access to perform this action"))
  281. self.sudo().env['cooperative.status']._cron_compute_counter_irregular(today=self.date)
  282. class ResPartner(models.Model):
  283. _inherit = 'res.partner'
  284. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  285. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  286. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  287. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  288. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  289. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  290. state = fields.Selection(related='cooperative_status_ids.status', readonly=True, store=True)
  291. extension_start_time = fields.Date(related='cooperative_status_ids.extension_start_time', string="Extension Start Day", readonly=True, store=True)
  292. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  293. @api.multi
  294. def coop_subscribe(self):
  295. return {
  296. 'name': _('Subscribe Cooperator'),
  297. 'type': 'ir.actions.act_window',
  298. 'view_type': 'form',
  299. 'view_mode': 'form',
  300. 'res_model': 'beesdoo.shift.subscribe',
  301. 'target': 'new',
  302. }
  303. @api.multi
  304. def coop_unsubscribe(self):
  305. res = self.coop_subscribe()
  306. res['context'] = {'default_unsubscribed': True}
  307. return res
  308. @api.multi
  309. def manual_extension(self):
  310. return {
  311. 'name': _('Manual Extension'),
  312. 'type': 'ir.actions.act_window',
  313. 'view_type': 'form',
  314. 'view_mode': 'form',
  315. 'res_model': 'beesdoo.shift.extension',
  316. 'target': 'new',
  317. }
  318. @api.multi
  319. def auto_extension(self):
  320. res = self.manual_extension()
  321. res['context'] = {'default_auto': True}
  322. res['name'] = _('Trigger Grace Delay')
  323. return res
  324. @api.multi
  325. def register_holiday(self):
  326. return {
  327. 'name': _('Register Holiday'),
  328. 'type': 'ir.actions.act_window',
  329. 'view_type': 'form',
  330. 'view_mode': 'form',
  331. 'res_model': 'beesdoo.shift.holiday',
  332. 'target': 'new',
  333. }
  334. @api.multi
  335. def temporary_exempt(self):
  336. return {
  337. 'name': _('Temporary Exemption'),
  338. 'type': 'ir.actions.act_window',
  339. 'view_type': 'form',
  340. 'view_mode': 'form',
  341. 'res_model': 'beesdoo.shift.temporary_exemption',
  342. 'target': 'new',
  343. }
  344. #TODO access right + vue on res.partner
  345. #TODO can_shop : Status can_shop ou extempted ou part C