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.

520 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_no = 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. "Annotation", default=""
  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. "Feedback"
  180. )
  181. worker_nb_feedback = fields.Selection(
  182. [
  183. ("not_enough", "Not enough"),
  184. ("enough", "Enough"),
  185. ("too_many", "Too many"),
  186. ],
  187. string="Number of workers.",
  188. )
  189. attended_worker_nb = fields.Integer(
  190. string="Number of attended workers",
  191. default=0,
  192. help="Number of workers who attended the session.",
  193. readonly=True,
  194. )
  195. validated_by = fields.Many2one(
  196. "res.partner",
  197. string="Validated by",
  198. domain=[
  199. ("eater", "=", "worker_eater"),
  200. ("super", "=", True),
  201. ("working_mode", "=", "regular"),
  202. ("state", "not in", ("unsubscribed", "resigning")),
  203. ],
  204. track_visibility="onchange",
  205. readonly=True,
  206. )
  207. _sql_constraints = [
  208. (
  209. "check_no_annotation_mark_read",
  210. "CHECK ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  211. "Non-annotated sheets can't be marked as read. ",
  212. )
  213. ]
  214. @api.constrains(
  215. "expected_shift_ids",
  216. "added_shift_ids",
  217. "annotation",
  218. "feedback",
  219. "worker_nb_feedback",
  220. )
  221. def _lock_after_validation(self):
  222. if self.state == "validated":
  223. raise UserError(
  224. "The sheet has already been validated and can't be edited."
  225. )
  226. @api.multi
  227. def button_mark_as_read(self):
  228. if self.is_read:
  229. raise UserError("The sheet has already been marked as read.")
  230. self.is_read = True
  231. @api.constrains("expected_shift_ids", "added_shift_ids")
  232. def _constrain_unique_worker(self):
  233. # Warning : map return generator in python3 (for Odoo 12)
  234. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  235. expected_ids = map(lambda s: s.worker_id.id, self.expected_shift_ids)
  236. replacement_ids = map(
  237. lambda s: s.replacement_worker_id.id, self.expected_shift_ids
  238. )
  239. replacement_ids = filter(bool, replacement_ids)
  240. ids = added_ids + expected_ids + replacement_ids
  241. if (len(ids) - len(set(ids))) > 0:
  242. raise UserError(
  243. "You can't add the same worker more than once to an attendance sheet."
  244. )
  245. @api.depends("added_shift_ids")
  246. def _compute_added_shift_nb(self):
  247. self.added_worker_nb = len(self.added_shift_ids)
  248. # Compute name (not hardcorded to prevent incoherence with timezone)
  249. @api.depends("start_time", "end_time")
  250. def _compute_name(self):
  251. start_time_dt = fields.Datetime.from_string(self.start_time)
  252. start_time_dt = fields.Datetime.context_timestamp(self, start_time_dt)
  253. end_time_dt = fields.Datetime.from_string(self.end_time)
  254. end_time_dt = fields.Datetime.context_timestamp(self, end_time_dt)
  255. self.name = (
  256. start_time_dt.strftime("%Y-%m-%d")
  257. + " "
  258. + start_time_dt.strftime("%H:%M")
  259. + "-"
  260. + end_time_dt.strftime("%H:%M")
  261. )
  262. # Is this method necessary ?
  263. @api.depends("annotation")
  264. def _compute_is_annotated(self):
  265. if self.annotation:
  266. self.is_annotated = len(self.annotation) != 0
  267. return
  268. @api.model
  269. def create(self, vals):
  270. new_sheet = super(AttendanceSheet, self).create(vals)
  271. # Creation and addition of the expected shifts corresponding
  272. # to the time range
  273. tasks = self.env["beesdoo.shift.shift"]
  274. tasks = tasks.search(
  275. [
  276. ("start_time", "=", new_sheet.start_time),
  277. ("end_time", "=", new_sheet.end_time),
  278. ]
  279. )
  280. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  281. task_templates = set()
  282. for task in tasks:
  283. if task.working_mode == "irregular":
  284. stage = "absent_1"
  285. else:
  286. stage = "absent_2"
  287. if task.worker_id:
  288. new_expected_shift = expected_shift.create(
  289. {
  290. "attendance_sheet_id": new_sheet.id,
  291. "task_id": task.id,
  292. "worker_id": task.worker_id.id,
  293. "replacement_worker_id": task.replaced_id.id,
  294. "task_type_id": task.task_type_id.id,
  295. "stage": stage,
  296. "working_mode": task.working_mode,
  297. }
  298. )
  299. task_templates.add(task.task_template_id)
  300. new_sheet.expected_worker_nb += 1
  301. # Maximum number of workers calculation
  302. new_sheet.max_worker_nb = sum(r.worker_nb for r in task_templates)
  303. return new_sheet
  304. # Workaround to display notifications only for unread and not validated
  305. # sheets, via a check on domain.
  306. @api.model
  307. def _needaction_count(self, domain=None):
  308. if domain == [
  309. ("is_annotated", "=", True),
  310. ("is_read", "=", False),
  311. ] or domain == [("state", "=", "not_validated")]:
  312. return self.search_count(domain)
  313. return
  314. def validate(self):
  315. self.ensure_one()
  316. if self.state == "validated":
  317. raise UserError("The sheet has already been validated.")
  318. shift = self.env["beesdoo.shift.shift"]
  319. stage = self.env["beesdoo.shift.stage"]
  320. # Fields validation
  321. for added_shift in self.added_shift_ids:
  322. if not added_shift.worker_id:
  323. raise UserError(
  324. "Worker must be set for shift %s" % added_shift.id
  325. )
  326. if not added_shift.stage:
  327. raise UserError(
  328. "Shift Stage is missing for %s"
  329. % added_shift.worker_id.name
  330. )
  331. if not added_shift.task_type_id:
  332. raise UserError(
  333. "Task Type is missing for %s" % added_shift.worker_id.name
  334. )
  335. if not added_shift.working_mode:
  336. raise UserError(
  337. "Working mode is missing for %s"
  338. % added_shift.worker_id.name
  339. )
  340. if (
  341. added_shift.worker_id.working_mode == "regular"
  342. and not added_shift.regular_task_type
  343. ):
  344. raise UserError(
  345. "Regular Task Type is missing for %s"
  346. % added_shift.worker_id.name
  347. )
  348. for expected_shift in self.expected_shift_ids:
  349. if not expected_shift.stage:
  350. raise UserError(
  351. "Shift Stage is missing for %s"
  352. % expected_shift.worker_id.name
  353. )
  354. # Expected shifts status update
  355. for expected_shift in self.expected_shift_ids:
  356. actual_shift = expected_shift.task_id
  357. # We get stage record corresponding to mapped stage id
  358. actual_stage = self.env.ref(
  359. "beesdoo_shift.%s" % expected_shift.get_actual_stage()
  360. )
  361. # If the actual stage has been deleted, the sheet is still validated.
  362. # Raising an exception would stop this but would prevent validation.
  363. # How can we show a message without stopping validation ?
  364. if actual_stage:
  365. actual_shift.stage_id = actual_stage
  366. actual_shift.replaced_id = expected_shift.replacement_worker_id
  367. # Added shifts status update
  368. for added_shift in self.added_shift_ids:
  369. actual_stage = self.env.ref(
  370. "beesdoo_shift.%s" % added_shift.get_actual_stage()
  371. )
  372. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  373. is_regular_shift = added_shift.regular_task_type == "normal"
  374. # Add an annotation if a regular worker is doing its regular shift
  375. if is_regular_shift and is_regular_worker:
  376. self.annotation += (
  377. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  378. " Something may be wrong in his/her personnal informations.\n"
  379. % added_shift.worker_id.name
  380. )
  381. # Edit a non-assigned shift or create one if none
  382. non_assigned_shifts = shift.search(
  383. [
  384. ("worker_id", "=", False),
  385. ("start_time", "=", self.start_time),
  386. ("end_time", "=", self.end_time),
  387. ("task_type_id", "=", added_shift.task_type_id.id),
  388. ],
  389. limit=1,
  390. )
  391. if len(non_assigned_shifts):
  392. actual_shift = non_assigned_shifts[0]
  393. actual_shift.write(
  394. {
  395. "stage_id": actual_stage.id,
  396. "worker_id": added_shift.worker_id.id,
  397. "stage_id": actual_stage.id,
  398. "is_regular": is_regular_shift and is_regular_worker,
  399. "is_compensation": not is_regular_shift
  400. and is_regular_worker,
  401. }
  402. )
  403. else:
  404. actual_shift = self.env["beesdoo.shift.shift"].create(
  405. {
  406. "name": "[Added Shift] %s" % self.start_time,
  407. "task_type_id": added_shift.task_type_id.id,
  408. "worker_id": added_shift.worker_id.id,
  409. "start_time": self.start_time,
  410. "end_time": self.end_time,
  411. "stage_id": actual_stage.id,
  412. "is_regular": is_regular_shift and is_regular_worker,
  413. "is_compensation": not is_regular_shift
  414. and is_regular_worker,
  415. }
  416. )
  417. added_shift.task_id = actual_shift.id
  418. self.state = "validated"
  419. return
  420. # @api.multi is needed to call the wizard, but doesn't match @api.one
  421. # from the validate() method
  422. @api.multi
  423. def validate_via_wizard(self):
  424. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  425. self.validated_by = self.env.user.partner_id
  426. self.validate()
  427. return
  428. return {
  429. "type": "ir.actions.act_window",
  430. "res_model": "beesdoo.shift.sheet.validate",
  431. "view_type": "form",
  432. "view_mode": "form",
  433. "target": "new",
  434. }
  435. def on_barcode_scanned(self, barcode):
  436. if self.state == "validated":
  437. raise UserError(
  438. "You cannot modify a validated attendance sheet."
  439. )
  440. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  441. if not len(worker):
  442. raise UserError("Worker not found (invalid barcode or status).")
  443. if len(worker) > 1:
  444. raise UserError("Multiple workers corresponding to barcode.")
  445. if worker.state in ("unsubscribed", "resigning"):
  446. raise UserError("Worker is %s." % worker.state)
  447. if worker.working_mode not in ("regular", "irregular"):
  448. raise UserError("Worker is %s and should be regular or irregular." % worker.working_mode)
  449. for id in self.expected_shift_ids.ids:
  450. shift = self.env["beesdoo.shift.sheet.expected"].browse(id)
  451. if shift.worker_id == worker or shift.replacement_worker_id == worker:
  452. shift.stage = "present"
  453. return
  454. if worker.working_mode == "regular":
  455. regular_task_type = "normal"
  456. else:
  457. regular_task_type = False
  458. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  459. if worker.id in added_ids:
  460. raise UserError("Worker is already present.")
  461. self.added_shift_ids |= self.added_shift_ids.new({
  462. "task_type_id": self.added_shift_ids._default_task_type_id(),
  463. "stage": "present",
  464. "attendance_sheet_id": self._origin.id,
  465. "worker_id": worker.id,
  466. "regular_task_type": regular_task_type
  467. })