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.

409 lines
13 KiB

4 years ago
4 years ago
4 years ago
7 years ago
4 years ago
7 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. import logging
  2. from datetime import timedelta
  3. from odoo import _, api, fields, models
  4. from odoo.exceptions import UserError, ValidationError
  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(
  23. [("status", "Status Change"), ("counter", "Counter Change")]
  24. )
  25. user_id = fields.Many2one("res.users", string="User")
  26. class CooperativeStatus(models.Model):
  27. _name = "cooperative.status"
  28. _description = "cooperative.status"
  29. _rec_name = "cooperator_id"
  30. _order = "cooperator_id"
  31. _period = 28
  32. def _get_status(self):
  33. return [
  34. ("ok", "Up to Date"),
  35. ("holiday", "Holidays"),
  36. ("alert", "Alerte"),
  37. ("extension", "Extension"),
  38. ("suspended", "Suspended"),
  39. ("exempted", "Exempted"),
  40. ("unsubscribed", "Unsubscribed"),
  41. ("resigning", "Resigning"),
  42. ]
  43. today = fields.Date(
  44. help="Field that allow to compute field and store them even if they "
  45. "are based on the current date",
  46. default=fields.Date.today,
  47. )
  48. cooperator_id = fields.Many2one("res.partner")
  49. active = fields.Boolean(
  50. related="cooperator_id.active", store=True, index=True
  51. )
  52. info_session = fields.Boolean("Information Session ?")
  53. info_session_date = fields.Date("Information Session Date")
  54. super = fields.Boolean("Super Cooperative")
  55. sr = fields.Integer("Regular shifts counter", default=0)
  56. sc = fields.Integer("Compensation shifts counter", default=0)
  57. time_extension = fields.Integer(
  58. "Extension Days NB",
  59. default=0,
  60. help="Addtional days to the automatic extension, 5 mean that you have "
  61. "a total of 15 extension days of default one is set to 10",
  62. )
  63. holiday_start_time = fields.Date("Holidays Start Day")
  64. holiday_end_time = fields.Date("Holidays End Day")
  65. alert_start_time = fields.Date("Alert Start Day")
  66. extension_start_time = fields.Date("Extension Start Day")
  67. working_mode = fields.Selection(
  68. [
  69. ("regular", "Regular worker"),
  70. ("irregular", "Irregular worker"),
  71. ("exempt", "Exempted"),
  72. ],
  73. string="Working mode",
  74. )
  75. exempt_reason_id = fields.Many2one(
  76. comodel_name="cooperative.exempt.reason", string="Exempt Reason"
  77. )
  78. status = fields.Selection(
  79. selection=_get_status,
  80. compute="_compute_status",
  81. string="Cooperative Status",
  82. store=True,
  83. )
  84. can_shop = fields.Boolean(compute="_compute_can_shop", store=True)
  85. history_ids = fields.One2many(
  86. "cooperative.status.history", "status_id", readonly=True
  87. )
  88. unsubscribed = fields.Boolean(default=False, help="Manually unsubscribed")
  89. resigning = fields.Boolean(
  90. default=False, help="Want to leave the beescoop"
  91. )
  92. # Specific to irregular
  93. irregular_start_date = fields.Date() # TODO migration script
  94. irregular_absence_date = fields.Date()
  95. irregular_absence_counter = (
  96. fields.Integer()
  97. ) # TODO unsubscribe when reach -2
  98. future_alert_date = fields.Date(compute="_compute_future_alert_date")
  99. next_countdown_date = fields.Date(compute="_compute_next_countdown_date")
  100. temporary_exempt_reason_id = fields.Many2one(
  101. comodel_name="cooperative.exempt.reason",
  102. string="Temporary Exempt Reason",
  103. )
  104. temporary_exempt_start_date = fields.Date()
  105. temporary_exempt_end_date = fields.Date()
  106. @api.depends("status")
  107. def _compute_can_shop(self):
  108. for rec in self:
  109. rec.can_shop = rec.status in self._can_shop_status()
  110. @api.depends(
  111. "today",
  112. "sr",
  113. "sc",
  114. "holiday_end_time",
  115. "holiday_start_time",
  116. "time_extension",
  117. "alert_start_time",
  118. "extension_start_time",
  119. "unsubscribed",
  120. "irregular_absence_date",
  121. "irregular_absence_counter",
  122. "temporary_exempt_start_date",
  123. "temporary_exempt_end_date",
  124. "resigning",
  125. "cooperator_id.subscribed_shift_ids",
  126. )
  127. def _compute_status(self):
  128. update = int(
  129. self.env["ir.config_parameter"]
  130. .sudo()
  131. .get_param("always_update", False)
  132. )
  133. for rec in self:
  134. if update or not rec.today:
  135. rec.status = "ok"
  136. continue
  137. if rec.resigning:
  138. rec.status = "resigning"
  139. continue
  140. if rec.working_mode == "regular":
  141. rec.status = rec._get_regular_status()
  142. elif rec.working_mode == "irregular":
  143. rec.status = rec._get_irregular_status()
  144. elif rec.working_mode == "exempt":
  145. rec.status = "ok"
  146. _sql_constraints = [
  147. (
  148. "cooperator_uniq",
  149. "unique (cooperator_id)",
  150. _("You can only set one cooperator status per cooperator"),
  151. )
  152. ]
  153. @api.constrains("working_mode", "irregular_start_date")
  154. def _constrains_irregular_start_date(self):
  155. if self.working_mode == "irregular" and not self.irregular_start_date:
  156. raise UserError(
  157. _("Irregular workers must have an irregular start date.")
  158. )
  159. @api.multi
  160. def write(self, vals):
  161. """
  162. Overwrite write to historize the change
  163. """
  164. for field in [
  165. "sr",
  166. "sc",
  167. "time_extension",
  168. "extension_start_time",
  169. "alert_start_time",
  170. "unsubscribed",
  171. ]:
  172. if field not in vals:
  173. continue
  174. for rec in self:
  175. data = {
  176. "status_id": rec.id,
  177. "cooperator_id": rec.cooperator_id.id,
  178. "type": "counter",
  179. "user_id": self.env.context.get("real_uid", self.env.uid),
  180. }
  181. if vals.get(field, rec[field]) != rec[field]:
  182. data["change"] = "{}: {} -> {}".format(
  183. field.upper(), rec[field], vals.get(field)
  184. )
  185. self.env["cooperative.status.history"].sudo().create(data)
  186. return super(CooperativeStatus, self).write(vals)
  187. @api.multi
  188. def _write(self, vals):
  189. """
  190. Overwrite write to historize the change of status
  191. and make action on status change
  192. """
  193. if "status" in vals:
  194. self._cr.execute(
  195. 'select id, status, sr, sc from "%s" where id in %%s'
  196. % self._table,
  197. (self._ids,),
  198. )
  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"
  208. % (
  209. old_status_per_id[rec.id]["status"],
  210. vals["status"],
  211. ),
  212. "user_id": self.env.context.get(
  213. "real_uid", self.env.uid
  214. ),
  215. }
  216. self.env["cooperative.status.history"].sudo().create(data)
  217. rec._state_change(vals["status"])
  218. return super(CooperativeStatus, self)._write(vals)
  219. def get_status_value(self):
  220. """
  221. Workararound to get translated selection value instead of key in mail
  222. template.
  223. """
  224. state_list = (
  225. self.env["cooperative.status"]
  226. ._fields["status"]
  227. ._description_selection(self.env)
  228. )
  229. return dict(state_list)[self.status]
  230. @api.model
  231. def _set_today(self):
  232. """
  233. Method call by the cron to update store value base on the date
  234. """
  235. self.search([]).write({"today": fields.Date.today()})
  236. @api.model
  237. def _cron_compute_counter_irregular(self, today=False):
  238. """
  239. Journal ensure that a irregular worker will be only check
  240. once per day
  241. """
  242. today = today or fields.Date.today()
  243. journal = self.env["beesdoo.shift.journal"].search(
  244. [("date", "=", today)]
  245. )
  246. if not journal:
  247. journal = self.env["beesdoo.shift.journal"].create({"date": today})
  248. domain = self._get_irregular_worker_domain(today=today)
  249. irregular = self.search(domain)
  250. for status in irregular:
  251. delta = (today - status.irregular_start_date).days
  252. if (
  253. delta
  254. and delta % self._period == 0
  255. and status not in journal.line_ids
  256. ):
  257. status._change_irregular_counter()
  258. journal.line_ids |= status
  259. @api.multi
  260. def clear_history(self):
  261. self.ensure_one()
  262. self.history_ids.unlink()
  263. ########################################################
  264. # Method to override #
  265. # To define the behavior of the status #
  266. # #
  267. # By default: everyone is always up to date #
  268. ########################################################
  269. ##############################
  270. # Computed field section #
  271. ##############################
  272. @api.depends("today")
  273. def _compute_future_alert_date(self):
  274. """
  275. Compute date until the worker is up to date
  276. for irregular worker
  277. """
  278. for rec in self:
  279. rec.future_alert_date = False
  280. @api.depends("today")
  281. def _compute_next_countdown_date(self):
  282. """
  283. Compute the following countdown date. This date is the date when
  284. the worker will see his counter changed due to the cron. This
  285. date is like the birthday date of the worker that occurred each
  286. _period.
  287. """
  288. for rec in self:
  289. rec.next_countdown_date = False
  290. def _can_shop_status(self):
  291. """
  292. return the list of status that give access
  293. to active cooperator privilege
  294. """
  295. return ["ok", "alert", "extension", "exempted"]
  296. #####################################
  297. # Status Change implementation #
  298. #####################################
  299. def _get_regular_status(self):
  300. """
  301. Return the value of the status
  302. for the regular worker
  303. """
  304. return "ok"
  305. def _get_irregular_status(self):
  306. """
  307. Return the value of the status
  308. for the irregular worker
  309. """
  310. return "ok"
  311. def _state_change(self, new_state):
  312. """
  313. Hook to watch change in the state
  314. """
  315. pass
  316. def _change_counter(self, data):
  317. """
  318. Call when a shift state is changed
  319. use data generated by _get_counter_date_state_change
  320. """
  321. pass
  322. ###############################################
  323. # Irregular Cron implementation #
  324. ###############################################
  325. def _get_irregular_worker_domain(self):
  326. """
  327. return the domain the give the list
  328. of valid irregular worker that should
  329. get their counter changed by the cron
  330. """
  331. return [(0, "=", 1)]
  332. def _change_irregular_counter(self):
  333. """
  334. Define how the counter will change
  335. for the irregular worker
  336. where today - start_date is a multiple of the period
  337. by default 28 days
  338. """
  339. pass
  340. class ShiftCronJournal(models.Model):
  341. _name = "beesdoo.shift.journal"
  342. _description = "beesdoo.shift.journal"
  343. _order = "date desc"
  344. _rec_name = "date"
  345. date = fields.Date()
  346. line_ids = fields.Many2many("cooperative.status")
  347. _sql_constraints = [
  348. (
  349. "one_entry_per_day",
  350. "unique (date)",
  351. _("You can only create one journal per day"),
  352. )
  353. ]
  354. @api.multi
  355. def run(self):
  356. self.ensure_one()
  357. if not self.user_has_groups("beesdoo_shift.group_cooperative_admin"):
  358. raise ValidationError(
  359. _("You don't have the access to perform this action")
  360. )
  361. self.sudo().env["cooperative.status"]._cron_compute_counter_irregular(
  362. today=self.date
  363. )