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.

476 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. from lxml import etree
  3. from openerp import models, exceptions, fields, api
  4. from openerp.exceptions import UserError, ValidationError
  5. from datetime import datetime
  6. from lxml import etree
  7. class AttendanceSheetShift(models.Model):
  8. _name = "beesdoo.shift.sheet.shift"
  9. _description = "Copy of an actual shift into an attendance sheet"
  10. @api.model
  11. def _default_task_type_id(self):
  12. parameters = self.env["ir.config_parameter"]
  13. id = int(parameters.get_param("beesdoo_shift.default_task_type_id"))
  14. task_types = self.env["beesdoo.shift.type"]
  15. return task_types.browse(id)
  16. # Related actual shift, not required because doesn't exist for added shift before validation
  17. # To update after validation
  18. task_id = fields.Many2one("beesdoo.shift.shift", string="Task")
  19. attendance_sheet_id = fields.Many2one(
  20. "beesdoo.shift.sheet",
  21. string="Attendance Sheet",
  22. required=True,
  23. ondelete="cascade",
  24. )
  25. stage = fields.Selection(
  26. [
  27. ("present", "Present"),
  28. ("absent", "Absent"),
  29. ("cancelled", "Cancelled"),
  30. ],
  31. string="Shift Stage",
  32. copy=False,
  33. )
  34. worker_id = fields.Many2one(
  35. "res.partner",
  36. string="Worker",
  37. domain=[
  38. ("eater", "=", "worker_eater"),
  39. ("working_mode", "in", ("regular", "irregular")),
  40. ("state", "not in", ("unsubscribed", "resigning")),
  41. ],
  42. required=True,
  43. )
  44. task_type_id = fields.Many2one(
  45. "beesdoo.shift.type", string="Task Type", default=_default_task_type_id
  46. )
  47. working_mode = fields.Selection(
  48. related="worker_id.working_mode", string="Working Mode", store=True
  49. )
  50. def get_actual_stage(self):
  51. """
  52. Mapping function returning the actual id
  53. of corresponding beesdoo.shift.stage
  54. This behavior should be temporary
  55. (increases lack of understanding).
  56. """
  57. if not self.working_mode or not self.stage:
  58. raise UserError(
  59. "Impossible to map task status, all values are not set."
  60. )
  61. if self.working_mode == "regular":
  62. if self.stage == "present":
  63. return "done"
  64. if self.stage == "absent" and self.compensation_nb:
  65. if self.compensation_nb == "0":
  66. return "excused_necessity"
  67. if self.compensation_nb == "1":
  68. return "excused"
  69. if self.compensation_nb == "2":
  70. return "absent"
  71. if self.stage == "cancelled":
  72. return "cancel"
  73. if self.working_mode == "irregular":
  74. if self.stage == "present":
  75. return "done"
  76. if self.stage == "cancelled":
  77. return "cancel"
  78. return "absent"
  79. class AttendanceSheetShiftExpected(models.Model):
  80. _name = "beesdoo.shift.sheet.expected"
  81. _description = "Expected Shift"
  82. _inherit = ["beesdoo.shift.sheet.shift"]
  83. compensation_nb = fields.Selection(
  84. [("0", "0"), ("1", "1"), ("2", "2")],
  85. string="Compensations (if absent)",
  86. )
  87. replacement_worker_id = fields.Many2one(
  88. "res.partner",
  89. string="Replacement Worker",
  90. domain=[
  91. ("eater", "=", "worker_eater"),
  92. ("working_mode", "=", "regular"),
  93. ("state", "not in", ("unsubscribed", "resigning")),
  94. ],
  95. )
  96. # The webclient has display issues with this method.
  97. @api.onchange("stage")
  98. def on_change_stage(self):
  99. if self.working_mode == "irregular":
  100. if self.stage == "present" or "cancelled":
  101. self.compensation_nb = False
  102. if self.stage == "absent":
  103. self.compensation_nb = "1"
  104. if self.working_mode == "regular":
  105. if self.stage == "present" or "cancelled":
  106. self.compensation_nb = False
  107. if self.stage == "absent":
  108. self.compensation_nb = "2"
  109. class AttendanceSheetShiftAdded(models.Model):
  110. """The added shifts stage must be Present
  111. (add an SQL constraint ?)
  112. """
  113. _name = "beesdoo.shift.sheet.added"
  114. _description = "Added Shift"
  115. _inherit = ["beesdoo.shift.sheet.shift"]
  116. # Change the previously determined two booleans for a more comprehensive field
  117. regular_task_type = fields.Selection(
  118. [("normal", "Normal"), ("compensation", "Compensation")],
  119. string="Task Mode (if regular)",
  120. help="Shift type for regular workers. ",
  121. )
  122. @api.model
  123. def create(self, vals):
  124. vals["stage"] = "present"
  125. return super(AttendanceSheetShiftAdded, self).create(vals)
  126. @api.onchange("working_mode")
  127. def on_change_working_mode(self):
  128. self.stage = "present"
  129. if self.working_mode == "regular":
  130. self.regular_task_type = "compensation"
  131. if self.working_mode == "irregular":
  132. self.regular_task_type = False
  133. class AttendanceSheet(models.Model):
  134. _name = "beesdoo.shift.sheet"
  135. _inherit = ["mail.thread", "ir.needaction_mixin"]
  136. _description = "Attendance sheets with all the shifts in one time range."
  137. _order = "start_time"
  138. name = fields.Char(
  139. string="Name", compute="_compute_name", store=True, readonly=True
  140. )
  141. state = fields.Selection(
  142. [
  143. ("not_validated", "Not Validated"),
  144. ("validated", "Validated"),
  145. ("cancelled", "Cancelled"),
  146. ],
  147. string="Status",
  148. readonly=True,
  149. index=True,
  150. copy=False,
  151. default="not_validated",
  152. track_visibility="onchange",
  153. )
  154. start_time = fields.Datetime(
  155. string="Start Time", required=True, readonly=True
  156. )
  157. end_time = fields.Datetime(string="End Time", required=True, readonly=True)
  158. expected_shift_ids = fields.One2many(
  159. "beesdoo.shift.sheet.expected",
  160. "attendance_sheet_id",
  161. string="Expected Shifts",
  162. )
  163. added_shift_ids = fields.One2many(
  164. "beesdoo.shift.sheet.added",
  165. "attendance_sheet_id",
  166. string="Added Shifts",
  167. )
  168. max_worker_nb = fields.Integer(
  169. string="Maximum number of workers",
  170. default=0,
  171. readonly=True,
  172. help="Indicative maximum number of workers for the shifts.",
  173. )
  174. expected_worker_nb = fields.Integer(
  175. string="Number of expected workers", readonly=True, default=0
  176. )
  177. added_worker_nb = fields.Integer(
  178. compute="_compute_added_shift_nb",
  179. string="Number of added workers",
  180. readonly=True,
  181. default=0,
  182. )
  183. annotation = fields.Text(
  184. "Attendance Sheet annotation", default="", track_visibility="onchange"
  185. )
  186. is_annotated = fields.Boolean(
  187. compute="_compute_is_annotated",
  188. string="Annotation",
  189. readonly=True,
  190. store=True,
  191. )
  192. is_read = fields.Boolean(
  193. string="Mark as read",
  194. help="Has annotation been read by an administrator ?",
  195. default=False,
  196. track_visibility="onchange",
  197. )
  198. feedback = fields.Text(
  199. "Attendance Sheet feedback", track_visibility="onchange"
  200. )
  201. worker_nb_feedback = fields.Selection(
  202. [
  203. ("not_enough", "Not enough"),
  204. ("enough", "Enough"),
  205. ("too much", "Too much"),
  206. ],
  207. string="Feedback regarding the number of workers.",
  208. track_visibility="onchange",
  209. )
  210. attended_worker_nb = fields.Integer(
  211. string="Number of attended workers",
  212. default=0,
  213. help="Number of workers who attended the session.",
  214. readonly=True,
  215. )
  216. validated_by = fields.Many2one(
  217. "res.partner",
  218. string="Validated by",
  219. domain=[
  220. ("eater", "=", "worker_eater"),
  221. ("super", "=", True),
  222. ("working_mode", "=", "regular"),
  223. ("state", "not in", ("unsubscribed", "resigning")),
  224. ],
  225. track_visibility="onchange",
  226. readonly=True,
  227. )
  228. _sql_constraints = [
  229. (
  230. "check_no_annotation_mark_read",
  231. "CHECK ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  232. "Non-annotated sheets can't be marked as read. ",
  233. )
  234. ]
  235. @api.constrains(
  236. "expected_shift_ids",
  237. "added_shift_ids",
  238. "annotation",
  239. "feedback",
  240. "worker_nb_feedback",
  241. )
  242. def _lock_after_validation(self):
  243. if self.state == "validated":
  244. raise UserError(
  245. "The sheet has already been validated and can't be edited."
  246. )
  247. @api.constrains("expected_shift_ids", "added_shift_ids")
  248. def _constrain_unique_worker(self):
  249. added_workers = set(self.added_shift_ids.mapped("worker_id").ids)
  250. expected_workers = self.expected_shift_ids.mapped("worker_id").ids
  251. replacement_workers = self.expected_shift_ids.mapped(
  252. "replacement_worker_id"
  253. ).ids
  254. if len(
  255. added_workers.intersection(replacement_workers + expected_workers)
  256. ):
  257. raise UserError("You can't add an already expected worker.")
  258. @api.depends("added_shift_ids")
  259. def _compute_added_shift_nb(self):
  260. self.added_worker_nb = len(self.added_shift_ids)
  261. return
  262. # Compute name (not hardcorded to prevent incoherence with timezone)
  263. # Actually not working, should depends on timezone as well
  264. @api.depends("start_time", "end_time")
  265. def _compute_name(self):
  266. start_time_dt = fields.Datetime.from_string(self.start_time)
  267. start_time_dt = fields.Datetime.context_timestamp(self, start_time_dt)
  268. end_time_dt = fields.Datetime.from_string(self.end_time)
  269. end_time_dt = fields.Datetime.context_timestamp(self, end_time_dt)
  270. self.name = (
  271. start_time_dt.strftime("%Y-%m-%d")
  272. + " "
  273. + start_time_dt.strftime("%H:%M")
  274. + " - "
  275. + end_time_dt.strftime("%H:%M")
  276. )
  277. return
  278. # Is this method necessary ?
  279. @api.depends("annotation")
  280. def _compute_is_annotated(self):
  281. if self.annotation:
  282. self.is_annotated = len(self.annotation) != 0
  283. return
  284. @api.model
  285. def create(self, vals):
  286. new_sheet = super(AttendanceSheet, self).create(vals)
  287. # Creation and addition of the expected shifts corresponding
  288. # to the time range
  289. tasks = self.env["beesdoo.shift.shift"]
  290. tasks = tasks.search(
  291. [
  292. ("start_time", "=", new_sheet.start_time),
  293. ("end_time", "=", new_sheet.end_time),
  294. ]
  295. )
  296. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  297. task_templates = set()
  298. for task in tasks:
  299. if task.working_mode == "irregular":
  300. compensation_nb = "1"
  301. else:
  302. compensation_nb = "2"
  303. new_expected_shift = expected_shift.create(
  304. {
  305. "attendance_sheet_id": new_sheet.id,
  306. "task_id": task.id,
  307. "worker_id": task.worker_id.id,
  308. "replacement_worker_id": task.replaced_id.id,
  309. "task_type_id": task.task_type_id.id,
  310. "stage": "absent",
  311. "compensation_nb": compensation_nb,
  312. "working_mode": task.working_mode,
  313. }
  314. )
  315. task_templates.add(task.task_template_id)
  316. new_sheet.expected_worker_nb += 1
  317. # Maximum number of workers calculation
  318. for task_template in task_templates:
  319. new_sheet.max_worker_nb += task_template.worker_nb
  320. return new_sheet
  321. # Workaround to display notifications only for unread and not validated
  322. # sheets, via a check on domain.
  323. @api.model
  324. def _needaction_count(self, domain=None):
  325. if domain == [
  326. ("is_annotated", "=", True),
  327. ("is_read", "=", False),
  328. ] or domain == [("state", "=", "not_validated")]:
  329. return self.search_count(domain)
  330. return
  331. @api.one
  332. def validate(self):
  333. self.ensure_one()
  334. if self.state == "validated":
  335. raise UserError("The sheet has already been validated.")
  336. shift = self.env["beesdoo.shift.shift"]
  337. stage = self.env["beesdoo.shift.stage"]
  338. # Fields validation
  339. for added_shift in self.added_shift_ids:
  340. if (
  341. not added_shift.stage
  342. or not added_shift.worker_id
  343. or not added_shift.task_type_id
  344. or not added_shift.working_mode
  345. or (
  346. added_shift.worker_id.working_mode == "regular"
  347. and not added_shift.regular_task_type
  348. )
  349. ):
  350. raise UserError("All fields must be set before validation.")
  351. # Expected shifts status update
  352. for expected_shift in self.expected_shift_ids:
  353. actual_shift = expected_shift.task_id
  354. actual_stage = stage.search(
  355. [("code", "=", expected_shift.get_actual_stage())]
  356. )
  357. # If the actual stage has been deleted, the sheet is still validated.
  358. # Raising an exception would stop this.
  359. # How can we show a message without stopping validation ?
  360. if actual_stage:
  361. actual_shift.stage_id = actual_stage
  362. actual_shift.replaced_id = expected_shift.replacement_worker_id
  363. # Added shifts status update
  364. for added_shift in self.added_shift_ids:
  365. actual_stage = stage.search(
  366. [("code", "=", added_shift.get_actual_stage())]
  367. )
  368. # WARNING: mapping the selection field to the booleans used in Task
  369. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  370. is_regular_shift = added_shift.regular_task_type == "normal"
  371. # Add an annotation if a regular worker is doing its regular shift
  372. if is_regular_shift and is_regular_worker:
  373. self.annotation += (
  374. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  375. " Something may be wrong in his/her personnal informations.\n"
  376. % added_shift.worker_id.name
  377. )
  378. # Edit a non-assigned shift or create one if none
  379. non_assigned_shifts = shift.search(
  380. [
  381. ("worker_id", "=", False),
  382. ("start_time", "=", self.start_time),
  383. ("end_time", "=", self.end_time),
  384. ("task_type_id", "=", added_shift.task_type_id.id),
  385. ]
  386. )
  387. if len(non_assigned_shifts):
  388. actual_shift = non_assigned_shifts[0]
  389. actual_shift.write(
  390. {
  391. "stage_id": actual_stage.id,
  392. "worker_id": added_shift.worker_id.id,
  393. "stage_id": actual_stage.id,
  394. "is_regular": is_regular_shift and is_regular_worker,
  395. "is_compensation": not is_regular_shift
  396. and is_regular_worker,
  397. }
  398. )
  399. else:
  400. actual_shift = self.env["beesdoo.shift.shift"].create(
  401. {
  402. "name": "Added shift TEST %s" % self.start_time,
  403. "task_type_id": added_shift.task_type_id.id,
  404. "worker_id": added_shift.worker_id.id,
  405. "start_time": self.start_time,
  406. "end_time": self.end_time,
  407. "stage_id": actual_stage.id,
  408. "is_regular": is_regular_shift and is_regular_worker,
  409. "is_compensation": not is_regular_shift
  410. and is_regular_worker,
  411. }
  412. )
  413. added_shift.task_id = actual_shift.id
  414. self.state = "validated"
  415. return
  416. # @api.multi is needed to call the wizard, but doesn't match @api.one
  417. # from the validate() method
  418. @api.multi
  419. def validate_via_wizard(self):
  420. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  421. self.validated_by = self.env.user.partner_id
  422. self.validate()
  423. return
  424. return {
  425. "type": "ir.actions.act_window",
  426. "res_model": "beesdoo.shift.sheet.validate",
  427. "view_type": "form",
  428. "view_mode": "form",
  429. "target": "new",
  430. }