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.

574 lines
20 KiB

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