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.

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