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.

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