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.

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