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.

492 lines
17 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. ],
  30. string="Shift Stage",
  31. copy=False,
  32. )
  33. worker_id = fields.Many2one(
  34. "res.partner",
  35. string="Worker",
  36. domain=[
  37. ("eater", "=", "worker_eater"),
  38. ("working_mode", "in", ("regular", "irregular")),
  39. ("state", "not in", ("unsubscribed", "resigning")),
  40. ],
  41. )
  42. task_type_id = fields.Many2one(
  43. "beesdoo.shift.type", string="Task Type", default=_default_task_type_id
  44. )
  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", "barcodes.barcode_events_mixin"]
  134. _description = "Attendance sheets with all the shifts in one time range."
  135. _order = "start_time"
  136. name = fields.Char(
  137. string="Name", compute="_compute_name", store=True, readonly=True
  138. )
  139. active = fields.Boolean(string="Active", default=1)
  140. state = fields.Selection(
  141. [
  142. ("not_validated", "Not Validated"),
  143. ("validated", "Validated"),
  144. ],
  145. string="Status",
  146. readonly=True,
  147. index=True,
  148. copy=False,
  149. default="not_validated",
  150. track_visibility="onchange",
  151. )
  152. start_time = fields.Datetime(
  153. string="Start Time", required=True, readonly=True
  154. )
  155. end_time = fields.Datetime(string="End Time", required=True, readonly=True)
  156. expected_shift_ids = fields.One2many(
  157. "beesdoo.shift.sheet.expected",
  158. "attendance_sheet_id",
  159. string="Expected Shifts",
  160. )
  161. added_shift_ids = fields.One2many(
  162. "beesdoo.shift.sheet.added",
  163. "attendance_sheet_id",
  164. string="Added Shifts",
  165. )
  166. max_worker_nb = fields.Integer(
  167. string="Maximum number of workers",
  168. default=0,
  169. readonly=True,
  170. help="Indicative maximum number of workers for the shifts.",
  171. )
  172. expected_worker_nb = fields.Integer(
  173. string="Number of expected workers", readonly=True, default=0
  174. )
  175. added_worker_nb = fields.Integer(
  176. compute="_compute_added_shift_nb",
  177. string="Number of added workers",
  178. readonly=True,
  179. default=0,
  180. )
  181. annotation = fields.Text(
  182. "Attendance Sheet annotation", default="", track_visibility="onchange"
  183. )
  184. is_annotated = fields.Boolean(
  185. compute="_compute_is_annotated",
  186. string="Annotation",
  187. readonly=True,
  188. store=True,
  189. )
  190. is_read = fields.Boolean(
  191. string="Mark as read",
  192. help="Has annotation been read by an administrator ?",
  193. default=False,
  194. track_visibility="onchange",
  195. )
  196. feedback = fields.Text(
  197. "Attendance Sheet feedback", track_visibility="onchange"
  198. )
  199. worker_nb_feedback = fields.Selection(
  200. [
  201. ("not_enough", "Not enough"),
  202. ("enough", "Enough"),
  203. ("too much", "Too much"),
  204. ],
  205. string="Feedback regarding the number of workers.",
  206. track_visibility="onchange",
  207. )
  208. attended_worker_nb = fields.Integer(
  209. string="Number of attended workers",
  210. default=0,
  211. help="Number of workers who attended the session.",
  212. readonly=True,
  213. )
  214. validated_by = fields.Many2one(
  215. "res.partner",
  216. string="Validated by",
  217. domain=[
  218. ("eater", "=", "worker_eater"),
  219. ("super", "=", True),
  220. ("working_mode", "=", "regular"),
  221. ("state", "not in", ("unsubscribed", "resigning")),
  222. ],
  223. track_visibility="onchange",
  224. readonly=True,
  225. )
  226. _sql_constraints = [
  227. (
  228. "check_no_annotation_mark_read",
  229. "CHECK ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  230. "Non-annotated sheets can't be marked as read. ",
  231. )
  232. ]
  233. @api.constrains(
  234. "expected_shift_ids",
  235. "added_shift_ids",
  236. "annotation",
  237. "feedback",
  238. "worker_nb_feedback",
  239. )
  240. def _lock_after_validation(self):
  241. if self.state == "validated":
  242. raise UserError(
  243. "The sheet has already been validated and can't be edited."
  244. )
  245. @api.multi
  246. def button_mark_as_read(self):
  247. if self.is_read:
  248. raise UserError("The sheet has already been marked as read.")
  249. self.is_read = True
  250. @api.constrains("expected_shift_ids", "added_shift_ids")
  251. def _constrain_unique_worker(self):
  252. # Warning : map return generator in python3 (for Odoo 12)
  253. added_workers_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  254. expected_workers_ids = map(
  255. lambda s: s.worker_id.id, self.expected_shift_ids
  256. )
  257. replacement_workers_ids = map(
  258. lambda s: s.replacement_worker_id.id, self.expected_shift_ids
  259. )
  260. ids = (
  261. added_workers_ids + expected_workers_ids + replacement_workers_ids
  262. )
  263. if len(ids) - len(set(ids)):
  264. raise UserError("You can't add the same worker more than once.")
  265. @api.depends("added_shift_ids")
  266. def _compute_added_shift_nb(self):
  267. self.added_worker_nb = len(self.added_shift_ids)
  268. return
  269. # Compute name (not hardcorded to prevent incoherence with timezone)
  270. @api.depends("start_time", "end_time")
  271. def _compute_name(self):
  272. start_time_dt = fields.Datetime.from_string(self.start_time)
  273. start_time_dt = fields.Datetime.context_timestamp(self, start_time_dt)
  274. end_time_dt = fields.Datetime.from_string(self.end_time)
  275. end_time_dt = fields.Datetime.context_timestamp(self, end_time_dt)
  276. self.name = (
  277. start_time_dt.strftime("%Y-%m-%d")
  278. + " "
  279. + start_time_dt.strftime("%H:%M")
  280. + " - "
  281. + end_time_dt.strftime("%H:%M")
  282. )
  283. return
  284. # Is this method necessary ?
  285. @api.depends("annotation")
  286. def _compute_is_annotated(self):
  287. if self.annotation:
  288. self.is_annotated = len(self.annotation) != 0
  289. return
  290. @api.model
  291. def create(self, vals):
  292. new_sheet = super(AttendanceSheet, self).create(vals)
  293. # Creation and addition of the expected shifts corresponding
  294. # to the time range
  295. tasks = self.env["beesdoo.shift.shift"]
  296. tasks = tasks.search(
  297. [
  298. ("start_time", "=", new_sheet.start_time),
  299. ("end_time", "=", new_sheet.end_time),
  300. ]
  301. )
  302. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  303. task_templates = set()
  304. for task in tasks:
  305. if task.working_mode == "irregular":
  306. compensation_nb = "1"
  307. else:
  308. compensation_nb = "2"
  309. if task.worker_id:
  310. new_expected_shift = expected_shift.create(
  311. {
  312. "attendance_sheet_id": new_sheet.id,
  313. "task_id": task.id,
  314. "worker_id": task.worker_id.id,
  315. "replacement_worker_id": task.replaced_id.id,
  316. "task_type_id": task.task_type_id.id,
  317. "stage": "absent",
  318. "compensation_nb": compensation_nb,
  319. "working_mode": task.working_mode,
  320. }
  321. )
  322. task_templates.add(task.task_template_id)
  323. new_sheet.expected_worker_nb += 1
  324. # Maximum number of workers calculation
  325. for task_template in task_templates:
  326. new_sheet.max_worker_nb += task_template.worker_nb
  327. return new_sheet
  328. # Workaround to display notifications only for unread and not validated
  329. # sheets, via a check on domain.
  330. @api.model
  331. def _needaction_count(self, domain=None):
  332. if domain == [
  333. ("is_annotated", "=", True),
  334. ("is_read", "=", False),
  335. ] or domain == [("state", "=", "not_validated")]:
  336. return self.search_count(domain)
  337. return
  338. @api.one
  339. def validate(self):
  340. self.ensure_one()
  341. if self.state == "validated":
  342. raise UserError("The sheet has already been validated.")
  343. shift = self.env["beesdoo.shift.shift"]
  344. stage = self.env["beesdoo.shift.stage"]
  345. # Fields validation
  346. for added_shift in self.added_shift_ids:
  347. if (
  348. not added_shift.stage
  349. or not added_shift.worker_id
  350. or not added_shift.task_type_id
  351. or not added_shift.working_mode
  352. or (
  353. added_shift.worker_id.working_mode == "regular"
  354. and not added_shift.regular_task_type
  355. )
  356. ):
  357. raise UserError("All fields must be set before validation.")
  358. # Expected shifts status update
  359. for expected_shift in self.expected_shift_ids:
  360. actual_shift = expected_shift.task_id
  361. actual_stage = stage.search(
  362. [("code", "=", expected_shift.get_actual_stage())]
  363. )
  364. # If the actual stage has been deleted, the sheet is still validated.
  365. # Raising an exception would stop this.
  366. # How can we show a message without stopping validation ?
  367. if actual_stage:
  368. actual_shift.stage_id = actual_stage
  369. actual_shift.replaced_id = expected_shift.replacement_worker_id
  370. # Added shifts status update
  371. for added_shift in self.added_shift_ids:
  372. actual_stage = stage.search(
  373. [("code", "=", added_shift.get_actual_stage())]
  374. )
  375. # WARNING: mapping the selection field to the booleans used in Task
  376. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  377. is_regular_shift = added_shift.regular_task_type == "normal"
  378. # Add an annotation if a regular worker is doing its regular shift
  379. if is_regular_shift and is_regular_worker:
  380. self.annotation += (
  381. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  382. " Something may be wrong in his/her personnal informations.\n"
  383. % added_shift.worker_id.name
  384. )
  385. # Edit a non-assigned shift or create one if none
  386. non_assigned_shifts = shift.search(
  387. [
  388. ("worker_id", "=", False),
  389. ("start_time", "=", self.start_time),
  390. ("end_time", "=", self.end_time),
  391. ("task_type_id", "=", added_shift.task_type_id.id),
  392. ]
  393. )
  394. if len(non_assigned_shifts):
  395. actual_shift = non_assigned_shifts[0]
  396. actual_shift.write(
  397. {
  398. "stage_id": actual_stage.id,
  399. "worker_id": added_shift.worker_id.id,
  400. "stage_id": actual_stage.id,
  401. "is_regular": is_regular_shift and is_regular_worker,
  402. "is_compensation": not is_regular_shift
  403. and is_regular_worker,
  404. }
  405. )
  406. else:
  407. actual_shift = self.env["beesdoo.shift.shift"].create(
  408. {
  409. "name": "Added shift TEST %s" % self.start_time,
  410. "task_type_id": added_shift.task_type_id.id,
  411. "worker_id": added_shift.worker_id.id,
  412. "start_time": self.start_time,
  413. "end_time": self.end_time,
  414. "stage_id": actual_stage.id,
  415. "is_regular": is_regular_shift and is_regular_worker,
  416. "is_compensation": not is_regular_shift
  417. and is_regular_worker,
  418. }
  419. )
  420. added_shift.task_id = actual_shift.id
  421. self.state = "validated"
  422. return
  423. # @api.multi is needed to call the wizard, but doesn't match @api.one
  424. # from the validate() method
  425. @api.multi
  426. def validate_via_wizard(self):
  427. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  428. self.validated_by = self.env.user.partner_id
  429. self.validate()
  430. return
  431. return {
  432. "type": "ir.actions.act_window",
  433. "res_model": "beesdoo.shift.sheet.validate",
  434. "view_type": "form",
  435. "view_mode": "form",
  436. "target": "new",
  437. }
  438. def on_barcode_scanned(self, barcode):
  439. import pdb
  440. pdb.set_trace()
  441. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  442. self.name = barcode