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.

600 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. if rec.annotation:
  300. rec.is_annotated = len(rec.annotation) != 0
  301. @api.model
  302. def create(self, vals):
  303. new_sheet = super(AttendanceSheet, self).create(vals)
  304. # Creation and addition of the expected shifts corresponding
  305. # to the time range
  306. tasks = self.env["beesdoo.shift.shift"]
  307. tasks = tasks.search(
  308. [
  309. ("start_time", "=", new_sheet.start_time),
  310. ("end_time", "=", new_sheet.end_time),
  311. ]
  312. )
  313. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  314. task_templates = set()
  315. for task in tasks:
  316. if task.working_mode == "irregular":
  317. stage = "absent_1"
  318. else:
  319. stage = "absent_2"
  320. if task.worker_id:
  321. new_expected_shift = expected_shift.create(
  322. {
  323. "attendance_sheet_id": new_sheet.id,
  324. "task_id": task.id,
  325. "worker_id": task.worker_id.id,
  326. "replacement_worker_id": task.replaced_id.id,
  327. "task_type_id": task.task_type_id.id,
  328. "super_coop_id": task.super_coop_id.id,
  329. "stage": stage,
  330. "working_mode": task.working_mode,
  331. }
  332. )
  333. task_templates.add(task.task_template_id)
  334. # Maximum number of workers calculation
  335. new_sheet.max_worker_no = sum(r.worker_nb for r in task_templates)
  336. return new_sheet
  337. # Workaround to display notifications only for unread and not validated
  338. # sheets, via a check on domain.
  339. @api.model
  340. def _needaction_count(self, domain=None):
  341. if domain == [
  342. ("is_annotated", "=", True),
  343. ("is_read", "=", False),
  344. ] or domain == [("state", "=", "not_validated")]:
  345. return self.search_count(domain)
  346. return
  347. def validate(self, user):
  348. self.ensure_one()
  349. if self.state == "validated":
  350. raise UserError("The sheet has already been validated.")
  351. shift = self.env["beesdoo.shift.shift"]
  352. stage = self.env["beesdoo.shift.stage"]
  353. # Fields validation
  354. for added_shift in self.added_shift_ids:
  355. if not added_shift.worker_id:
  356. raise UserError(
  357. _("Worker must be set for shift %s") % added_shift.id
  358. )
  359. if not added_shift.stage:
  360. raise UserError(
  361. _("Shift Stage is missing for %s")
  362. % added_shift.worker_id.name
  363. )
  364. if not added_shift.task_type_id:
  365. raise UserError(
  366. _("Task Type is missing for %s")
  367. % added_shift.worker_id.name
  368. )
  369. if not added_shift.working_mode:
  370. raise UserError(
  371. _("Working mode is missing for %s")
  372. % added_shift.worker_id.name
  373. )
  374. if (
  375. added_shift.worker_id.working_mode == "regular"
  376. and not added_shift.regular_task_type
  377. ):
  378. raise UserError(
  379. _("Regular Task Type is missing for %s")
  380. % added_shift.worker_id.name
  381. )
  382. for expected_shift in self.expected_shift_ids:
  383. if not expected_shift.stage:
  384. raise UserError(
  385. _("Shift Stage is missing for %s")
  386. % expected_shift.worker_id.name
  387. )
  388. # Expected shifts status update
  389. for expected_shift in self.expected_shift_ids:
  390. actual_shift = expected_shift.task_id
  391. # We get stage record corresponding to mapped stage id
  392. actual_stage = self.env.ref(
  393. "beesdoo_shift.%s" % expected_shift.get_actual_stage()
  394. )
  395. # If the actual stage has been deleted, the sheet is still validated.
  396. # Raising an exception would stop this but would prevent validation.
  397. # How can we show a message without stopping validation ?
  398. if actual_stage:
  399. actual_shift.stage_id = actual_stage
  400. actual_shift.replaced_id = expected_shift.replacement_worker_id
  401. # Added shifts status update
  402. for added_shift in self.added_shift_ids:
  403. actual_stage = self.env.ref(
  404. "beesdoo_shift.%s" % added_shift.get_actual_stage()
  405. )
  406. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  407. is_regular_shift = added_shift.regular_task_type == "normal"
  408. # Add an annotation if a regular worker is doing its regular shift
  409. if is_regular_shift and is_regular_worker:
  410. self.annotation += (
  411. _(
  412. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  413. " Something may be wrong in his/her personnal informations.\n"
  414. )
  415. % added_shift.worker_id.name
  416. )
  417. # Edit a non-assigned shift or create one if none
  418. non_assigned_shifts = shift.search(
  419. [
  420. ("worker_id", "=", False),
  421. ("start_time", "=", self.start_time),
  422. ("end_time", "=", self.end_time),
  423. ("task_type_id", "=", added_shift.task_type_id.id),
  424. ],
  425. limit=1,
  426. )
  427. if len(non_assigned_shifts):
  428. actual_shift = non_assigned_shifts[0]
  429. actual_shift.write(
  430. {
  431. "stage_id": actual_stage.id,
  432. "worker_id": added_shift.worker_id.id,
  433. "stage_id": actual_stage.id,
  434. "is_regular": is_regular_shift and is_regular_worker,
  435. "is_compensation": not is_regular_shift
  436. and is_regular_worker,
  437. }
  438. )
  439. else:
  440. actual_shift = self.env["beesdoo.shift.shift"].create(
  441. {
  442. "name": _("[Added Shift] %s") % self.start_time,
  443. "task_type_id": added_shift.task_type_id.id,
  444. "worker_id": added_shift.worker_id.id,
  445. "start_time": self.start_time,
  446. "end_time": self.end_time,
  447. "stage_id": actual_stage.id,
  448. "is_regular": is_regular_shift and is_regular_worker,
  449. "is_compensation": not is_regular_shift
  450. and is_regular_worker,
  451. }
  452. )
  453. added_shift.task_id = actual_shift.id
  454. self.validated_by = user
  455. self.state = "validated"
  456. return
  457. # @api.multi is needed to call the wizard, but doesn't match @api.one
  458. # from the validate() method
  459. @api.multi
  460. def validate_via_wizard(self):
  461. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  462. self.validated_by = self.env.user.partner_id
  463. self.validate()
  464. return
  465. return {
  466. "type": "ir.actions.act_window",
  467. "res_model": "beesdoo.shift.sheet.validate",
  468. "view_type": "form",
  469. "view_mode": "form",
  470. "target": "new",
  471. }
  472. @api.model
  473. def _generate_attendance_sheet(self):
  474. """
  475. Generate sheets 20 minutes before current time.
  476. Corresponding CRON intervall time must be the same.
  477. Check if any task exists in the time intervall.
  478. If no sheet is already created, it is created.
  479. """
  480. time_ranges = set()
  481. tasks = self.env["beesdoo.shift.shift"]
  482. sheets = self.env["beesdoo.shift.sheet"]
  483. current_time = datetime.now()
  484. allowed_time_range = timedelta(minutes=20)
  485. tasks = tasks.search(
  486. [
  487. ("start_time", ">", str(current_time),),
  488. ("start_time", "<", str(current_time + allowed_time_range),),
  489. ]
  490. )
  491. for task in tasks:
  492. start_time = task.start_time
  493. end_time = task.end_time
  494. sheets = sheets.search(
  495. [("start_time", "=", start_time), ("end_time", "=", end_time),]
  496. )
  497. if not sheets:
  498. sheet = sheets.create(
  499. {"start_time": start_time, "end_time": end_time}
  500. )
  501. def on_barcode_scanned(self, barcode):
  502. if self.state == "validated":
  503. raise UserError(
  504. _("You cannot modify a validated attendance sheet.")
  505. )
  506. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  507. if not len(worker):
  508. raise UserError(_("Worker not found (invalid barcode or status)."))
  509. if len(worker) > 1:
  510. raise UserError(
  511. _("Multiple workers are corresponding this barcode.")
  512. )
  513. if worker.state in ("unsubscribed", "resigning"):
  514. raise UserError(_("Worker is %s.") % worker.state)
  515. if worker.working_mode not in ("regular", "irregular"):
  516. raise UserError(
  517. _("Worker is %s and should be regular or irregular.")
  518. % worker.working_mode
  519. )
  520. for id in self.expected_shift_ids.ids:
  521. shift = self.env["beesdoo.shift.sheet.expected"].browse(id)
  522. if (
  523. shift.worker_id == worker
  524. or shift.replacement_worker_id == worker
  525. ):
  526. shift.stage = "present"
  527. return
  528. if worker.working_mode == "regular":
  529. regular_task_type = "normal"
  530. else:
  531. regular_task_type = False
  532. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  533. if worker.id in added_ids:
  534. raise UserError(_("Worker is already present."))
  535. self.added_shift_ids |= self.added_shift_ids.new(
  536. {
  537. "task_type_id": self.added_shift_ids.default_task_type_id(),
  538. "stage": "present",
  539. "attendance_sheet_id": self._origin.id,
  540. "worker_id": worker.id,
  541. "regular_task_type": regular_task_type,
  542. }
  543. )