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.

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