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.

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