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.

193 lines
8.9 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', 'Suspended (auto ext)'),
  50. ('extension_current', 'In extension'),
  51. ('suspended', 'Suspended'),
  52. ('unsubscribed', 'Unsubscribed')],
  53. compute="_compute_status", string="Cooperative Status", store=True)
  54. can_shop = fields.Boolean(compute='_compute_status', store=True)
  55. history_ids = fields.One2many('cooperative.status.history', 'status_id', readonly=True)
  56. @api.depends('today', 'sr', 'sc', 'time_holiday', 'holiday_start_time', 'time_extension', 'alert_start_time', 'extension_start_time')
  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. for rec in self:
  61. ok = rec.sr >= 0 and rec.sc >= 0
  62. grace_delay = grace_delay + rec.time_extension
  63. if rec.sr < -1: #un subscribed
  64. rec.status = 'unsubscribed'
  65. rec.can_shop = False
  66. #Transition to alert sr < 0 or stay in alert sr < 0 or sc < 0 and thus alert time is defined
  67. 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):
  68. rec.status = 'extension_current'
  69. rec.can_shop = True
  70. 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):
  71. rec.status = 'suspended'
  72. rec.can_shop = False
  73. elif not ok and rec.alert_start_time and rec.today > add_days_delta(rec.alert_start_time, alert_delay):
  74. rec.status = 'extension'
  75. rec.can_shop = False
  76. elif (rec.sr < 0) or (not ok and rec.alert_start_time):
  77. rec.status = 'alert'
  78. rec.can_shop = True
  79. #Check for holidays; Can be in holidays even in alert or other mode ?
  80. elif rec.today >= rec.holiday_start_time and rec.today < add_days_delta(rec.holiday_start_time, rec.time_holiday):
  81. rec.status = 'holiday'
  82. rec.can_shop = True
  83. elif ok or (not rec.alert_start_time and rec.sr >= 0):
  84. rec.status = 'ok'
  85. rec.can_shop = True
  86. @api.multi
  87. def write(self, vals):
  88. """
  89. Overwrite write to historize the change
  90. """
  91. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time']:
  92. if not field in vals:
  93. continue
  94. for rec in self:
  95. data = {
  96. 'status_id': rec.id,
  97. 'cooperator_id': rec.cooperator_id.id,
  98. 'type': 'counter',
  99. 'user_id': self.env.context.get('real_uid', self.env.uid),
  100. }
  101. if vals.get(field, rec[field]) != rec[field]:
  102. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  103. self.env['cooperative.status.history'].sudo().create(data)
  104. return super(CooperativeStatus, self).write(vals)
  105. def _state_change(self, new_state, old_stage):
  106. if new_state == 'alert':
  107. self.write({'alert_start_time': self.today, 'extension_start_time': False, 'time_extension': 0})
  108. if new_state == 'ok': #reset alert start time if back to ok
  109. self.write({'alert_start_time': False, 'extension_start_time': False, 'time_extension': 0})
  110. if new_state == 'unsubscribed':
  111. self.cooperator_id.sudo().write({'subscribed_shift_ids' : [(5,0,0)]})
  112. self.env['beesdoo.shift.shift'].sudo().unsubscribe_from_today([self.cooperator_id.id], today=self.today)
  113. @api.multi
  114. def _write(self, vals):
  115. """
  116. Overwrite write to historize the change of status
  117. and make action on status change
  118. """
  119. if 'status' in vals:
  120. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  121. result = self._cr.dictfetchall()
  122. old_status_per_id = {r['id'] : r for r in result}
  123. for rec in self:
  124. if old_status_per_id[rec.id]['status'] != vals['status']:
  125. data = {
  126. 'status_id': rec.id,
  127. 'cooperator_id': rec.cooperator_id.id,
  128. 'type': 'status',
  129. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  130. 'user_id': self.env.context.get('real_uid', self.env.uid),
  131. }
  132. self.env['cooperative.status.history'].sudo().create(data)
  133. rec._state_change(vals['status'], old_status_per_id[rec.id]['status'])
  134. return super(CooperativeStatus, self)._write(vals)
  135. _sql_constraints = [
  136. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  137. ]
  138. @api.model
  139. def _set_today(self):
  140. """
  141. Method call by the cron to update store value base on the date
  142. """
  143. self.search([]).write({'today': fields.Date.today()})
  144. @api.multi
  145. def clear_history(self):
  146. self.ensure_one()
  147. self.history_ids.unlink()
  148. class ResPartner(models.Model):
  149. _inherit = 'res.partner'
  150. cooperative_status_ids = fields.One2many('cooperative.status', 'cooperator_id', readonly=True)
  151. super = fields.Boolean(related='cooperative_status_ids.super', string="Super Cooperative", readonly=True, store=True)
  152. info_session = fields.Boolean(related='cooperative_status_ids.info_session', string='Information Session ?', readonly=True, store=True)
  153. info_session_date = fields.Datetime(related='cooperative_status_ids.info_session_date', string='Information Session Date', readonly=True, store=True)
  154. working_mode = fields.Selection(related='cooperative_status_ids.working_mode', readonly=True, store=True)
  155. exempt_reason_id = fields.Many2one(related='cooperative_status_ids.exempt_reason_id', readonly=True, store=True)
  156. subscribed_shift_ids = fields.Many2many('beesdoo.shift.template')
  157. @api.multi
  158. def coop_subscribe(self):
  159. return {
  160. 'name': _('Subscribe Cooperator'),
  161. 'type': 'ir.actions.act_window',
  162. 'view_type': 'form',
  163. 'view_mode': 'form',
  164. 'res_model': 'beesdoo.shift.subscribe',
  165. 'target': 'new',
  166. }
  167. #TODO access right + vue on res.partner