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.

656 lines
22 KiB

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