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.

625 lines
21 KiB

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