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.

661 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
  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 ((is_annotated=FALSE AND is_read=FALSE) OR is_annotated=TRUE)",
  199. _("Non-annotated sheets can't be marked as read."),
  200. )
  201. ]
  202. @api.depends("start_time", "end_time")
  203. def _compute_time_slot(self):
  204. for rec in self:
  205. start_time = fields.Datetime.context_timestamp(rec, rec.start_time)
  206. end_time = fields.Datetime.context_timestamp(rec, rec.end_time)
  207. rec.time_slot = (
  208. start_time.strftime("%H:%M") + "-" + end_time.strftime("%H:%M")
  209. )
  210. @api.depends("start_time", "end_time", "week", "day_abbrevation")
  211. def _compute_name(self):
  212. for rec in self:
  213. start_time = fields.Datetime.context_timestamp(rec, rec.start_time)
  214. name = "[%s] " % fields.Date.to_string(start_time)
  215. if rec.week:
  216. name += rec.week + " "
  217. if rec.day_abbrevation:
  218. name += rec.day_abbrevation + " "
  219. if rec.time_slot:
  220. name += "(%s)" % rec.time_slot
  221. rec.name = name
  222. @api.depends("start_time")
  223. def _compute_day(self):
  224. for rec in self:
  225. rec.day = rec.start_time.date()
  226. @api.depends("expected_shift_ids")
  227. def _compute_day_abbrevation(self):
  228. """
  229. Compute Day Abbrevation from Planning Name
  230. of first expected shift with one.
  231. """
  232. for rec in self:
  233. for shift in rec.expected_shift_ids:
  234. if shift.task_id.task_template_id.day_nb_id.name:
  235. rec.day_abbrevation = (
  236. shift.task_id.task_template_id.day_nb_id.name
  237. )
  238. @api.depends("expected_shift_ids")
  239. def _compute_week(self):
  240. """
  241. Compute Week Name from Planning Name
  242. of first expected shift with one.
  243. """
  244. for rec in self:
  245. for shift in rec.expected_shift_ids:
  246. if shift.task_id.planning_id.name:
  247. rec.week = shift.task_id.planning_id.name
  248. @api.depends("notes")
  249. def _compute_is_annotated(self):
  250. for rec in self:
  251. if rec.notes:
  252. rec.is_annotated = bool(rec.notes.strip())
  253. @api.constrains("expected_shift_ids", "added_shift_ids")
  254. def _constrain_unique_worker(self):
  255. # Warning : map return generator in python3 (for Odoo 12)
  256. added_ids = [s.worker_id.id for s in self.added_shift_ids]
  257. expected_ids = [s.worker_id.id for s in self.expected_shift_ids]
  258. replacement_ids = [
  259. s.replaced_id.id
  260. for s in self.expected_shift_ids
  261. if s.replaced_id.id
  262. ]
  263. ids = added_ids + expected_ids + replacement_ids
  264. if (len(ids) - len(set(ids))) > 0:
  265. raise UserError(
  266. _(
  267. "You can't add the same worker more than once to an attendance sheet."
  268. )
  269. )
  270. @api.constrains(
  271. "expected_shift_ids",
  272. "added_shift_ids",
  273. "notes",
  274. "feedback",
  275. "worker_nb_feedback",
  276. )
  277. def _lock_after_validation(self):
  278. if self.state == "validated":
  279. raise UserError(
  280. _("The sheet has already been validated and can't be edited.")
  281. )
  282. def on_barcode_scanned(self, barcode):
  283. if self.env.user.has_group(
  284. "beesdoo_shift_attendance.group_shift_attendance"
  285. ):
  286. raise UserError(
  287. _(
  288. "You must be logged as 'Attendance Sheet Generic Access' "
  289. " if you want to scan cards."
  290. )
  291. )
  292. if self.state == "validated":
  293. raise UserError(
  294. _("A validated attendance sheet can't be modified")
  295. )
  296. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  297. if not len(worker):
  298. raise UserError(
  299. _(
  300. "Worker not found (invalid barcode or status). \nBarcode : %s"
  301. )
  302. % barcode
  303. )
  304. if len(worker) > 1:
  305. raise UserError(
  306. _(
  307. "Multiple workers are corresponding this barcode. \nBarcode : %s"
  308. )
  309. % barcode
  310. )
  311. if worker.state == "unsubscribed":
  312. shift_counter = (
  313. worker.cooperative_status_ids.sc
  314. + worker.cooperative_status_ids.sr
  315. )
  316. raise UserError(
  317. _(
  318. "Beware, your account is frozen because your shift counter "
  319. "is at %s. Please contact Members Office to unfreeze it. "
  320. "If you want to attend this shift, your supercoop "
  321. "can write your name in the notes field during validation."
  322. )
  323. % shift_counter
  324. )
  325. if worker.state == "resigning":
  326. raise UserError(
  327. _(
  328. "Beware, you are recorded as resigning. "
  329. "Please contact member's office if this is incorrect. Thank you."
  330. )
  331. )
  332. if worker.working_mode not in ("regular", "irregular"):
  333. raise UserError(
  334. _(
  335. "%s's working mode is %s and should be regular or irregular."
  336. )
  337. % (worker.name, worker.working_mode)
  338. )
  339. # Expected shifts status update
  340. for id_ in self.expected_shift_ids.ids:
  341. shift = self.env["beesdoo.shift.sheet.expected"].browse(id_)
  342. if (
  343. shift.worker_id == worker and not shift.replaced_id
  344. ) or shift.replaced_id == worker:
  345. shift.state = "done"
  346. return
  347. if shift.worker_id == worker and shift.replaced_id:
  348. raise UserError(
  349. _("%s is registered as replaced.") % worker.name
  350. )
  351. is_compensation = worker.working_mode == "regular"
  352. added_ids = [s.worker_id.id for s in self.added_shift_ids]
  353. if worker.id not in added_ids:
  354. # Added shift creation
  355. self.added_shift_ids |= self.added_shift_ids.new(
  356. {
  357. "task_type_id": self.added_shift_ids.pre_filled_task_type_id(),
  358. "state": "done",
  359. "attendance_sheet_id": self._origin.id,
  360. "worker_id": worker.id,
  361. "is_compensation": is_compensation,
  362. }
  363. )
  364. @api.model
  365. def create(self, vals):
  366. new_sheet = super(AttendanceSheet, self).create(vals)
  367. # Creation and addition of the expected shifts corresponding
  368. # to the time range
  369. tasks = self.env["beesdoo.shift.shift"]
  370. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  371. # Fix issues with equality check on datetime
  372. # by searching on a small intervall instead
  373. delta = timedelta(minutes=1)
  374. tasks = tasks.search(
  375. [
  376. ("start_time", ">", new_sheet.start_time - delta),
  377. ("start_time", "<", new_sheet.start_time + delta),
  378. ("end_time", ">", new_sheet.end_time - delta),
  379. ("end_time", "<", new_sheet.end_time + delta),
  380. ]
  381. )
  382. workers = []
  383. for task in tasks:
  384. # Only one shift is added if multiple similar exist
  385. if (
  386. task.worker_id
  387. and task.worker_id not in workers
  388. and (task.state != "cancel")
  389. ):
  390. expected_shift.create(
  391. {
  392. "attendance_sheet_id": new_sheet.id,
  393. "task_id": task.id,
  394. "worker_id": task.worker_id.id,
  395. "replaced_id": task.replaced_id.id,
  396. "task_type_id": task.task_type_id.id,
  397. "state": "absent_2",
  398. "working_mode": task.working_mode,
  399. "is_compensation": task.is_compensation,
  400. }
  401. )
  402. workers.append(task.worker_id)
  403. # Maximum number of workers calculation (count empty shifts)
  404. new_sheet.max_worker_no = len(tasks)
  405. return new_sheet
  406. @api.multi
  407. def button_mark_as_read(self):
  408. if self.is_read:
  409. raise UserError(_("The sheet has already been marked as read."))
  410. self.is_read = True
  411. def _validate(self, user):
  412. self.ensure_one()
  413. if self.state == "validated":
  414. raise UserError(_("The sheet has already been validated."))
  415. # Expected shifts status update
  416. for expected_shift in self.expected_shift_ids:
  417. actual_shift = expected_shift.task_id
  418. actual_shift.replaced_id = expected_shift.replaced_id
  419. actual_shift.state = expected_shift.state
  420. if expected_shift.state == "done":
  421. self.attended_worker_no += 1
  422. if expected_shift.state != "done":
  423. mail_template = self.env.ref(
  424. "beesdoo_shift_attendance.email_template_non_attendance",
  425. 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. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  431. is_compensation = added_shift.is_compensation
  432. # Edit a non-assigned shift or create one if none
  433. # Fix issues with equality check on datetime
  434. # by searching on a small intervall instead
  435. delta = timedelta(minutes=1)
  436. non_assigned_shifts = self.env["beesdoo.shift.shift"].search(
  437. [
  438. ("worker_id", "=", False),
  439. ("start_time", ">", self.start_time - delta),
  440. ("start_time", "<", self.start_time + delta),
  441. ("end_time", ">", self.end_time - delta),
  442. ("end_time", "<", self.end_time + delta),
  443. ("task_type_id", "=", added_shift.task_type_id.id),
  444. ],
  445. limit=1,
  446. )
  447. if len(non_assigned_shifts):
  448. actual_shift = non_assigned_shifts[0]
  449. else:
  450. actual_shift = self.env["beesdoo.shift.shift"].create(
  451. {
  452. "name": _("%s (added)" % self.name),
  453. "task_type_id": added_shift.task_type_id.id,
  454. "start_time": self.start_time,
  455. "end_time": self.end_time,
  456. }
  457. )
  458. actual_shift.write(
  459. {
  460. "state": added_shift.state,
  461. "worker_id": added_shift.worker_id.id,
  462. "is_regular": not is_compensation and is_regular_worker,
  463. "is_compensation": is_compensation and is_regular_worker,
  464. }
  465. )
  466. added_shift.task_id = actual_shift.id
  467. if actual_shift.state == "done":
  468. self.attended_worker_no += 1
  469. self.validated_by = user
  470. self.state = "validated"
  471. return
  472. @api.multi
  473. def validate_with_checks(self):
  474. self.ensure_one()
  475. if self.state == "validated":
  476. raise UserError(_("The sheet has already been validated."))
  477. if self.start_time > datetime.now():
  478. raise UserError(
  479. _(
  480. "Attendance sheet can only be validated once the shifts have started."
  481. )
  482. )
  483. # Fields validation
  484. for added_shift in self.added_shift_ids:
  485. if not added_shift.worker_id:
  486. raise UserError(
  487. _("Worker name is missing for an added shift.")
  488. )
  489. if added_shift.state != "done":
  490. raise UserError(
  491. _("Shift State is missing or wrong for %s")
  492. % added_shift.worker_id.name
  493. )
  494. if not added_shift.task_type_id:
  495. raise UserError(
  496. _("Task Type is missing for %s")
  497. % added_shift.worker_id.name
  498. )
  499. if not added_shift.working_mode:
  500. raise UserError(
  501. _("Working mode is missing for %s")
  502. % added_shift.worker_id.name
  503. )
  504. if added_shift.working_mode not in ["regular", "irregular"]:
  505. raise UserError(
  506. _("Warning : Working mode for %s is %s")
  507. % (
  508. added_shift.worker_id.name,
  509. added_shift.worker_id.working_mode,
  510. )
  511. )
  512. for expected_shift in self.expected_shift_ids:
  513. if not expected_shift.state:
  514. raise UserError(
  515. _("Shift State is missing for %s")
  516. % expected_shift.worker_id.name
  517. )
  518. if (
  519. expected_shift.state == "absent"
  520. and not expected_shift.compensation_no
  521. ):
  522. raise UserError(
  523. _("Compensation number is missing for %s")
  524. % expected_shift.worker_id.name
  525. )
  526. # Open a validation wizard only if not admin
  527. if self.env.user.has_group(
  528. "beesdoo_shift_attendance.group_shift_attendance_sheet_validation"
  529. ):
  530. if not self.worker_nb_feedback:
  531. raise UserError(
  532. _("Please give your feedback about the number of workers.")
  533. )
  534. self._validate(self.env.user.partner_id)
  535. return
  536. return {
  537. "type": "ir.actions.act_window",
  538. "res_model": "beesdoo.shift.sheet.validate",
  539. "view_type": "form",
  540. "view_mode": "form",
  541. "target": "new",
  542. }
  543. @api.model
  544. def _generate_attendance_sheet(self):
  545. """
  546. Generate sheets with shifts in the time interval
  547. defined from corresponding CRON time interval.
  548. """
  549. tasks = self.env["beesdoo.shift.shift"]
  550. sheets = self.env["beesdoo.shift.sheet"]
  551. current_time = datetime.now()
  552. generation_interval_setting = int(
  553. self.env["ir.config_parameter"]
  554. .sudo()
  555. .get_param(
  556. "beesdoo_shift_attendance.attendance_sheet_generation_interval"
  557. )
  558. )
  559. allowed_time_range = timedelta(minutes=generation_interval_setting)
  560. tasks = tasks.search(
  561. [
  562. ("start_time", ">", str(current_time)),
  563. ("start_time", "<", str(current_time + allowed_time_range)),
  564. ]
  565. )
  566. for task in tasks:
  567. start_time = task.start_time
  568. end_time = task.end_time
  569. sheets = sheets.search(
  570. [("start_time", "=", start_time), ("end_time", "=", end_time)]
  571. )
  572. if not sheets:
  573. sheet = sheets.create(
  574. {"start_time": start_time, "end_time": end_time}
  575. )
  576. @api.model
  577. def _cron_non_validated_sheets(self):
  578. sheets = self.env["beesdoo.shift.sheet"]
  579. non_validated_sheets = sheets.search(
  580. [
  581. ("day", "=", date.today() - timedelta(days=1)),
  582. ("state", "=", "not_validated"),
  583. ]
  584. )
  585. if non_validated_sheets:
  586. mail_template = self.env.ref(
  587. "beesdoo_shift_attendance.email_template_non_validated_sheet",
  588. False,
  589. )
  590. for rec in non_validated_sheets:
  591. mail_template.send_mail(rec.id, True)