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.

407 lines
13 KiB

5 years ago
5 years ago
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. import logging
  2. from datetime import datetime, 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(),
  181. rec[field],
  182. vals.get(field),
  183. )
  184. self.env["cooperative.status.history"].sudo().create(data)
  185. return super(CooperativeStatus, self).write(vals)
  186. @api.multi
  187. def _write(self, vals):
  188. """
  189. Overwrite write to historize the change of status
  190. and make action on status change
  191. """
  192. if "status" in vals:
  193. self._cr.execute(
  194. 'select id, status, sr, sc from "%s" where id in %%s'
  195. % self._table,
  196. (self._ids,),
  197. )
  198. result = self._cr.dictfetchall()
  199. old_status_per_id = {r["id"]: r for r in result}
  200. for rec in self:
  201. if old_status_per_id[rec.id]["status"] != vals["status"]:
  202. data = {
  203. "status_id": rec.id,
  204. "cooperator_id": rec.cooperator_id.id,
  205. "type": "status",
  206. "change": "STATUS: %s -> %s"
  207. % (
  208. old_status_per_id[rec.id]["status"],
  209. vals["status"],
  210. ),
  211. "user_id": self.env.context.get(
  212. "real_uid", self.env.uid
  213. ),
  214. }
  215. self.env["cooperative.status.history"].sudo().create(data)
  216. rec._state_change(vals["status"])
  217. return super(CooperativeStatus, self)._write(vals)
  218. def get_status_value(self):
  219. """
  220. Workararound to get translated selection value instead of key in mail template.
  221. """
  222. state_list = (
  223. self.env["cooperative.status"]
  224. ._fields["status"]
  225. ._description_selection(self.env)
  226. )
  227. return dict(state_list)[self.status]
  228. @api.model
  229. def _set_today(self):
  230. """
  231. Method call by the cron to update store value base on the date
  232. """
  233. self.search([]).write({"today": fields.Date.today()})
  234. @api.model
  235. def _cron_compute_counter_irregular(self, today=False):
  236. """
  237. Journal ensure that a irregular worker will be only check
  238. once per day
  239. """
  240. today = today or fields.Date.today()
  241. journal = self.env["beesdoo.shift.journal"].search(
  242. [("date", "=", today)]
  243. )
  244. if not journal:
  245. journal = self.env["beesdoo.shift.journal"].create({"date": today})
  246. domain = self._get_irregular_worker_domain(today=today)
  247. irregular = self.search(domain)
  248. for status in irregular:
  249. delta = (today - status.irregular_start_date).days
  250. if (
  251. delta
  252. and delta % self._period == 0
  253. and status not in journal.line_ids
  254. ):
  255. status._change_irregular_counter()
  256. journal.line_ids |= status
  257. @api.multi
  258. def clear_history(self):
  259. self.ensure_one()
  260. self.history_ids.unlink()
  261. ########################################################
  262. # Method to override #
  263. # To define the behavior of the status #
  264. # #
  265. # By default: everyone is always up to date #
  266. ########################################################
  267. ##############################
  268. # Computed field section #
  269. ##############################
  270. @api.depends("today")
  271. def _compute_future_alert_date(self):
  272. """
  273. Compute date until the worker is up to date
  274. for irregular worker
  275. """
  276. for rec in self:
  277. rec.future_alert_date = False
  278. @api.depends("today")
  279. def _compute_next_countdown_date(self):
  280. """
  281. Compute the following countdown date. This date is the date when
  282. the worker will see his counter changed due to the cron. This
  283. date is like the birthday date of the worker that occurred each
  284. _period.
  285. """
  286. for rec in self:
  287. rec.next_countdown_date = False
  288. def _can_shop_status(self):
  289. """
  290. return the list of status that give access
  291. to active cooperator privilege
  292. """
  293. return ["ok", "alert", "extension", "exempted"]
  294. #####################################
  295. # Status Change implementation #
  296. #####################################
  297. def _get_regular_status(self):
  298. """
  299. Return the value of the status
  300. for the regular worker
  301. """
  302. return "ok"
  303. def _get_irregular_status(self):
  304. """
  305. Return the value of the status
  306. for the irregular worker
  307. """
  308. return "ok"
  309. def _state_change(self, new_state):
  310. """
  311. Hook to watch change in the state
  312. """
  313. pass
  314. def _change_counter(self, data):
  315. """
  316. Call when a shift state is changed
  317. use data generated by _get_counter_date_state_change
  318. """
  319. pass
  320. ###############################################
  321. ###### Irregular Cron implementation ##########
  322. ###############################################
  323. def _get_irregular_worker_domain(self):
  324. """
  325. return the domain the give the list
  326. of valid irregular worker that should
  327. get their counter changed by the cron
  328. """
  329. return [(0, "=", 1)]
  330. def _change_irregular_counter(self):
  331. """
  332. Define how the counter will change
  333. for the irregular worker
  334. where today - start_date is a multiple of the period
  335. by default 28 days
  336. """
  337. pass
  338. class ShiftCronJournal(models.Model):
  339. _name = "beesdoo.shift.journal"
  340. _description = "beesdoo.shift.journal"
  341. _order = "date desc"
  342. _rec_name = "date"
  343. date = fields.Date()
  344. line_ids = fields.Many2many("cooperative.status")
  345. _sql_constraints = [
  346. (
  347. "one_entry_per_day",
  348. "unique (date)",
  349. _("You can only create one journal per day"),
  350. )
  351. ]
  352. @api.multi
  353. def run(self):
  354. self.ensure_one()
  355. if not self.user_has_groups("beesdoo_shift.group_cooperative_admin"):
  356. raise ValidationError(
  357. _("You don't have the access to perform this action")
  358. )
  359. self.sudo().env["cooperative.status"]._cron_compute_counter_irregular(
  360. today=self.date
  361. )