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.

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