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.

668 lines
22 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. from datetime import date, datetime, timedelta
  2. from odoo import _, api, fields, models
  3. from odoo.exceptions import UserError
  4. class AttendanceSheetShift(models.Model):
  5. """
  6. Partial copy of Task class to use in AttendanceSheet,
  7. actual Task is updated at validation.
  8. Should be Abstract and not used alone (common code for
  9. AttendanceSheetShiftAdded and AttendanceSheetShiftExpected),
  10. but create() method from res.partner raise error
  11. when class is Abstract.
  12. """
  13. _name = "beesdoo.shift.sheet.shift"
  14. _description = "Copy of an actual shift into an attendance sheet"
  15. _order = "task_type_id, worker_name"
  16. @api.model
  17. def pre_filled_task_type_id(self):
  18. parameters = self.env["ir.config_parameter"].sudo()
  19. tasktype_id = int(
  20. parameters.get_param(
  21. "beesdoo_shift_attendance.pre_filled_task_type_id", default=1
  22. )
  23. )
  24. task_types = self.env["beesdoo.shift.type"]
  25. return task_types.browse(tasktype_id)
  26. # Related actual shift
  27. task_id = fields.Many2one("beesdoo.shift.shift", string="Task")
  28. attendance_sheet_id = fields.Many2one(
  29. "beesdoo.shift.sheet",
  30. string="Attendance Sheet",
  31. required=True,
  32. ondelete="cascade",
  33. )
  34. state = fields.Selection(
  35. [
  36. ("done", "Present"),
  37. ("absent_0", "Absent - 0 Compensation"),
  38. ("absent_1", "Absent - 1 Compensation"),
  39. ("absent_2", "Absent - 2 Compensations"),
  40. ],
  41. string="Shift State",
  42. required=True,
  43. )
  44. worker_id = fields.Many2one(
  45. "res.partner",
  46. string="Worker",
  47. domain=[
  48. ("is_worker", "=", True),
  49. ("working_mode", "in", ("regular", "irregular")),
  50. ("state", "not in", ("unsubscribed", "resigning")),
  51. ],
  52. required=True,
  53. )
  54. worker_name = fields.Char(related="worker_id.name", store=True)
  55. task_type_id = fields.Many2one(
  56. "beesdoo.shift.type",
  57. string="Task Type",
  58. default=pre_filled_task_type_id,
  59. )
  60. working_mode = fields.Selection(
  61. related="worker_id.working_mode", string="Working Mode"
  62. )
  63. # The two exclusive booleans are gathered in a simple one
  64. is_compensation = fields.Boolean(
  65. string="Compensation shift ?", help="Only for regular workers"
  66. )
  67. class AttendanceSheetShiftExpected(models.Model):
  68. """
  69. Shifts already expected.
  70. """
  71. _name = "beesdoo.shift.sheet.expected"
  72. _description = "Expected Shift"
  73. _inherit = ["beesdoo.shift.sheet.shift"]
  74. super_coop_id = fields.Many2one(
  75. related="task_id.super_coop_id", store=True
  76. )
  77. replaced_id = fields.Many2one(
  78. "res.partner",
  79. string="Replacement Worker",
  80. help="Replacement Worker (must be regular)",
  81. domain=[
  82. ("eater", "=", "worker_eater"),
  83. ("working_mode", "=", "regular"),
  84. ("state", "not in", ("unsubscribed", "resigning")),
  85. ],
  86. )
  87. @api.onchange("replaced_id")
  88. def on_change_replacement_worker(self):
  89. if self.replaced_id:
  90. self.state = "done"
  91. class AttendanceSheetShiftAdded(models.Model):
  92. """
  93. Shifts added during time slot.
  94. """
  95. _name = "beesdoo.shift.sheet.added"
  96. _description = "Added Shift"
  97. _inherit = ["beesdoo.shift.sheet.shift"]
  98. state = fields.Selection(default="done")
  99. @api.onchange("working_mode")
  100. def on_change_working_mode(self):
  101. self.state = "done"
  102. self.is_compensation = self.working_mode == "regular"
  103. class AttendanceSheet(models.Model):
  104. _name = "beesdoo.shift.sheet"
  105. _inherit = ["mail.thread", "barcodes.barcode_events_mixin"]
  106. _description = "Attendance sheet"
  107. _order = "start_time"
  108. name = fields.Char(string="Name", compute="_compute_name")
  109. time_slot = fields.Char(
  110. string="Time Slot",
  111. compute="_compute_time_slot",
  112. store=True,
  113. readonly=True,
  114. )
  115. active = fields.Boolean(string="Active", default=1)
  116. state = fields.Selection(
  117. [("not_validated", "Not Validated"), ("validated", "Validated")],
  118. string="State",
  119. readonly=True,
  120. index=True,
  121. default="not_validated",
  122. track_visibility="onchange",
  123. )
  124. start_time = fields.Datetime(
  125. string="Start Time", required=True, readonly=True
  126. )
  127. end_time = fields.Datetime(string="End Time", required=True, readonly=True)
  128. day = fields.Date(string="Day", compute="_compute_day", store=True)
  129. day_abbrevation = fields.Char(
  130. string="Day Abbrevation", compute="_compute_day_abbrevation"
  131. )
  132. week = fields.Char(
  133. string="Week",
  134. help="Computed from planning name",
  135. compute="_compute_week",
  136. )
  137. expected_shift_ids = fields.One2many(
  138. "beesdoo.shift.sheet.expected",
  139. "attendance_sheet_id",
  140. string="Expected Shifts",
  141. )
  142. added_shift_ids = fields.One2many(
  143. "beesdoo.shift.sheet.added",
  144. "attendance_sheet_id",
  145. string="Added Shifts",
  146. )
  147. max_worker_no = fields.Integer(
  148. string="Maximum number of workers",
  149. default=0,
  150. readonly=True,
  151. help="Indicative maximum number of workers.",
  152. )
  153. attended_worker_no = fields.Integer(
  154. string="Number of workers present", default=0, readonly=True
  155. )
  156. notes = fields.Text(
  157. "Notes",
  158. default="",
  159. help="Notes about the attendance for the Members Office",
  160. )
  161. is_annotated = fields.Boolean(
  162. compute="_compute_is_annotated",
  163. string="Is annotated",
  164. readonly=True,
  165. store=True,
  166. )
  167. is_read = fields.Boolean(
  168. string="Mark as read",
  169. help="Has notes been read by an administrator ?",
  170. default=False,
  171. track_visibility="onchange",
  172. )
  173. feedback = fields.Text("Comments about the shift")
  174. worker_nb_feedback = fields.Selection(
  175. [
  176. ("not_enough", "Not enough workers"),
  177. ("enough", "Enough workers"),
  178. ("too_many", "Too many workers"),
  179. ("empty", "I was not there during the shift"),
  180. ],
  181. string="Was your team big enough ? *",
  182. )
  183. validated_by = fields.Many2one(
  184. "res.partner",
  185. string="Validated by",
  186. domain=[
  187. ("eater", "=", "worker_eater"),
  188. ("super", "=", True),
  189. ("working_mode", "=", "regular"),
  190. ("state", "not in", ("unsubscribed", "resigning")),
  191. ],
  192. track_visibility="onchange",
  193. readonly=True,
  194. )
  195. _sql_constraints = [
  196. (
  197. "check_not_annotated_mark_as_read",
  198. "CHECK"
  199. " ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  200. _("Non-annotated sheets can't be marked as read."),
  201. )
  202. ]
  203. @api.depends("start_time", "end_time")
  204. def _compute_time_slot(self):
  205. for rec in self:
  206. start_time = fields.Datetime.context_timestamp(rec, rec.start_time)
  207. end_time = fields.Datetime.context_timestamp(rec, rec.end_time)
  208. rec.time_slot = (
  209. start_time.strftime("%H:%M") + "-" + end_time.strftime("%H:%M")
  210. )
  211. @api.depends("start_time", "end_time", "week", "day_abbrevation")
  212. def _compute_name(self):
  213. for rec in self:
  214. start_time = fields.Datetime.context_timestamp(rec, rec.start_time)
  215. name = "[%s] " % fields.Date.to_string(start_time)
  216. if rec.week:
  217. name += rec.week + " "
  218. if rec.day_abbrevation:
  219. name += rec.day_abbrevation + " "
  220. if rec.time_slot:
  221. name += "(%s)" % rec.time_slot
  222. rec.name = name
  223. @api.depends("start_time")
  224. def _compute_day(self):
  225. for rec in self:
  226. rec.day = rec.start_time.date()
  227. @api.depends("expected_shift_ids")
  228. def _compute_day_abbrevation(self):
  229. """
  230. Compute Day Abbrevation from Planning Name
  231. of first expected shift with one.
  232. """
  233. for rec in self:
  234. for shift in rec.expected_shift_ids:
  235. if shift.task_id.task_template_id.day_nb_id.name:
  236. rec.day_abbrevation = (
  237. shift.task_id.task_template_id.day_nb_id.name
  238. )
  239. @api.depends("expected_shift_ids")
  240. def _compute_week(self):
  241. """
  242. Compute Week Name from Planning Name
  243. of first expected shift with one.
  244. """
  245. for rec in self:
  246. for shift in rec.expected_shift_ids:
  247. if shift.task_id.planning_id.name:
  248. rec.week = shift.task_id.planning_id.name
  249. @api.depends("notes")
  250. def _compute_is_annotated(self):
  251. for rec in self:
  252. if rec.notes:
  253. rec.is_annotated = bool(rec.notes.strip())
  254. @api.constrains("expected_shift_ids", "added_shift_ids")
  255. def _constrain_unique_worker(self):
  256. # Warning : map return generator in python3 (for Odoo 12)
  257. added_ids = [s.worker_id.id for s in self.added_shift_ids]
  258. expected_ids = [s.worker_id.id for s in self.expected_shift_ids]
  259. replacement_ids = [
  260. s.replaced_id.id
  261. for s in self.expected_shift_ids
  262. if s.replaced_id.id
  263. ]
  264. ids = added_ids + expected_ids + replacement_ids
  265. if (len(ids) - len(set(ids))) > 0:
  266. raise UserError(
  267. _(
  268. "You can't add the same worker more than once to an "
  269. "attendance sheet. "
  270. )
  271. )
  272. @api.constrains(
  273. "expected_shift_ids",
  274. "added_shift_ids",
  275. "notes",
  276. "feedback",
  277. "worker_nb_feedback",
  278. )
  279. def _lock_after_validation(self):
  280. if self.state == "validated":
  281. raise UserError(
  282. _("The sheet has already been validated and can't be edited.")
  283. )
  284. def on_barcode_scanned(self, barcode):
  285. if self.env.user.has_group(
  286. "beesdoo_shift_attendance.group_shift_attendance"
  287. ):
  288. raise UserError(
  289. _(
  290. "You must be logged as 'Attendance Sheet Generic Access' "
  291. " if you want to scan cards."
  292. )
  293. )
  294. if self.state == "validated":
  295. raise UserError(
  296. _("A validated attendance sheet can't be modified")
  297. )
  298. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  299. if not len(worker):
  300. raise UserError(
  301. _(
  302. "Worker not found (invalid barcode or status). \n"
  303. "Barcode : %s"
  304. )
  305. % barcode
  306. )
  307. if len(worker) > 1:
  308. raise UserError(
  309. _(
  310. "Multiple workers are corresponding this barcode. \n"
  311. "Barcode : %s"
  312. )
  313. % barcode
  314. )
  315. if worker.state == "unsubscribed":
  316. shift_counter = (
  317. worker.cooperative_status_ids.sc
  318. + worker.cooperative_status_ids.sr
  319. )
  320. raise UserError(
  321. _(
  322. "Beware, your account is frozen because your shift counter "
  323. "is at %s. Please contact Members Office to unfreeze it. "
  324. "If you want to attend this shift, your supercoop "
  325. "can write your name in the notes field during validation."
  326. )
  327. % shift_counter
  328. )
  329. if worker.state == "resigning":
  330. raise UserError(
  331. _(
  332. "Beware, you are recorded as resigning. "
  333. "Please contact member's office if this is incorrect. "
  334. "Thank you. "
  335. )
  336. )
  337. if worker.working_mode not in ("regular", "irregular"):
  338. raise UserError(
  339. _(
  340. "%s's working mode is %s and should be regular or "
  341. "irregular. "
  342. )
  343. % (worker.name, worker.working_mode)
  344. )
  345. # Expected shifts status update
  346. for id_ in self.expected_shift_ids.ids:
  347. shift = self.env["beesdoo.shift.sheet.expected"].browse(id_)
  348. if (
  349. shift.worker_id == worker and not shift.replaced_id
  350. ) or shift.replaced_id == worker:
  351. shift.state = "done"
  352. return
  353. if shift.worker_id == worker and shift.replaced_id:
  354. raise UserError(
  355. _("%s is registered as replaced.") % worker.name
  356. )
  357. is_compensation = worker.working_mode == "regular"
  358. added_ids = [s.worker_id.id for s in self.added_shift_ids]
  359. if worker.id not in added_ids:
  360. # Added shift creation
  361. self.added_shift_ids |= self.added_shift_ids.new(
  362. {
  363. "task_type_id": (
  364. self.added_shift_ids.pre_filled_task_type_id()
  365. ),
  366. "state": "done",
  367. "attendance_sheet_id": self._origin.id,
  368. "worker_id": worker.id,
  369. "is_compensation": is_compensation,
  370. }
  371. )
  372. @api.model
  373. def create(self, vals):
  374. new_sheet = super(AttendanceSheet, self).create(vals)
  375. # Creation and addition of the expected shifts corresponding
  376. # to the time range
  377. tasks = self.env["beesdoo.shift.shift"]
  378. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  379. # Fix issues with equality check on datetime
  380. # by searching on a small intervall instead
  381. delta = timedelta(minutes=1)
  382. tasks = tasks.search(
  383. [
  384. ("start_time", ">", new_sheet.start_time - delta),
  385. ("start_time", "<", new_sheet.start_time + delta),
  386. ("end_time", ">", new_sheet.end_time - delta),
  387. ("end_time", "<", new_sheet.end_time + delta),
  388. ]
  389. )
  390. workers = []
  391. for task in tasks:
  392. # Only one shift is added if multiple similar exist
  393. if (
  394. task.worker_id
  395. and task.worker_id not in workers
  396. and (task.state != "cancel")
  397. ):
  398. expected_shift.create(
  399. {
  400. "attendance_sheet_id": new_sheet.id,
  401. "task_id": task.id,
  402. "worker_id": task.worker_id.id,
  403. "replaced_id": task.replaced_id.id,
  404. "task_type_id": task.task_type_id.id,
  405. "state": "absent_2",
  406. "working_mode": task.working_mode,
  407. "is_compensation": task.is_compensation,
  408. }
  409. )
  410. workers.append(task.worker_id)
  411. # Maximum number of workers calculation (count empty shifts)
  412. new_sheet.max_worker_no = len(tasks)
  413. return new_sheet
  414. @api.multi
  415. def button_mark_as_read(self):
  416. if self.is_read:
  417. raise UserError(_("The sheet has already been marked as read."))
  418. self.is_read = True
  419. def _validate(self, user):
  420. self.ensure_one()
  421. if self.state == "validated":
  422. raise UserError(_("The sheet has already been validated."))
  423. # Expected shifts status update
  424. for expected_shift in self.expected_shift_ids:
  425. actual_shift = expected_shift.task_id
  426. actual_shift.replaced_id = expected_shift.replaced_id
  427. actual_shift.state = expected_shift.state
  428. if expected_shift.state == "done":
  429. self.attended_worker_no += 1
  430. if expected_shift.state != "done":
  431. mail_template = self.env.ref(
  432. "beesdoo_shift_attendance.email_template_non_attendance",
  433. False,
  434. )
  435. mail_template.send_mail(expected_shift.task_id.id, True)
  436. # Added shifts status update
  437. for added_shift in self.added_shift_ids:
  438. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  439. is_compensation = added_shift.is_compensation
  440. # Edit a non-assigned shift or create one if none
  441. # Fix issues with equality check on datetime
  442. # by searching on a small intervall instead
  443. delta = timedelta(minutes=1)
  444. non_assigned_shifts = self.env["beesdoo.shift.shift"].search(
  445. [
  446. ("worker_id", "=", False),
  447. ("start_time", ">", self.start_time - delta),
  448. ("start_time", "<", self.start_time + delta),
  449. ("end_time", ">", self.end_time - delta),
  450. ("end_time", "<", self.end_time + delta),
  451. ("task_type_id", "=", added_shift.task_type_id.id),
  452. ],
  453. limit=1,
  454. )
  455. if len(non_assigned_shifts):
  456. actual_shift = non_assigned_shifts[0]
  457. else:
  458. actual_shift = self.env["beesdoo.shift.shift"].create(
  459. {
  460. "name": _("%s (added)" % self.name),
  461. "task_type_id": added_shift.task_type_id.id,
  462. "start_time": self.start_time,
  463. "end_time": self.end_time,
  464. }
  465. )
  466. actual_shift.write(
  467. {
  468. "state": added_shift.state,
  469. "worker_id": added_shift.worker_id.id,
  470. "is_regular": not is_compensation and is_regular_worker,
  471. "is_compensation": is_compensation and is_regular_worker,
  472. }
  473. )
  474. added_shift.task_id = actual_shift.id
  475. if actual_shift.state == "done":
  476. self.attended_worker_no += 1
  477. self.validated_by = user
  478. self.state = "validated"
  479. return
  480. @api.multi
  481. def validate_with_checks(self):
  482. self.ensure_one()
  483. if self.state == "validated":
  484. raise UserError(_("The sheet has already been validated."))
  485. if self.start_time > datetime.now():
  486. raise UserError(
  487. _(
  488. "Attendance sheet can only be validated once the shifts "
  489. "have started. "
  490. )
  491. )
  492. # Fields validation
  493. for added_shift in self.added_shift_ids:
  494. if not added_shift.worker_id:
  495. raise UserError(
  496. _("Worker name is missing for an added shift.")
  497. )
  498. if added_shift.state != "done":
  499. raise UserError(
  500. _("Shift State is missing or wrong for %s")
  501. % added_shift.worker_id.name
  502. )
  503. if not added_shift.task_type_id:
  504. raise UserError(
  505. _("Task Type is missing for %s")
  506. % added_shift.worker_id.name
  507. )
  508. if not added_shift.working_mode:
  509. raise UserError(
  510. _("Working mode is missing for %s")
  511. % added_shift.worker_id.name
  512. )
  513. if added_shift.working_mode not in ["regular", "irregular"]:
  514. raise UserError(
  515. _("Warning : Working mode for %s is %s")
  516. % (
  517. added_shift.worker_id.name,
  518. added_shift.worker_id.working_mode,
  519. )
  520. )
  521. for expected_shift in self.expected_shift_ids:
  522. if not expected_shift.state:
  523. raise UserError(
  524. _("Shift State is missing for %s")
  525. % expected_shift.worker_id.name
  526. )
  527. if (
  528. expected_shift.state == "absent"
  529. and not expected_shift.compensation_no
  530. ):
  531. raise UserError(
  532. _("Compensation number is missing for %s")
  533. % expected_shift.worker_id.name
  534. )
  535. # Open a validation wizard only if not admin
  536. if self.env.user.has_group(
  537. "beesdoo_shift_attendance.group_shift_attendance_sheet_validation"
  538. ):
  539. if not self.worker_nb_feedback:
  540. raise UserError(
  541. _("Please give your feedback about the number of workers.")
  542. )
  543. self._validate(self.env.user.partner_id)
  544. return
  545. return {
  546. "type": "ir.actions.act_window",
  547. "res_model": "beesdoo.shift.sheet.validate",
  548. "view_type": "form",
  549. "view_mode": "form",
  550. "target": "new",
  551. }
  552. @api.model
  553. def _generate_attendance_sheet(self):
  554. """
  555. Generate sheets with shifts in the time interval
  556. defined from corresponding CRON time interval.
  557. """
  558. tasks = self.env["beesdoo.shift.shift"]
  559. sheets = self.env["beesdoo.shift.sheet"]
  560. current_time = datetime.now()
  561. generation_interval_setting = int(
  562. self.env["ir.config_parameter"]
  563. .sudo()
  564. .get_param(
  565. "beesdoo_shift_attendance.attendance_sheet_generation_interval"
  566. )
  567. )
  568. allowed_time_range = timedelta(minutes=generation_interval_setting)
  569. tasks = tasks.search(
  570. [
  571. ("start_time", ">", str(current_time)),
  572. ("start_time", "<", str(current_time + allowed_time_range)),
  573. ]
  574. )
  575. for task in tasks:
  576. start_time = task.start_time
  577. end_time = task.end_time
  578. sheets = sheets.search(
  579. [("start_time", "=", start_time), ("end_time", "=", end_time)]
  580. )
  581. if not sheets:
  582. sheets.create({"start_time": start_time, "end_time": end_time})
  583. @api.model
  584. def _cron_non_validated_sheets(self):
  585. sheets = self.env["beesdoo.shift.sheet"]
  586. non_validated_sheets = sheets.search(
  587. [
  588. ("day", "=", date.today() - timedelta(days=1)),
  589. ("state", "=", "not_validated"),
  590. ]
  591. )
  592. if non_validated_sheets:
  593. mail_template = self.env.ref(
  594. "beesdoo_shift_attendance.email_template_non_validated_sheet",
  595. False,
  596. )
  597. for rec in non_validated_sheets:
  598. mail_template.send_mail(rec.id, True)