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.

584 lines
20 KiB

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