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.

504 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. annotation = fields.Text(
  155. "Annotation", default=""
  156. )
  157. is_annotated = fields.Boolean(
  158. compute="_compute_is_annotated",
  159. string="Annotation",
  160. readonly=True,
  161. store=True,
  162. )
  163. is_read = fields.Boolean(
  164. string="Mark as read",
  165. help="Has annotation been read by an administrator ?",
  166. default=False,
  167. track_visibility="onchange",
  168. )
  169. feedback = fields.Text(
  170. "Feedback"
  171. )
  172. worker_nb_feedback = fields.Selection(
  173. [
  174. ("not_enough", "Not enough"),
  175. ("enough", "Enough"),
  176. ("too_many", "Too many"),
  177. ],
  178. string="Number of workers.",
  179. )
  180. attended_worker_nb = fields.Integer(
  181. string="Number of attended workers",
  182. default=0,
  183. help="Number of workers who attended the session.",
  184. readonly=True,
  185. )
  186. validated_by = fields.Many2one(
  187. "res.partner",
  188. string="Validated by",
  189. domain=[
  190. ("eater", "=", "worker_eater"),
  191. ("super", "=", True),
  192. ("working_mode", "=", "regular"),
  193. ("state", "not in", ("unsubscribed", "resigning")),
  194. ],
  195. track_visibility="onchange",
  196. readonly=True,
  197. )
  198. _sql_constraints = [
  199. (
  200. "check_no_annotation_mark_read",
  201. "CHECK ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  202. "Non-annotated sheets can't be marked as read. ",
  203. )
  204. ]
  205. @api.constrains(
  206. "expected_shift_ids",
  207. "added_shift_ids",
  208. "annotation",
  209. "feedback",
  210. "worker_nb_feedback",
  211. )
  212. def _lock_after_validation(self):
  213. if self.state == "validated":
  214. raise UserError(
  215. "The sheet has already been validated and can't be edited."
  216. )
  217. @api.multi
  218. def button_mark_as_read(self):
  219. if self.is_read:
  220. raise UserError("The sheet has already been marked as read.")
  221. self.is_read = True
  222. @api.constrains("expected_shift_ids", "added_shift_ids")
  223. def _constrain_unique_worker(self):
  224. # Warning : map return generator in python3 (for Odoo 12)
  225. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  226. expected_ids = map(lambda s: s.worker_id.id, self.expected_shift_ids)
  227. replacement_ids = map(
  228. lambda s: s.replacement_worker_id.id, self.expected_shift_ids
  229. )
  230. replacement_ids = filter(bool, replacement_ids)
  231. ids = added_ids + expected_ids + replacement_ids
  232. if (len(ids) - len(set(ids))) > 0:
  233. raise UserError(
  234. "You can't add the same worker more than once to an attendance sheet."
  235. )
  236. # Compute name (not hardcorded to prevent incoherence with timezone)
  237. @api.depends("start_time", "end_time")
  238. def _compute_name(self):
  239. start_time_dt = fields.Datetime.from_string(self.start_time)
  240. start_time_dt = fields.Datetime.context_timestamp(self, start_time_dt)
  241. end_time_dt = fields.Datetime.from_string(self.end_time)
  242. end_time_dt = fields.Datetime.context_timestamp(self, end_time_dt)
  243. self.name = (
  244. start_time_dt.strftime("%Y-%m-%d")
  245. + " "
  246. + start_time_dt.strftime("%H:%M")
  247. + "-"
  248. + end_time_dt.strftime("%H:%M")
  249. )
  250. # Is this method necessary ?
  251. @api.depends("annotation")
  252. def _compute_is_annotated(self):
  253. if self.annotation:
  254. self.is_annotated = len(self.annotation) != 0
  255. return
  256. @api.model
  257. def create(self, vals):
  258. new_sheet = super(AttendanceSheet, self).create(vals)
  259. # Creation and addition of the expected shifts corresponding
  260. # to the time range
  261. tasks = self.env["beesdoo.shift.shift"]
  262. tasks = tasks.search(
  263. [
  264. ("start_time", "=", new_sheet.start_time),
  265. ("end_time", "=", new_sheet.end_time),
  266. ]
  267. )
  268. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  269. task_templates = set()
  270. for task in tasks:
  271. if task.working_mode == "irregular":
  272. stage = "absent_1"
  273. else:
  274. stage = "absent_2"
  275. if task.worker_id:
  276. new_expected_shift = expected_shift.create(
  277. {
  278. "attendance_sheet_id": new_sheet.id,
  279. "task_id": task.id,
  280. "worker_id": task.worker_id.id,
  281. "replacement_worker_id": task.replaced_id.id,
  282. "task_type_id": task.task_type_id.id,
  283. "stage": stage,
  284. "working_mode": task.working_mode,
  285. }
  286. )
  287. task_templates.add(task.task_template_id)
  288. # Maximum number of workers calculation
  289. new_sheet.max_worker_no = sum(r.worker_nb for r in task_templates)
  290. return new_sheet
  291. # Workaround to display notifications only for unread and not validated
  292. # sheets, via a check on domain.
  293. @api.model
  294. def _needaction_count(self, domain=None):
  295. if domain == [
  296. ("is_annotated", "=", True),
  297. ("is_read", "=", False),
  298. ] or domain == [("state", "=", "not_validated")]:
  299. return self.search_count(domain)
  300. return
  301. def validate(self):
  302. self.ensure_one()
  303. if self.state == "validated":
  304. raise UserError("The sheet has already been validated.")
  305. shift = self.env["beesdoo.shift.shift"]
  306. stage = self.env["beesdoo.shift.stage"]
  307. # Fields validation
  308. for added_shift in self.added_shift_ids:
  309. if not added_shift.worker_id:
  310. raise UserError(
  311. "Worker must be set for shift %s" % added_shift.id
  312. )
  313. if not added_shift.stage:
  314. raise UserError(
  315. "Shift Stage is missing for %s"
  316. % added_shift.worker_id.name
  317. )
  318. if not added_shift.task_type_id:
  319. raise UserError(
  320. "Task Type is missing for %s" % added_shift.worker_id.name
  321. )
  322. if not added_shift.working_mode:
  323. raise UserError(
  324. "Working mode is missing for %s"
  325. % added_shift.worker_id.name
  326. )
  327. if (
  328. added_shift.worker_id.working_mode == "regular"
  329. and not added_shift.regular_task_type
  330. ):
  331. raise UserError(
  332. "Regular Task Type is missing for %s"
  333. % added_shift.worker_id.name
  334. )
  335. for expected_shift in self.expected_shift_ids:
  336. if not expected_shift.stage:
  337. raise UserError(
  338. "Shift Stage is missing for %s"
  339. % expected_shift.worker_id.name
  340. )
  341. # Expected shifts status update
  342. for expected_shift in self.expected_shift_ids:
  343. actual_shift = expected_shift.task_id
  344. # We get stage record corresponding to mapped stage id
  345. actual_stage = self.env.ref(
  346. "beesdoo_shift.%s" % 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 but would prevent validation.
  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 = self.env.ref(
  357. "beesdoo_shift.%s" % added_shift.get_actual_stage()
  358. )
  359. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  360. is_regular_shift = added_shift.regular_task_type == "normal"
  361. # Add an annotation if a regular worker is doing its regular shift
  362. if is_regular_shift and is_regular_worker:
  363. self.annotation += (
  364. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  365. " Something may be wrong in his/her personnal informations.\n"
  366. % added_shift.worker_id.name
  367. )
  368. # Edit a non-assigned shift or create one if none
  369. non_assigned_shifts = shift.search(
  370. [
  371. ("worker_id", "=", False),
  372. ("start_time", "=", self.start_time),
  373. ("end_time", "=", self.end_time),
  374. ("task_type_id", "=", added_shift.task_type_id.id),
  375. ],
  376. limit=1,
  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] %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. }
  422. def on_barcode_scanned(self, barcode):
  423. if self.state == "validated":
  424. raise UserError(
  425. "You cannot modify a validated attendance sheet."
  426. )
  427. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  428. if not len(worker):
  429. raise UserError("Worker not found (invalid barcode or status).")
  430. if len(worker) > 1:
  431. raise UserError("Multiple workers corresponding to barcode.")
  432. if worker.state in ("unsubscribed", "resigning"):
  433. raise UserError("Worker is %s." % worker.state)
  434. if worker.working_mode not in ("regular", "irregular"):
  435. raise UserError("Worker is %s and should be regular or irregular." % worker.working_mode)
  436. for id in self.expected_shift_ids.ids:
  437. shift = self.env["beesdoo.shift.sheet.expected"].browse(id)
  438. if shift.worker_id == worker or shift.replacement_worker_id == worker:
  439. shift.stage = "present"
  440. return
  441. if worker.working_mode == "regular":
  442. regular_task_type = "normal"
  443. else:
  444. regular_task_type = False
  445. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  446. if worker.id in added_ids:
  447. raise UserError("Worker is already present.")
  448. self.added_shift_ids |= self.added_shift_ids.new({
  449. "task_type_id": self.added_shift_ids._default_task_type_id(),
  450. "stage": "present",
  451. "attendance_sheet_id": self._origin.id,
  452. "worker_id": worker.id,
  453. "regular_task_type": regular_task_type
  454. })