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

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
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=lambda x: x._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()
  94. irregular_absence_date = fields.Date()
  95. irregular_absence_counter = fields.Integer()
  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. comodel_name="cooperative.exempt.reason",
  100. string="Temporary Exempt Reason",
  101. )
  102. temporary_exempt_start_date = fields.Date()
  103. temporary_exempt_end_date = fields.Date()
  104. @api.depends("status")
  105. def _compute_can_shop(self):
  106. for rec in self:
  107. rec.can_shop = rec.status in self._can_shop_status()
  108. @api.depends(
  109. "today",
  110. "sr",
  111. "sc",
  112. "holiday_end_time",
  113. "holiday_start_time",
  114. "time_extension",
  115. "alert_start_time",
  116. "extension_start_time",
  117. "unsubscribed",
  118. "irregular_absence_date",
  119. "irregular_absence_counter",
  120. "temporary_exempt_start_date",
  121. "temporary_exempt_end_date",
  122. "resigning",
  123. "cooperator_id.subscribed_shift_ids",
  124. )
  125. def _compute_status(self):
  126. update = int(
  127. self.env["ir.config_parameter"]
  128. .sudo()
  129. .get_param("always_update", False)
  130. )
  131. for rec in self:
  132. if update or not rec.today:
  133. rec.status = "ok"
  134. continue
  135. if rec.resigning:
  136. rec.status = "resigning"
  137. continue
  138. if rec.working_mode == "regular":
  139. rec.status = rec._get_regular_status()
  140. elif rec.working_mode == "irregular":
  141. rec.status = rec._get_irregular_status()
  142. elif rec.working_mode == "exempt":
  143. rec.status = "ok"
  144. _sql_constraints = [
  145. (
  146. "cooperator_uniq",
  147. "unique (cooperator_id)",
  148. _("You can only set one cooperator status per cooperator"),
  149. )
  150. ]
  151. @api.constrains("working_mode", "irregular_start_date")
  152. def _constrains_irregular_start_date(self):
  153. if self.working_mode == "irregular" and not self.irregular_start_date:
  154. raise UserError(
  155. _("Irregular workers must have an irregular start date.")
  156. )
  157. @api.multi
  158. def write(self, vals):
  159. """
  160. Overwrite write to historize the change
  161. """
  162. for field in [
  163. "sr",
  164. "sc",
  165. "time_extension",
  166. "extension_start_time",
  167. "alert_start_time",
  168. "unsubscribed",
  169. ]:
  170. if field not in vals:
  171. continue
  172. for rec in self:
  173. data = {
  174. "status_id": rec.id,
  175. "cooperator_id": rec.cooperator_id.id,
  176. "type": "counter",
  177. "user_id": self.env.context.get("real_uid", self.env.uid),
  178. }
  179. if vals.get(field, rec[field]) != rec[field]:
  180. data["change"] = "{}: {} -> {}".format(
  181. field.upper(), rec[field], vals.get(field)
  182. )
  183. self.env["cooperative.status.history"].sudo().create(data)
  184. return super(CooperativeStatus, self).write(vals)
  185. @api.multi
  186. def _write(self, vals):
  187. """
  188. Overwrite write to historize the change of status
  189. and make action on status change
  190. """
  191. if "status" in vals:
  192. self._cr.execute(
  193. 'select id, status, sr, sc from "%s" where id in %%s'
  194. % self._table,
  195. (self._ids,),
  196. )
  197. result = self._cr.dictfetchall()
  198. old_status_per_id = {r["id"]: r for r in result}
  199. for rec in self:
  200. if old_status_per_id[rec.id]["status"] != vals["status"]:
  201. data = {
  202. "status_id": rec.id,
  203. "cooperator_id": rec.cooperator_id.id,
  204. "type": "status",
  205. "change": "STATUS: %s -> %s"
  206. % (
  207. old_status_per_id[rec.id]["status"],
  208. vals["status"],
  209. ),
  210. "user_id": self.env.context.get(
  211. "real_uid", self.env.uid
  212. ),
  213. }
  214. self.env["cooperative.status.history"].sudo().create(data)
  215. rec._state_change(vals["status"])
  216. return super(CooperativeStatus, self)._write(vals)
  217. def get_status_value(self):
  218. """
  219. Workararound to get translated selection value instead of key in mail
  220. 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)
  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, today):
  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. )