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.

583 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. default_task_type = self.env[
  270. "beesdoo.shift.sheet.expected"
  271. ].default_task_type_id()
  272. shift = self.expected_shift_ids.search(
  273. [
  274. ("task_type_id", "=", default_task_type.id),
  275. ("super_coop_id", "!=", False),
  276. ],
  277. limit=1,
  278. )
  279. self.default_super_coop_id = shift.super_coop_id
  280. # Is this method necessary ?
  281. @api.depends("annotation")
  282. def _compute_is_annotated(self):
  283. if self.annotation:
  284. self.is_annotated = len(self.annotation) != 0
  285. return
  286. @api.model
  287. def create(self, vals):
  288. new_sheet = super(AttendanceSheet, self).create(vals)
  289. # Creation and addition of the expected shifts corresponding
  290. # to the time range
  291. tasks = self.env["beesdoo.shift.shift"]
  292. tasks = tasks.search(
  293. [
  294. ("start_time", "=", new_sheet.start_time),
  295. ("end_time", "=", new_sheet.end_time),
  296. ]
  297. )
  298. expected_shift = self.env["beesdoo.shift.sheet.expected"]
  299. task_templates = set()
  300. for task in tasks:
  301. if task.working_mode == "irregular":
  302. stage = "absent_1"
  303. else:
  304. stage = "absent_2"
  305. if task.worker_id:
  306. new_expected_shift = expected_shift.create(
  307. {
  308. "attendance_sheet_id": new_sheet.id,
  309. "task_id": task.id,
  310. "worker_id": task.worker_id.id,
  311. "replacement_worker_id": task.replaced_id.id,
  312. "task_type_id": task.task_type_id.id,
  313. "super_coop_id": task.super_coop_id.id,
  314. "stage": stage,
  315. "working_mode": task.working_mode,
  316. }
  317. )
  318. task_templates.add(task.task_template_id)
  319. # Maximum number of workers calculation
  320. new_sheet.max_worker_no = sum(r.worker_nb for r in task_templates)
  321. return new_sheet
  322. # Workaround to display notifications only for unread and not validated
  323. # sheets, via a check on domain.
  324. @api.model
  325. def _needaction_count(self, domain=None):
  326. if domain == [
  327. ("is_annotated", "=", True),
  328. ("is_read", "=", False),
  329. ] or domain == [("state", "=", "not_validated")]:
  330. return self.search_count(domain)
  331. return
  332. def validate(self):
  333. self.ensure_one()
  334. if self.state == "validated":
  335. raise UserError("The sheet has already been validated.")
  336. shift = self.env["beesdoo.shift.shift"]
  337. stage = self.env["beesdoo.shift.stage"]
  338. # Fields validation
  339. for added_shift in self.added_shift_ids:
  340. if not added_shift.worker_id:
  341. raise UserError(
  342. _("Worker must be set for shift %s") % added_shift.id
  343. )
  344. if not added_shift.stage:
  345. raise UserError(
  346. _("Shift Stage is missing for %s")
  347. % added_shift.worker_id.name
  348. )
  349. if not added_shift.task_type_id:
  350. raise UserError(
  351. _("Task Type is missing for %s")
  352. % added_shift.worker_id.name
  353. )
  354. if not added_shift.working_mode:
  355. raise UserError(
  356. _("Working mode is missing for %s")
  357. % added_shift.worker_id.name
  358. )
  359. if (
  360. added_shift.worker_id.working_mode == "regular"
  361. and not added_shift.regular_task_type
  362. ):
  363. raise UserError(
  364. _("Regular Task Type is missing for %s")
  365. % added_shift.worker_id.name
  366. )
  367. for expected_shift in self.expected_shift_ids:
  368. if not expected_shift.stage:
  369. raise UserError(
  370. _("Shift Stage is missing for %s")
  371. % expected_shift.worker_id.name
  372. )
  373. # Expected shifts status update
  374. for expected_shift in self.expected_shift_ids:
  375. actual_shift = expected_shift.task_id
  376. # We get stage record corresponding to mapped stage id
  377. actual_stage = self.env.ref(
  378. "beesdoo_shift.%s" % expected_shift.get_actual_stage()
  379. )
  380. # If the actual stage has been deleted, the sheet is still validated.
  381. # Raising an exception would stop this but would prevent validation.
  382. # How can we show a message without stopping validation ?
  383. if actual_stage:
  384. actual_shift.stage_id = actual_stage
  385. actual_shift.replaced_id = expected_shift.replacement_worker_id
  386. # Added shifts status update
  387. for added_shift in self.added_shift_ids:
  388. actual_stage = self.env.ref(
  389. "beesdoo_shift.%s" % added_shift.get_actual_stage()
  390. )
  391. is_regular_worker = added_shift.worker_id.working_mode == "regular"
  392. is_regular_shift = added_shift.regular_task_type == "normal"
  393. # Add an annotation if a regular worker is doing its regular shift
  394. if is_regular_shift and is_regular_worker:
  395. self.annotation += (
  396. _(
  397. "\n\nWarning : %s attended its shift as a normal one but was not expected."
  398. " Something may be wrong in his/her personnal informations.\n"
  399. )
  400. % added_shift.worker_id.name
  401. )
  402. # Edit a non-assigned shift or create one if none
  403. non_assigned_shifts = shift.search(
  404. [
  405. ("worker_id", "=", False),
  406. ("start_time", "=", self.start_time),
  407. ("end_time", "=", self.end_time),
  408. ("task_type_id", "=", added_shift.task_type_id.id),
  409. ],
  410. limit=1,
  411. )
  412. if len(non_assigned_shifts):
  413. actual_shift = non_assigned_shifts[0]
  414. actual_shift.write(
  415. {
  416. "stage_id": actual_stage.id,
  417. "worker_id": added_shift.worker_id.id,
  418. "stage_id": actual_stage.id,
  419. "is_regular": is_regular_shift and is_regular_worker,
  420. "is_compensation": not is_regular_shift
  421. and is_regular_worker,
  422. }
  423. )
  424. else:
  425. actual_shift = self.env["beesdoo.shift.shift"].create(
  426. {
  427. "name": _("[Added Shift] %s") % self.start_time,
  428. "task_type_id": added_shift.task_type_id.id,
  429. "worker_id": added_shift.worker_id.id,
  430. "start_time": self.start_time,
  431. "end_time": self.end_time,
  432. "stage_id": actual_stage.id,
  433. "is_regular": is_regular_shift and is_regular_worker,
  434. "is_compensation": not is_regular_shift
  435. and is_regular_worker,
  436. }
  437. )
  438. added_shift.task_id = actual_shift.id
  439. self.state = "validated"
  440. return
  441. # @api.multi is needed to call the wizard, but doesn't match @api.one
  442. # from the validate() method
  443. @api.multi
  444. def validate_via_wizard(self):
  445. if self.env.user.has_group("beesdoo_shift.group_cooperative_admin"):
  446. self.validated_by = self.env.user.partner_id
  447. self.validate()
  448. return
  449. return {
  450. "type": "ir.actions.act_window",
  451. "res_model": "beesdoo.shift.sheet.validate",
  452. "view_type": "form",
  453. "view_mode": "form",
  454. "target": "new",
  455. }
  456. @api.model
  457. def _generate_attendance_sheet(self):
  458. """
  459. Generate sheets 20 minutes before current time.
  460. Corresponding CRON intervall time must be the same.
  461. Check if any task exists in the time intervall.
  462. If no sheet is already created, it is created.
  463. """
  464. time_ranges = set()
  465. tasks = self.env["beesdoo.shift.shift"]
  466. sheets = self.env["beesdoo.shift.sheet"]
  467. current_time = datetime.now()
  468. allowed_time_range = timedelta(minutes=20)
  469. tasks = tasks.search(
  470. [
  471. ("start_time", ">", str(current_time),),
  472. ("start_time", "<", str(current_time + allowed_time_range),),
  473. ]
  474. )
  475. for task in tasks:
  476. start_time = task.start_time
  477. end_time = task.end_time
  478. sheets = sheets.search(
  479. [("start_time", "=", start_time), ("end_time", "=", end_time),]
  480. )
  481. if not sheets:
  482. sheet = sheets.create(
  483. {"start_time": start_time, "end_time": end_time}
  484. )
  485. def on_barcode_scanned(self, barcode):
  486. if self.state == "validated":
  487. raise UserError(
  488. _("You cannot modify a validated attendance sheet.")
  489. )
  490. worker = self.env["res.partner"].search([("barcode", "=", barcode)])
  491. if not len(worker):
  492. raise UserError(_("Worker not found (invalid barcode or status)."))
  493. if len(worker) > 1:
  494. raise UserError(
  495. _("Multiple workers are corresponding this barcode.")
  496. )
  497. if worker.state in ("unsubscribed", "resigning"):
  498. raise UserError(_("Worker is %s.") % worker.state)
  499. if worker.working_mode not in ("regular", "irregular"):
  500. raise UserError(
  501. _("Worker is %s and should be regular or irregular.")
  502. % worker.working_mode
  503. )
  504. for id in self.expected_shift_ids.ids:
  505. shift = self.env["beesdoo.shift.sheet.expected"].browse(id)
  506. if (
  507. shift.worker_id == worker
  508. or shift.replacement_worker_id == worker
  509. ):
  510. shift.stage = "present"
  511. return
  512. if worker.working_mode == "regular":
  513. regular_task_type = "normal"
  514. else:
  515. regular_task_type = False
  516. added_ids = map(lambda s: s.worker_id.id, self.added_shift_ids)
  517. if worker.id in added_ids:
  518. raise UserError(_("Worker is already present."))
  519. self.added_shift_ids |= self.added_shift_ids.new(
  520. {
  521. "task_type_id": self.added_shift_ids.default_task_type_id(),
  522. "stage": "present",
  523. "attendance_sheet_id": self._origin.id,
  524. "worker_id": worker.id,
  525. "regular_task_type": regular_task_type,
  526. }
  527. )