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.

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