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.

552 lines
19 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 date, datetime, timedelta
  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 = (
  14. int(parameters.get_param("beesdoo_shift.default_task_type_id"))
  15. or 1
  16. )
  17. task_types = self.env["beesdoo.shift.type"]
  18. return task_types.browse(id)
  19. # Related actual shift, not required because doesn't exist for added shift before validation
  20. # To update after validation
  21. task_id = fields.Many2one("beesdoo.shift.shift", string="Task")
  22. attendance_sheet_id = fields.Many2one(
  23. "beesdoo.shift.sheet",
  24. string="Attendance Sheet",
  25. required=True,
  26. ondelete="cascade",
  27. )
  28. stage = fields.Selection(
  29. [
  30. ("present", "Present"),
  31. ("absent_0", "Absent / 0 Compensation"),
  32. ("absent_1", "Absent / 1 Compensation"),
  33. ("absent_2", "Absent / 2 Compensations"),
  34. ("cancelled", "Cancelled"),
  35. ],
  36. string="Shift Stage",
  37. )
  38. worker_id = fields.Many2one(
  39. "res.partner",
  40. string="Worker",
  41. domain=[
  42. ("eater", "=", "worker_eater"),
  43. ("working_mode", "in", ("regular", "irregular")),
  44. ("state", "not in", ("unsubscribed", "resigning")),
  45. ],
  46. )
  47. task_type_id = fields.Many2one(
  48. "beesdoo.shift.type", string="Task Type", default=default_task_type_id
  49. )
  50. working_mode = fields.Selection(
  51. related="worker_id.working_mode", string="Working Mode", store=True
  52. )
  53. def get_actual_stage(self):
  54. """
  55. Mapping function returning the actual id
  56. of corresponding beesdoo.shift.stage,
  57. because we prefer users to select number of compensations
  58. on the sheet rather than the exact stage name.
  59. """
  60. if not self.working_mode or not self.stage:
  61. raise UserError(
  62. _("Impossible to map task status, all values are not set.")
  63. )
  64. if self.working_mode == "regular":
  65. if self.stage == "present":
  66. return "done"
  67. if self.stage == "absent_0":
  68. return "excused_necessity"
  69. if self.stage == "absent_1":
  70. return "excused"
  71. if self.stage == "absent_2":
  72. return "absent"
  73. if self.stage == "cancelled":
  74. return "cancel"
  75. if self.working_mode == "irregular":
  76. if self.stage == "present":
  77. return "done"
  78. if self.stage == "cancelled":
  79. return "cancel"
  80. return "absent"
  81. class AttendanceSheetShiftExpected(models.Model):
  82. _name = "beesdoo.shift.sheet.expected"
  83. _description = "Expected Shift"
  84. _inherit = ["beesdoo.shift.sheet.shift"]
  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. class AttendanceSheetShiftAdded(models.Model):
  95. """The added shifts stage must be Present
  96. (add an SQL constraint ?)
  97. """
  98. _name = "beesdoo.shift.sheet.added"
  99. _description = "Added Shift"
  100. _inherit = ["beesdoo.shift.sheet.shift"]
  101. # Change the previously determined two booleans for a more comprehensive field
  102. regular_task_type = fields.Selection(
  103. [("normal", "Normal"), ("compensation", "Compensation")],
  104. string="Task Mode (if regular)",
  105. help="Shift type for regular workers. ",
  106. )
  107. stage = fields.Selection(default="present")
  108. # WARNING: check the code, readonly fields modified by onchange are not inserted on write
  109. @api.onchange("working_mode")
  110. def on_change_working_mode(self):
  111. self.stage = "present"
  112. if self.working_mode == "regular":
  113. self.regular_task_type = "compensation"
  114. if self.working_mode == "irregular":
  115. self.regular_task_type = False
  116. class AttendanceSheet(models.Model):
  117. _name = "beesdoo.shift.sheet"
  118. _inherit = [
  119. "mail.thread",
  120. "ir.needaction_mixin",
  121. "barcodes.barcode_events_mixin",
  122. ]
  123. _description = "Attendance sheets with all the shifts in one time range."
  124. _order = "start_time"
  125. name = fields.Char(
  126. string="Name", compute="_compute_name", store=True, readonly=True
  127. )
  128. active = fields.Boolean(string="Active", default=1)
  129. state = fields.Selection(
  130. [("not_validated", "Not Validated"), ("validated", "Validated"),],
  131. string="Status",
  132. readonly=True,
  133. index=True,
  134. default="not_validated",
  135. track_visibility="onchange",
  136. )
  137. start_time = fields.Datetime(
  138. string="Start Time", required=True, readonly=True
  139. )
  140. end_time = fields.Datetime(string="End Time", required=True, readonly=True)
  141. expected_shift_ids = fields.One2many(
  142. "beesdoo.shift.sheet.expected",
  143. "attendance_sheet_id",
  144. string="Expected Shifts",
  145. )
  146. added_shift_ids = fields.One2many(
  147. "beesdoo.shift.sheet.added",
  148. "attendance_sheet_id",
  149. string="Added Shifts",
  150. )
  151. max_worker_no = fields.Integer(
  152. string="Maximum number of workers",
  153. default=0,
  154. readonly=True,
  155. help="Indicative maximum number of workers for the shifts.",
  156. )
  157. annotation = fields.Text("Annotation", default="")
  158. is_annotated = fields.Boolean(
  159. compute="_compute_is_annotated",
  160. string="Annotation",
  161. readonly=True,
  162. store=True,
  163. )
  164. is_read = fields.Boolean(
  165. string="Mark as read",
  166. help="Has annotation been read by an administrator ?",
  167. default=False,
  168. track_visibility="onchange",
  169. )
  170. feedback = fields.Text("Feedback")
  171. worker_nb_feedback = fields.Selection(
  172. [
  173. ("not_enough", "Not enough"),
  174. ("enough", "Enough"),
  175. ("too_many", "Too many"),
  176. ],
  177. string="Number of workers.",
  178. )
  179. attended_worker_nb = fields.Integer(
  180. string="Number of attended workers",
  181. default=0,
  182. help="Number of workers who attended the session.",
  183. readonly=True,
  184. )
  185. validated_by = fields.Many2one(
  186. "res.partner",
  187. string="Validated by",
  188. domain=[
  189. ("eater", "=", "worker_eater"),
  190. ("super", "=", True),
  191. ("working_mode", "=", "regular"),
  192. ("state", "not in", ("unsubscribed", "resigning")),
  193. ],
  194. track_visibility="onchange",
  195. readonly=True,
  196. )
  197. _sql_constraints = [
  198. (
  199. "check_no_annotation_mark_read",
  200. "CHECK ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  201. _("Non-annotated sheets can't be marked as read."),
  202. )
  203. ]
  204. @api.constrains(
  205. "expected_shift_ids",
  206. "added_shift_ids",
  207. "annotation",
  208. "feedback",
  209. "worker_nb_feedback",
  210. )
  211. def _lock_after_validation(self):
  212. if self.state == "validated":
  213. raise UserError(
  214. _("The sheet has already been validated and can't be edited.")
  215. )
  216. @api.multi
  217. def button_mark_as_read(self):
  218. if self.is_read:
  219. raise UserError(_("The sheet has already been marked as read."))
  220. self.is_read = True
  221. @api.constrains("expected_shift_ids", "added_shift_ids")
  222. def _constrain_unique_worker(self):
  223. # Warning : map return generator in python3 (for Odoo 12)
  224. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  225. expected_ids = map(lambda s: s.worker_id.id, self.expected_shift_ids)
  226. replacement_ids = map(
  227. lambda s: s.replacement_worker_id.id, self.expected_shift_ids
  228. )
  229. replacement_ids = filter(bool, replacement_ids)
  230. ids = added_ids + expected_ids + replacement_ids
  231. if (len(ids) - len(set(ids))) > 0:
  232. raise UserError(
  233. _(
  234. "You can't add the same worker more than once to an attendance sheet."
  235. )
  236. )
  237. # Compute name (not hardcorded to prevent incoherence with timezone)
  238. @api.depends("start_time", "end_time")
  239. def _compute_name(self):
  240. start_time_dt = fields.Datetime.from_string(self.start_time)
  241. start_time_dt = fields.Datetime.context_timestamp(self, start_time_dt)
  242. end_time_dt = fields.Datetime.from_string(self.end_time)
  243. end_time_dt = fields.Datetime.context_timestamp(self, end_time_dt)
  244. self.name = (
  245. start_time_dt.strftime("%Y-%m-%d")
  246. + " "
  247. + start_time_dt.strftime("%H:%M")
  248. + "-"
  249. + end_time_dt.strftime("%H:%M")
  250. )
  251. # Is this method necessary ?
  252. @api.depends("annotation")
  253. def _compute_is_annotated(self):
  254. if self.annotation:
  255. self.is_annotated = len(self.annotation) != 0
  256. return
  257. @api.model
  258. def create(self, vals):
  259. new_sheet = super(AttendanceSheet, self).create(vals)
  260. # Creation and addition of the expected shifts corresponding
  261. # to the time range
  262. tasks = self.env["beesdoo.shift.shift"]
  263. tasks = tasks.search(
  264. [
  265. ("start_time", "=", new_sheet.start_time),
  266. ("end_time", "=", new_sheet.end_time),
  267. ]
  268. )
  269. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  270. task_templates = set()
  271. for task in tasks:
  272. if task.working_mode == "irregular":
  273. stage = "absent_1"
  274. else:
  275. stage = "absent_2"
  276. if task.worker_id:
  277. new_expected_shift = expected_shift.create(
  278. {
  279. "attendance_sheet_id": new_sheet.id,
  280. "task_id": task.id,
  281. "worker_id": task.worker_id.id,
  282. "replacement_worker_id": task.replaced_id.id,
  283. "task_type_id": task.task_type_id.id,
  284. "stage": stage,
  285. "working_mode": task.working_mode,
  286. }
  287. )
  288. task_templates.add(task.task_template_id)
  289. # Maximum number of workers calculation
  290. new_sheet.max_worker_no = sum(r.worker_nb for r in task_templates)
  291. return new_sheet
  292. # Workaround to display notifications only for unread and not validated
  293. # sheets, via a check on domain.
  294. @api.model
  295. def _needaction_count(self, domain=None):
  296. if domain == [
  297. ("is_annotated", "=", True),
  298. ("is_read", "=", False),
  299. ] or domain == [("state", "=", "not_validated")]:
  300. return self.search_count(domain)
  301. return
  302. def validate(self):
  303. self.ensure_one()
  304. if self.state == "validated":
  305. raise UserError("The sheet has already been validated.")
  306. shift = self.env["beesdoo.shift.shift"]
  307. stage = self.env["beesdoo.shift.stage"]
  308. # Fields validation
  309. for added_shift in self.added_shift_ids:
  310. if not added_shift.worker_id:
  311. raise UserError(
  312. _("Worker must be set for shift %s") % added_shift.id
  313. )
  314. if not added_shift.stage:
  315. raise UserError(
  316. _("Shift Stage is missing for %s")
  317. % added_shift.worker_id.name
  318. )
  319. if not added_shift.task_type_id:
  320. raise UserError(
  321. _("Task Type is missing for %s")
  322. % added_shift.worker_id.name
  323. )
  324. if not added_shift.working_mode:
  325. raise UserError(
  326. _("Working mode is missing for %s")
  327. % added_shift.worker_id.name
  328. )
  329. if (
  330. added_shift.worker_id.working_mode == "regular"
  331. and not added_shift.regular_task_type
  332. ):
  333. raise UserError(
  334. _("Regular Task Type is missing for %s")
  335. % added_shift.worker_id.name
  336. )
  337. for expected_shift in self.expected_shift_ids:
  338. if not expected_shift.stage:
  339. raise UserError(
  340. _("Shift Stage is missing for %s")
  341. % expected_shift.worker_id.name
  342. )
  343. # Expected shifts status update
  344. for expected_shift in self.expected_shift_ids:
  345. actual_shift = expected_shift.task_id
  346. # We get stage record corresponding to mapped stage id
  347. actual_stage = self.env.ref(
  348. "beesdoo_shift.%s" % expected_shift.get_actual_stage()
  349. )
  350. # If the actual stage has been deleted, the sheet is still validated.
  351. # Raising an exception would stop this but would prevent validation.
  352. # How can we show a message without stopping validation ?
  353. if actual_stage:
  354. actual_shift.stage_id = actual_stage
  355. actual_shift.replaced_id = expected_shift.replacement_worker_id
  356. # Added shifts status update
  357. for added_shift in self.added_shift_ids:
  358. actual_stage = self.env.ref(
  359. "beesdoo_shift.%s" % added_shift.get_actual_stage()
  360. )
  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. _(
  367. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  368. " Something may be wrong in his/her personnal informations.\n"
  369. )
  370. % added_shift.worker_id.name
  371. )
  372. # Edit a non-assigned shift or create one if none
  373. non_assigned_shifts = shift.search(
  374. [
  375. ("worker_id", "=", False),
  376. ("start_time", "=", self.start_time),
  377. ("end_time", "=", self.end_time),
  378. ("task_type_id", "=", added_shift.task_type_id.id),
  379. ],
  380. limit=1,
  381. )
  382. if len(non_assigned_shifts):
  383. actual_shift = non_assigned_shifts[0]
  384. actual_shift.write(
  385. {
  386. "stage_id": actual_stage.id,
  387. "worker_id": added_shift.worker_id.id,
  388. "stage_id": actual_stage.id,
  389. "is_regular": is_regular_shift and is_regular_worker,
  390. "is_compensation": not is_regular_shift
  391. and is_regular_worker,
  392. }
  393. )
  394. else:
  395. actual_shift = self.env["beesdoo.shift.shift"].create(
  396. {
  397. "name": _("[Added Shift] %s") % self.start_time,
  398. "task_type_id": added_shift.task_type_id.id,
  399. "worker_id": added_shift.worker_id.id,
  400. "start_time": self.start_time,
  401. "end_time": self.end_time,
  402. "stage_id": actual_stage.id,
  403. "is_regular": is_regular_shift and is_regular_worker,
  404. "is_compensation": not is_regular_shift
  405. and is_regular_worker,
  406. }
  407. )
  408. added_shift.task_id = actual_shift.id
  409. self.state = "validated"
  410. return
  411. # @api.multi is needed to call the wizard, but doesn't match @api.one
  412. # from the validate() method
  413. @api.multi
  414. def validate_via_wizard(self):
  415. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  416. self.validated_by = self.env.user.partner_id
  417. self.validate()
  418. return
  419. return {
  420. "type": "ir.actions.act_window",
  421. "res_model": "beesdoo.shift.sheet.validate",
  422. "view_type": "form",
  423. "view_mode": "form",
  424. "target": "new",
  425. }
  426. @api.model
  427. def _generate_attendance_sheet(self):
  428. """
  429. Generate sheets 20 minutes before current time.
  430. Corresponding CRON intervall time must be the same.
  431. Check if any task exists in the time intervall.
  432. If no sheet is already created, it is created.
  433. """
  434. time_ranges = set()
  435. tasks = self.env["beesdoo.shift.shift"]
  436. sheets = self.env["beesdoo.shift.sheet"]
  437. current_time = datetime.now()
  438. allowed_time_range = timedelta(minutes=20)
  439. tasks = tasks.search(
  440. [
  441. ("start_time", ">", str(current_time),),
  442. ("start_time", "<", str(current_time + allowed_time_range),),
  443. ]
  444. )
  445. for task in tasks:
  446. start_time = task.start_time
  447. end_time = task.end_time
  448. sheets = sheets.search(
  449. [("start_time", "=", start_time), ("end_time", "=", end_time),]
  450. )
  451. if not sheets:
  452. sheet = sheets.create(
  453. {"start_time": start_time, "end_time": end_time}
  454. )
  455. def on_barcode_scanned(self, barcode):
  456. if self.state == "validated":
  457. raise UserError(
  458. _("You cannot modify a validated attendance sheet.")
  459. )
  460. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  461. if not len(worker):
  462. raise UserError(_("Worker not found (invalid barcode or status)."))
  463. if len(worker) > 1:
  464. raise UserError(
  465. _("Multiple workers are corresponding this barcode.")
  466. )
  467. if worker.state in ("unsubscribed", "resigning"):
  468. raise UserError(_("Worker is %s.") % worker.state)
  469. if worker.working_mode not in ("regular", "irregular"):
  470. raise UserError(
  471. _("Worker is %s and should be regular or irregular.")
  472. % worker.working_mode
  473. )
  474. for id in self.expected_shift_ids.ids:
  475. shift = self.env["beesdoo.shift.sheet.expected"].browse(id)
  476. if (
  477. shift.worker_id == worker
  478. or shift.replacement_worker_id == worker
  479. ):
  480. shift.stage = "present"
  481. return
  482. if worker.working_mode == "regular":
  483. regular_task_type = "normal"
  484. else:
  485. regular_task_type = False
  486. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  487. if worker.id in added_ids:
  488. raise UserError(_("Worker is already present."))
  489. self.added_shift_ids |= self.added_shift_ids.new(
  490. {
  491. "task_type_id": self.added_shift_ids.default_task_type_id(),
  492. "stage": "present",
  493. "attendance_sheet_id": self._origin.id,
  494. "worker_id": worker.id,
  495. "regular_task_type": regular_task_type,
  496. }
  497. )