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.

598 lines
21 KiB

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