|
| 1 | +# Copyright 2024 KMEE |
| 2 | +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). |
| 3 | + |
| 4 | +import ast |
| 5 | +import json as simplejson |
| 6 | + |
| 7 | +from odoo import _, api, models |
| 8 | +from odoo.exceptions import UserError |
| 9 | + |
| 10 | + |
| 11 | +class ProjectTask(models.Model): |
| 12 | + |
| 13 | + _inherit = "project.task" |
| 14 | + |
| 15 | + @api.model |
| 16 | + def _get_view(self, view_id=None, view_type="form", **options): |
| 17 | + arch, view = super()._get_view(view_id, view_type, **options) |
| 18 | + stages = self.env["project.task.type"].search( |
| 19 | + [("required_field_ids", "!=", False)] |
| 20 | + ) |
| 21 | + if view.type == "form" and stages: |
| 22 | + for field in stages.mapped("required_field_ids"): |
| 23 | + stages_with_field = stages.filtered( |
| 24 | + lambda stage, field=field: field in stage.required_field_ids |
| 25 | + ) |
| 26 | + for node in arch.xpath("//field[@name='%s']" % field.name): |
| 27 | + attrs = ast.literal_eval(node.attrib.get("attrs", "{}")) |
| 28 | + if attrs: |
| 29 | + if attrs.get("required"): |
| 30 | + attrs["required"] = [ |
| 31 | + "|", |
| 32 | + ("stage_id", "in", stages_with_field.ids), |
| 33 | + ] + attrs["required"] |
| 34 | + else: |
| 35 | + attrs["required"] = [ |
| 36 | + ("stage_id", "in", stages_with_field.ids) |
| 37 | + ] |
| 38 | + else: |
| 39 | + attrs["required"] = [("stage_id", "in", stages_with_field.ids)] |
| 40 | + node.set("attrs", simplejson.dumps(attrs)) |
| 41 | + return arch, view |
| 42 | + |
| 43 | + @api.model |
| 44 | + def _get_view_cache_key(self, view_id=None, view_type="form", **options): |
| 45 | + """The override of _get_view changing the required fields labels according |
| 46 | + to the stage makes the view cache dependent on the stages with required fields.""" |
| 47 | + key = super()._get_view_cache_key(view_id, view_type, **options) |
| 48 | + return key + tuple( |
| 49 | + self.env["project.task.type"] |
| 50 | + .search([("required_field_ids", "!=", False)]) |
| 51 | + .mapped("required_field_ids.name") |
| 52 | + ) |
| 53 | + |
| 54 | + @api.constrains("stage_id") |
| 55 | + def _check_stage_id_(self): |
| 56 | + for rec in self: |
| 57 | + stage = self.env["project.task.type"].search([("id", "=", rec.stage_id.id)]) |
| 58 | + for s in stage: |
| 59 | + fields = ( |
| 60 | + self.env["ir.model.fields"] |
| 61 | + .sudo() |
| 62 | + .search([("id", "in", s.required_field_ids.ids)]) |
| 63 | + ) |
| 64 | + for field in fields: |
| 65 | + if hasattr(self, "%s" % field.name): |
| 66 | + if not getattr(self, "%s" % field.name): |
| 67 | + raise UserError( |
| 68 | + _( |
| 69 | + "Field '%(field)s' is mandatory in stage '%(stage)s'." |
| 70 | + ) |
| 71 | + % ( |
| 72 | + { |
| 73 | + "field": field.display_name.split(" (")[0], |
| 74 | + "stage": s.display_name, |
| 75 | + } |
| 76 | + ) |
| 77 | + ) |
0 commit comments