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.

211 lines
9.7 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
  5. def add_days_delta(date_from, days_delta):
  6. if not date_from:
  7. return date_from
  8. next_date = fields.Date.from_string(date_from) + timedelta(days=days_delta)
  9. return fields.Date.to_string(next_date)
  10. class ExemptReason(models.Model):
  11. _name = 'cooperative.exempt.reason'
  12. name = fields.Char(required=True)
  13. class HistoryStatus(models.Model):
  14. _name = 'cooperative.status.history'
  15. _order= 'create_date desc'
  16. status_id = fields.Many2one('cooperative.status')
  17. cooperator_id = fields.Many2one('res.partner')
  18. change = fields.Char()
  19. type = fields.Selection([('status', 'Status Change'), ('counter', 'Counter Change')])
  20. user_id = fields.Many2one('res.users', string="User")
  21. class CooperativeStatus(models.Model):
  22. _name = 'cooperative.status'
  23. _rec_name = 'cooperator_id'
  24. today = fields.Date(help="Field that allow to compute field and store them even if they are based on the current date")
  25. cooperator_id = fields.Many2one('res.partner')
  26. info_session = fields.Boolean('Information Session ?')
  27. info_session_date = fields.Datetime('Information Session Date')
  28. super = fields.Boolean("Super Cooperative")
  29. sr = fields.Integer("Compteur shift regulier", default=0)
  30. sc = fields.Integer("Compteur shift de compensation", default=0)
  31. time_holiday = fields.Integer("Holidays Days NB", default=0)
  32. 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")
  33. holiday_start_time = fields.Date("Holidays Start Day")
  34. alert_start_time = fields.Date("Alert Start Day")
  35. extension_start_time = fields.Date("Extension Start Day")
  36. #Champ compute
  37. working_mode = fields.Selection(
  38. [
  39. ('regular', 'Regular worker'),
  40. ('irregular', 'Irregular worker'),
  41. ('exempt', 'Exempted'),
  42. ],
  43. string="Working mode"
  44. )
  45. exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  46. status = fields.Selection([('ok', 'Up to Date'),
  47. ('holiday', 'Holidays'),
  48. ('alert', 'Alerte'),
  49. ('extension', 'Extension'),
  50. ('suspended', 'Suspended'),
  51. ('unsubscribed', 'Unsubscribed')],
  52. compute="_compute_status", string="Cooperative Status", store=True)
  53. can_shop = fields.Boolean(compute='_compute_status', store=True)
  54. history_ids = fields.One2many('cooperative.status.history', 'status_id', readonly=True)
  55. unsubscribed = fields.Boolean(default=False, help="Manually unsubscribed")
  56. @api.depends('today', 'sr', 'sc', 'time_holiday', 'holiday_start_time', 'time_extension', 'alert_start_time', 'extension_start_time', 'unsubscribed')
  57. def _compute_status(self):
  58. alert_delay = int(self.env['ir.config_parameter'].get_param('alert_delay', 28))
  59. grace_delay = int(self.env['ir.config_parameter'].get_param('default_grace_delay', 10))
  60. update = int(self.env['ir.config_parameter'].get_param('always_update', False))
  61. print update
  62. for rec in self:
  63. if update:
  64. rec.status = 'ok'
  65. rec.can_shop = True
  66. continue
  67. ok = rec.sr >= 0 and rec.sc >= 0
  68. grace_delay = grace_delay + rec.time_extension
  69. if rec.sr < -1 or rec.unsubscribed:
  70. rec.status = 'unsubscribed'
  71. rec.can_shop = False
  72. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  73. elif not ok and rec.alert_start_time and rec.extension_start_time and rec.today <= add_days_delta(rec.extension_start_time, grace_delay):
  74. rec.status = 'extension'
  75. rec.can_shop = True
  76. elif not ok and rec.alert_start_time and rec.extension_start_time and rec.today > add_days_delta(rec.extension_start_time, grace_delay):
  77. rec.status = 'suspended'
  78. rec.can_shop = False
  79. elif not ok and rec.alert_start_time and rec.today > add_days_delta(rec.alert_start_time, alert_delay):
  80. rec.status = 'suspended'
  81. rec.can_shop = False
  82. elif (rec.sr < 0) or (not ok and rec.alert_start_time):
  83. rec.status = 'alert'
  84. rec.can_shop = True
  85. #Check for holidays; Can be in holidays even in alert or other mode ?
  86. elif rec.today >= rec.holiday_start_time and rec.today < add_days_delta(rec.holiday_start_time, rec.time_holiday):
  87. rec.status = 'holiday'
  88. rec.can_shop = True
  89. elif ok or (not rec.alert_start_time and rec.sr >= 0):
  90. rec.status = 'ok'
  91. rec.can_shop = True
  92. @api.multi
  93. def write(self, vals):
  94. """
  95. Overwrite write to historize the change
  96. """
  97. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time', 'unsubscribed']:
  98. if not field in vals:
  99. continue
  100. for rec in self:
  101. data = {
  102. 'status_id': rec.id,
  103. 'cooperator_id': rec.cooperator_id.id,
  104. 'type': 'counter',
  105. 'user_id': self.env.context.get('real_uid', self.env.uid),
  106. }
  107. if vals.get(field, rec[field]) != rec[field]:
  108. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  109. self.env['cooperative.status.history'].sudo().create(data)
  110. return super(CooperativeStatus, self).write(vals)
  111. def _state_change(self, new_state, old_stage):
  112. self.ensure_one()
  113. if new_state == 'alert':
  114. self.write({'alert_start_time': self.today, 'extension_start_time': False, 'time_extension': 0})
  115. if new_state == 'ok': #reset alert start time if back to ok
  116. self.write({'alert_start_time': False, 'extension_start_time': False, 'time_extension': 0})
  117. if new_state == 'unsubscribed':
  118. self.cooperator_id.sudo().write({'subscribed_shift_ids' : [(5,0,0)]})
  119. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today([self.cooperator_id.id], today=self.today)
  120. @api.multi
  121. def _write(self, vals):
  122. """
  123. Overwrite write to historize the change of status
  124. and make action on status change
  125. """
  126. if 'status' in vals:
  127. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  128. result = self._cr.dictfetchall()
  129. old_status_per_id = {r['id'] : r for r in result}
  130. for rec in self:
  131. if old_status_per_id[rec.id]['status'] != vals['status']:
  132. data = {
  133. 'status_id': rec.id,
  134. 'cooperator_id': rec.cooperator_id.id,
  135. 'type': 'status',
  136. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  137. 'user_id': self.env.context.get('real_uid', self.env.uid),
  138. }
  139. self.env['cooperative.status.history'].sudo().create(data)
  140. rec._state_change(vals['status'], old_status_per_id[rec.id]['status'])
  141. return super(CooperativeStatus, self)._write(vals)
  142. _sql_constraints = [
  143. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  144. ]
  145. @api.model
  146. def _set_today(self):
  147. """
  148. Method call by the cron to update store value base on the date
  149. """
  150. self.search([]).write({'today': fields.Date.today()})
  151. @api.multi
  152. def clear_history(self):
  153. self.ensure_one()
  154. self.history_ids.unlink()
  155. class ResPartner(models.Model):
  156. _inherit = 'res.partner'
  157. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  158. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  159. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  160. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  161. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  162. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  163. state = fields.Selection(related='cooperative_status_ids.status', readonly=True, store=True)
  164. extension_start_time = fields.Date(related='cooperative_status_ids.extension_start_time', string="Extension Start Day", readonly=True, store=True)
  165. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  166. @api.multi
  167. def coop_subscribe(self):
  168. return {
  169. 'name': _('Subscribe Cooperator'),
  170. 'type': 'ir.actions.act_window',
  171. 'view_type': 'form',
  172. 'view_mode': 'form',
  173. 'res_model': 'beesdoo.shift.subscribe',
  174. 'target': 'new',
  175. }
  176. @api.multi
  177. def coop_unsubscribe(self):
  178. res = self.coop_subscribe()
  179. res['context'] = {'default_unsubscribed': True}
  180. return res
  181. #TODO access right + vue on res.partner
  182. #TODO can_shop : Status can_shop ou extempted ou part C