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.

318 lines
12 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. from odoo import models, fields, api, _
  2. from odoo.exceptions import ValidationError, UserError
  3. from datetime import timedelta, datetime
  4. import logging
  5. _logger = logging.getLogger(__name__)
  6. def add_days_delta(date_from, days_delta):
  7. if not date_from:
  8. return date_from
  9. next_date = date_from + timedelta(days=days_delta)
  10. return next_date
  11. class ExemptReason(models.Model):
  12. _name = 'cooperative.exempt.reason'
  13. _description = 'cooperative.exempt.reason'
  14. name = fields.Char(required=True)
  15. class HistoryStatus(models.Model):
  16. _name = 'cooperative.status.history'
  17. _description = '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. _description = 'cooperative.status'
  27. _rec_name = 'cooperator_id'
  28. _order = 'cooperator_id'
  29. _period = 28
  30. def _get_status(self):
  31. return [
  32. ('ok', 'Up to Date'),
  33. ('holiday', 'Holidays'),
  34. ('alert', 'Alerte'),
  35. ('extension', 'Extension'),
  36. ('suspended', 'Suspended'),
  37. ('exempted', 'Exempted'),
  38. ('unsubscribed', 'Unsubscribed'),
  39. ('resigning', 'Resigning')
  40. ]
  41. 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)
  42. cooperator_id = fields.Many2one('res.partner')
  43. active = fields.Boolean(related="cooperator_id.active", store=True, index=True)
  44. info_session = fields.Boolean('Information Session ?')
  45. info_session_date = fields.Date('Information Session Date')
  46. super = fields.Boolean("Super Cooperative")
  47. sr = fields.Integer("Regular shifts counter", default=0)
  48. sc = fields.Integer("Compensation shifts counter", default=0)
  49. 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")
  50. holiday_start_time = fields.Date("Holidays Start Day")
  51. holiday_end_time = fields.Date("Holidays End Day")
  52. alert_start_time = fields.Date("Alert Start Day")
  53. extension_start_time = fields.Date("Extension Start Day")
  54. working_mode = fields.Selection(
  55. [
  56. ('regular', 'Regular worker'),
  57. ('irregular', 'Irregular worker'),
  58. ('exempt', 'Exempted'),
  59. ],
  60. string="Working mode"
  61. )
  62. exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  63. status = fields.Selection(selection=_get_status,
  64. compute="_compute_status", string="Cooperative Status", store=True)
  65. can_shop = fields.Boolean(compute='_compute_can_shop', store=True)
  66. history_ids = fields.One2many('cooperative.status.history', 'status_id', readonly=True)
  67. unsubscribed = fields.Boolean(default=False, help="Manually unsubscribed")
  68. resigning = fields.Boolean(default=False, help="Want to leave the beescoop")
  69. #Specific to irregular
  70. irregular_start_date = fields.Date() #TODO migration script
  71. irregular_absence_date = fields.Date()
  72. irregular_absence_counter = fields.Integer() #TODO unsubscribe when reach -2
  73. future_alert_date = fields.Date(compute='_compute_future_alert_date')
  74. next_countdown_date = fields.Date(compute='_compute_next_countdown_date')
  75. temporary_exempt_reason_id = fields.Many2one('cooperative.exempt.reason', 'Exempt Reason')
  76. temporary_exempt_start_date = fields.Date()
  77. temporary_exempt_end_date = fields.Date()
  78. @api.depends('status')
  79. def _compute_can_shop(self):
  80. for rec in self:
  81. rec.can_shop = rec.status in self._can_shop_status()
  82. @api.depends('today', 'sr', 'sc', 'holiday_end_time',
  83. 'holiday_start_time', 'time_extension',
  84. 'alert_start_time', 'extension_start_time',
  85. 'unsubscribed', 'irregular_absence_date',
  86. 'irregular_absence_counter', 'temporary_exempt_start_date',
  87. 'temporary_exempt_end_date', 'resigning', 'cooperator_id.subscribed_shift_ids')
  88. def _compute_status(self):
  89. update = int(self.env['ir.config_parameter'].sudo().get_param('always_update', False))
  90. for rec in self:
  91. if update or not rec.today:
  92. rec.status = 'ok'
  93. continue
  94. if rec.resigning:
  95. rec.status = 'resigning'
  96. continue
  97. if rec.working_mode == 'regular':
  98. rec.status = rec._get_regular_status()
  99. elif rec.working_mode == 'irregular':
  100. rec.status = rec._get_irregular_status()
  101. elif rec.working_mode == 'exempt':
  102. rec.status = 'ok'
  103. _sql_constraints = [
  104. ('cooperator_uniq', 'unique (cooperator_id)', _('You can only set one cooperator status per cooperator')),
  105. ]
  106. @api.constrains("working_mode", "irregular_start_date")
  107. def _constrains_irregular_start_date(self):
  108. if self.working_mode == "irregular" and not self.irregular_start_date:
  109. raise UserError(_("Irregular workers must have an irregular start date."))
  110. @api.multi
  111. def write(self, vals):
  112. """
  113. Overwrite write to historize the change
  114. """
  115. for field in ['sr', 'sc', 'time_extension', 'extension_start_time', 'alert_start_time', 'unsubscribed']:
  116. if not field in vals:
  117. continue
  118. for rec in self:
  119. data = {
  120. 'status_id': rec.id,
  121. 'cooperator_id': rec.cooperator_id.id,
  122. 'type': 'counter',
  123. 'user_id': self.env.context.get('real_uid', self.env.uid),
  124. }
  125. if vals.get(field, rec[field]) != rec[field]:
  126. data['change'] = '%s: %s -> %s' % (field.upper(), rec[field], vals.get(field))
  127. self.env['cooperative.status.history'].sudo().create(data)
  128. return super(CooperativeStatus, self).write(vals)
  129. @api.multi
  130. def _write(self, vals):
  131. """
  132. Overwrite write to historize the change of status
  133. and make action on status change
  134. """
  135. if 'status' in vals:
  136. self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
  137. result = self._cr.dictfetchall()
  138. old_status_per_id = {r['id'] : r for r in result}
  139. for rec in self:
  140. if old_status_per_id[rec.id]['status'] != vals['status']:
  141. data = {
  142. 'status_id': rec.id,
  143. 'cooperator_id': rec.cooperator_id.id,
  144. 'type': 'status',
  145. 'change': "STATUS: %s -> %s" % (old_status_per_id[rec.id]['status'], vals['status']),
  146. 'user_id': self.env.context.get('real_uid', self.env.uid),
  147. }
  148. self.env['cooperative.status.history'].sudo().create(data)
  149. rec._state_change(vals['status'])
  150. return super(CooperativeStatus, self)._write(vals)
  151. def get_status_value(self):
  152. """
  153. Workararound to get translated selection value instead of key in mail template.
  154. """
  155. state_list = self.env["cooperative.status"]._fields['status']._description_selection(self.env)
  156. return dict(state_list)[self.status]
  157. @api.model
  158. def _set_today(self):
  159. """
  160. Method call by the cron to update store value base on the date
  161. """
  162. self.search([]).write({'today': fields.Date.today()})
  163. @api.model
  164. def _cron_compute_counter_irregular(self, today=False):
  165. """
  166. Journal ensure that a irregular worker will be only check
  167. once per day
  168. """
  169. today = today or fields.Date.today()
  170. journal = self.env['beesdoo.shift.journal'].search([('date', '=', today)])
  171. if not journal:
  172. journal = self.env['beesdoo.shift.journal'].create({'date': today})
  173. domain = self._get_irregular_worker_domain(today=today)
  174. irregular = self.search(domain)
  175. for status in irregular:
  176. delta = (today - status.irregular_start_date).days
  177. if delta and delta % self._period == 0 and status not in journal.line_ids:
  178. status._change_irregular_counter()
  179. journal.line_ids |= status
  180. @api.multi
  181. def clear_history(self):
  182. self.ensure_one()
  183. self.history_ids.unlink()
  184. ########################################################
  185. # Method to override #
  186. # To define the behavior of the status #
  187. # #
  188. # By default: everyone is always up to date #
  189. ########################################################
  190. ##############################
  191. # Computed field section #
  192. ##############################
  193. @api.depends('today')
  194. def _compute_future_alert_date(self):
  195. """
  196. Compute date until the worker is up to date
  197. for irregular worker
  198. """
  199. for rec in self:
  200. rec.future_alert_date = False
  201. @api.depends('today')
  202. def _compute_next_countdown_date(self):
  203. """
  204. Compute the following countdown date. This date is the date when
  205. the worker will see his counter changed due to the cron. This
  206. date is like the birthday date of the worker that occurred each
  207. _period.
  208. """
  209. for rec in self:
  210. rec.next_countdown_date = False
  211. def _can_shop_status(self):
  212. """
  213. return the list of status that give access
  214. to active cooperator privilege
  215. """
  216. return ['ok', 'alert', 'extension', 'exempted']
  217. #####################################
  218. # Status Change implementation #
  219. #####################################
  220. def _get_regular_status(self):
  221. """
  222. Return the value of the status
  223. for the regular worker
  224. """
  225. return 'ok'
  226. def _get_irregular_status(self):
  227. """
  228. Return the value of the status
  229. for the irregular worker
  230. """
  231. return 'ok'
  232. def _state_change(self, new_state):
  233. """
  234. Hook to watch change in the state
  235. """
  236. pass
  237. def _change_counter(self, data):
  238. """
  239. Call when a shift state is changed
  240. use data generated by _get_counter_date_state_change
  241. """
  242. pass
  243. ###############################################
  244. ###### Irregular Cron implementation ##########
  245. ###############################################
  246. def _get_irregular_worker_domain(self):
  247. """
  248. return the domain the give the list
  249. of valid irregular worker that should
  250. get their counter changed by the cron
  251. """
  252. return [(0, '=', 1)]
  253. def _change_irregular_counter(self):
  254. """
  255. Define how the counter will change
  256. for the irregular worker
  257. where today - start_date is a multiple of the period
  258. by default 28 days
  259. """
  260. pass
  261. class ShiftCronJournal(models.Model):
  262. _name = 'beesdoo.shift.journal'
  263. _description = 'beesdoo.shift.journal'
  264. _order = 'date desc'
  265. _rec_name = 'date'
  266. date = fields.Date()
  267. line_ids = fields.Many2many('cooperative.status')
  268. _sql_constraints = [
  269. ('one_entry_per_day', 'unique (date)', _('You can only create one journal per day')),
  270. ]
  271. @api.multi
  272. def run(self):
  273. self.ensure_one()
  274. if not self.user_has_groups('beesdoo_shift.group_cooperative_admin'):
  275. raise ValidationError(_("You don't have the access to perform this action"))
  276. self.sudo().env['cooperative.status']._cron_compute_counter_irregular(today=self.date)