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.

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