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.

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