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.

408 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
5 years ago
5 years ago
5 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. "cooperative.exempt.reason", "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. "cooperative.exempt.reason", "Exempt Reason"
  102. )
  103. temporary_exempt_start_date = fields.Date()
  104. temporary_exempt_end_date = fields.Date()
  105. @api.depends("status")
  106. def _compute_can_shop(self):
  107. for rec in self:
  108. rec.can_shop = rec.status in self._can_shop_status()
  109. @api.depends(
  110. "today",
  111. "sr",
  112. "sc",
  113. "holiday_end_time",
  114. "holiday_start_time",
  115. "time_extension",
  116. "alert_start_time",
  117. "extension_start_time",
  118. "unsubscribed",
  119. "irregular_absence_date",
  120. "irregular_absence_counter",
  121. "temporary_exempt_start_date",
  122. "temporary_exempt_end_date",
  123. "resigning",
  124. "cooperator_id.subscribed_shift_ids",
  125. )
  126. def _compute_status(self):
  127. update = int(
  128. self.env["ir.config_parameter"]
  129. .sudo()
  130. .get_param("always_update", False)
  131. )
  132. for rec in self:
  133. if update or not rec.today:
  134. rec.status = "ok"
  135. continue
  136. if rec.resigning:
  137. rec.status = "resigning"
  138. continue
  139. if rec.working_mode == "regular":
  140. rec.status = rec._get_regular_status()
  141. elif rec.working_mode == "irregular":
  142. rec.status = rec._get_irregular_status()
  143. elif rec.working_mode == "exempt":
  144. rec.status = "ok"
  145. _sql_constraints = [
  146. (
  147. "cooperator_uniq",
  148. "unique (cooperator_id)",
  149. _("You can only set one cooperator status per cooperator"),
  150. )
  151. ]
  152. @api.constrains("working_mode", "irregular_start_date")
  153. def _constrains_irregular_start_date(self):
  154. if self.working_mode == "irregular" and not self.irregular_start_date:
  155. raise UserError(
  156. _("Irregular workers must have an irregular start date.")
  157. )
  158. @api.multi
  159. def write(self, vals):
  160. """
  161. Overwrite write to historize the change
  162. """
  163. for field in [
  164. "sr",
  165. "sc",
  166. "time_extension",
  167. "extension_start_time",
  168. "alert_start_time",
  169. "unsubscribed",
  170. ]:
  171. if field not in vals:
  172. continue
  173. for rec in self:
  174. data = {
  175. "status_id": rec.id,
  176. "cooperator_id": rec.cooperator_id.id,
  177. "type": "counter",
  178. "user_id": self.env.context.get("real_uid", self.env.uid),
  179. }
  180. if vals.get(field, rec[field]) != rec[field]:
  181. data["change"] = "{}: {} -> {}".format(
  182. field.upper(), rec[field], 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
  221. template.
  222. """
  223. state_list = (
  224. self.env["cooperative.status"]
  225. ._fields["status"]
  226. ._description_selection(self.env)
  227. )
  228. return dict(state_list)[self.status]
  229. @api.model
  230. def _set_today(self):
  231. """
  232. Method call by the cron to update store value base on the date
  233. """
  234. self.search([]).write({"today": fields.Date.today()})
  235. @api.model
  236. def _cron_compute_counter_irregular(self, today=False):
  237. """
  238. Journal ensure that a irregular worker will be only check
  239. once per day
  240. """
  241. today = today or fields.Date.today()
  242. journal = self.env["beesdoo.shift.journal"].search(
  243. [("date", "=", today)]
  244. )
  245. if not journal:
  246. journal = self.env["beesdoo.shift.journal"].create({"date": today})
  247. domain = self._get_irregular_worker_domain(today=today)
  248. irregular = self.search(domain)
  249. for status in irregular:
  250. delta = (today - status.irregular_start_date).days
  251. if (
  252. delta
  253. and delta % self._period == 0
  254. and status not in journal.line_ids
  255. ):
  256. status._change_irregular_counter()
  257. journal.line_ids |= status
  258. @api.multi
  259. def clear_history(self):
  260. self.ensure_one()
  261. self.history_ids.unlink()
  262. ########################################################
  263. # Method to override #
  264. # To define the behavior of the status #
  265. # #
  266. # By default: everyone is always up to date #
  267. ########################################################
  268. ##############################
  269. # Computed field section #
  270. ##############################
  271. @api.depends("today")
  272. def _compute_future_alert_date(self):
  273. """
  274. Compute date until the worker is up to date
  275. for irregular worker
  276. """
  277. for rec in self:
  278. rec.future_alert_date = False
  279. @api.depends("today")
  280. def _compute_next_countdown_date(self):
  281. """
  282. Compute the following countdown date. This date is the date when
  283. the worker will see his counter changed due to the cron. This
  284. date is like the birthday date of the worker that occurred each
  285. _period.
  286. """
  287. for rec in self:
  288. rec.next_countdown_date = False
  289. def _can_shop_status(self):
  290. """
  291. return the list of status that give access
  292. to active cooperator privilege
  293. """
  294. return ["ok", "alert", "extension", "exempted"]
  295. #####################################
  296. # Status Change implementation #
  297. #####################################
  298. def _get_regular_status(self):
  299. """
  300. Return the value of the status
  301. for the regular worker
  302. """
  303. return "ok"
  304. def _get_irregular_status(self):
  305. """
  306. Return the value of the status
  307. for the irregular worker
  308. """
  309. return "ok"
  310. def _state_change(self, new_state):
  311. """
  312. Hook to watch change in the state
  313. """
  314. pass
  315. def _change_counter(self, data):
  316. """
  317. Call when a shift state is changed
  318. use data generated by _get_counter_date_state_change
  319. """
  320. pass
  321. ###############################################
  322. # Irregular Cron implementation #
  323. ###############################################
  324. def _get_irregular_worker_domain(self):
  325. """
  326. return the domain the give the list
  327. of valid irregular worker that should
  328. get their counter changed by the cron
  329. """
  330. return [(0, "=", 1)]
  331. def _change_irregular_counter(self):
  332. """
  333. Define how the counter will change
  334. for the irregular worker
  335. where today - start_date is a multiple of the period
  336. by default 28 days
  337. """
  338. pass
  339. class ShiftCronJournal(models.Model):
  340. _name = "beesdoo.shift.journal"
  341. _description = "beesdoo.shift.journal"
  342. _order = "date desc"
  343. _rec_name = "date"
  344. date = fields.Date()
  345. line_ids = fields.Many2many("cooperative.status")
  346. _sql_constraints = [
  347. (
  348. "one_entry_per_day",
  349. "unique (date)",
  350. _("You can only create one journal per day"),
  351. )
  352. ]
  353. @api.multi
  354. def run(self):
  355. self.ensure_one()
  356. if not self.user_has_groups("beesdoo_shift.group_cooperative_admin"):
  357. raise ValidationError(
  358. _("You don't have the access to perform this action")
  359. )
  360. self.sudo().env["cooperative.status"]._cron_compute_counter_irregular(
  361. today=self.date
  362. )