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.

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