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.

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