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.

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