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.

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