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.

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