|
| 1 | +# Copyright 2024 Camptocamp SA |
| 2 | +# @author Simone Orsi <simahawk@gmail.com> |
| 3 | +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). |
| 4 | + |
| 5 | +import datetime |
| 6 | + |
| 7 | +import pytz |
| 8 | + |
| 9 | +from odoo import _, api, exceptions, fields, models |
| 10 | +from odoo.tools import DotDict, safe_eval |
| 11 | + |
| 12 | + |
| 13 | +def date_to_datetime(dt): |
| 14 | + """Convert date to datetime.""" |
| 15 | + if isinstance(dt, datetime.date): |
| 16 | + return datetime.datetime.combine(dt, datetime.datetime.min.time()) |
| 17 | + return dt |
| 18 | + |
| 19 | + |
| 20 | +def to_utc(dt): |
| 21 | + """Convert date or datetime to UTC.""" |
| 22 | + # Gracefully convert to datetime if needed 1st |
| 23 | + return date_to_datetime(dt).astimezone(pytz.UTC) |
| 24 | + |
| 25 | + |
| 26 | +class EdiConfiguration(models.Model): |
| 27 | + _name = "edi.configuration" |
| 28 | + _description = """ |
| 29 | + This model is used to configure EDI (Electronic Data Interchange) flows. |
| 30 | + It allows users to create their own configurations, which can be tailored |
| 31 | + to meet the specific needs of their business processes. |
| 32 | + """ |
| 33 | + |
| 34 | + name = fields.Char(string="Name", required=True) |
| 35 | + active = fields.Boolean(default=True) |
| 36 | + code = fields.Char(required=True, copy=False, index=True, unique=True) |
| 37 | + description = fields.Char(help="Describe what the conf is for") |
| 38 | + backend_id = fields.Many2one(string="Backend", comodel_name="edi.backend") |
| 39 | + # Field `type_id` is not a mandatory field because we will create 2 common confs |
| 40 | + # for EDI (`send_via_email` and `send_via_edi`). So type_id is |
| 41 | + # a mandatory field will create unwanted data for users when installing this module. |
| 42 | + type_id = fields.Many2one( |
| 43 | + string="Exchange Type", |
| 44 | + comodel_name="edi.exchange.type", |
| 45 | + ondelete="cascade", |
| 46 | + auto_join=True, |
| 47 | + index=True, |
| 48 | + ) |
| 49 | + model_id = fields.Many2one( |
| 50 | + "ir.model", |
| 51 | + string="Model", |
| 52 | + help="Model the conf applies to. Leave blank to apply for all models", |
| 53 | + ) |
| 54 | + model_name = fields.Char(related="model_id.model", store=True) |
| 55 | + trigger = fields.Selection( |
| 56 | + # The selections below are intended to assist with basic operations |
| 57 | + # and are used to setup common configuration. |
| 58 | + [ |
| 59 | + ("on_record_write", "Update Record"), |
| 60 | + ("on_record_create", "Create Record"), |
| 61 | + ("on_send_via_email", "Send Via Email"), |
| 62 | + ("on_send_via_edi", "Send Via EDI"), |
| 63 | + ("disabled", "Disabled"), |
| 64 | + ], |
| 65 | + string="Trigger", |
| 66 | + # The default selection will be disabled. |
| 67 | + # which would allow to keep the conf visible but disabled. |
| 68 | + required=True, |
| 69 | + default="disabled", |
| 70 | + ondelete="on default", |
| 71 | + ) |
| 72 | + snippet_before_do = fields.Text( |
| 73 | + string="Snippet Before Do", |
| 74 | + help="Snippet to validate the state and collect records to do", |
| 75 | + ) |
| 76 | + snippet_do = fields.Text( |
| 77 | + string="Snippet Do", |
| 78 | + help="""Used to do something specific here. |
| 79 | + Receives: operation, edi_action, vals, old_vals.""", |
| 80 | + ) |
| 81 | + |
| 82 | + @api.constrains("backend_id", "type_id") |
| 83 | + def _constrains_backend(self): |
| 84 | + for rec in self: |
| 85 | + if rec.type_id.backend_id: |
| 86 | + if rec.type_id.backend_id != rec.backend_id: |
| 87 | + raise exceptions.ValidationError( |
| 88 | + _("Backend must match with exchange type's backend!") |
| 89 | + ) |
| 90 | + else: |
| 91 | + if rec.type_id.backend_type_id != rec.backend_id.backend_type_id: |
| 92 | + raise exceptions.ValidationError( |
| 93 | + _("Backend type must match with exchange type's backend type!") |
| 94 | + ) |
| 95 | + |
| 96 | + # TODO: This function is also available in `edi_exchange_template`. |
| 97 | + # Consider adding this to util or mixin |
| 98 | + def _code_snippet_valued(self, snippet): |
| 99 | + snippet = snippet or "" |
| 100 | + return bool( |
| 101 | + [ |
| 102 | + not line.startswith("#") |
| 103 | + for line in (snippet.splitlines()) |
| 104 | + if line.strip("") |
| 105 | + ] |
| 106 | + ) |
| 107 | + |
| 108 | + @staticmethod |
| 109 | + def _date_to_string(dt, utc=True): |
| 110 | + if not dt: |
| 111 | + return "" |
| 112 | + if utc: |
| 113 | + dt = to_utc(dt) |
| 114 | + return fields.Date.to_string(dt) |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def _datetime_to_string(dt, utc=True): |
| 118 | + if not dt: |
| 119 | + return "" |
| 120 | + if utc: |
| 121 | + dt = to_utc(dt) |
| 122 | + return fields.Datetime.to_string(dt) |
| 123 | + |
| 124 | + def _time_utils(self): |
| 125 | + return { |
| 126 | + "datetime": safe_eval.datetime, |
| 127 | + "dateutil": safe_eval.dateutil, |
| 128 | + "time": safe_eval.time, |
| 129 | + "utc_now": fields.Datetime.now(), |
| 130 | + "date_to_string": self._date_to_string, |
| 131 | + "datetime_to_string": self._datetime_to_string, |
| 132 | + "time_to_string": lambda dt: dt.strftime("%H:%M:%S") if dt else "", |
| 133 | + "first_of": fields.first, |
| 134 | + } |
| 135 | + |
| 136 | + def _get_code_snippet_eval_context(self): |
| 137 | + """Prepare the context used when evaluating python code |
| 138 | +
|
| 139 | + :returns: dict -- evaluation context given to safe_eval |
| 140 | + """ |
| 141 | + ctx = { |
| 142 | + "uid": self.env.uid, |
| 143 | + "user": self.env.user, |
| 144 | + "DotDict": DotDict, |
| 145 | + "conf": self, |
| 146 | + } |
| 147 | + ctx.update(self._time_utils()) |
| 148 | + return ctx |
| 149 | + |
| 150 | + def _evaluate_code_snippet(self, snippet, **render_values): |
| 151 | + if not self._code_snippet_valued(snippet): |
| 152 | + return {} |
| 153 | + eval_ctx = dict(render_values, **self._get_code_snippet_eval_context()) |
| 154 | + safe_eval.safe_eval(snippet, eval_ctx, mode="exec", nocopy=True) |
| 155 | + result = eval_ctx.get("result", {}) |
| 156 | + if not isinstance(result, dict): |
| 157 | + return {} |
| 158 | + return result |
| 159 | + |
| 160 | + def edi_exec_snippet_before_do(self, record, **kwargs): |
| 161 | + self.ensure_one() |
| 162 | + # Execute snippet before do |
| 163 | + vals_before_do = self._evaluate_code_snippet( |
| 164 | + self.snippet_before_do, record=record, **kwargs |
| 165 | + ) |
| 166 | + |
| 167 | + # Prepare data |
| 168 | + vals = { |
| 169 | + "todo": vals_before_do.get("todo", True), |
| 170 | + "snippet_do_vars": vals_before_do.get("snippet_do_vars", False), |
| 171 | + "event_only": vals_before_do.get("event_only", False), |
| 172 | + "tracked_fields": vals_before_do.get("tracked_fields", False), |
| 173 | + "edi_action": vals_before_do.get("edi_action", False), |
| 174 | + } |
| 175 | + return vals |
| 176 | + |
| 177 | + def edi_exec_snippet_do(self, record, **kwargs): |
| 178 | + self.ensure_one() |
| 179 | + if self.trigger == "disabled": |
| 180 | + return False |
| 181 | + |
| 182 | + old_value = kwargs.get("old_vals", {}).get(record.id, {}) |
| 183 | + new_value = kwargs.get("vals", {}).get(record.id, {}) |
| 184 | + vals = { |
| 185 | + "todo": True, |
| 186 | + "record": record, |
| 187 | + "operation": kwargs.get("operation", False), |
| 188 | + "edi_action": kwargs.get("edi_action", False), |
| 189 | + "old_value": old_value, |
| 190 | + "vals": new_value, |
| 191 | + } |
| 192 | + if self.snippet_before_do: |
| 193 | + before_do_vals = self.edi_exec_snippet_before_do(record, **kwargs) |
| 194 | + vals.update(before_do_vals) |
| 195 | + if vals["todo"]: |
| 196 | + return self._evaluate_code_snippet(self.snippet_do, **vals) |
| 197 | + return True |
| 198 | + |
| 199 | + def edi_get_conf(self, trigger, backend=None): |
| 200 | + domain = [("trigger", "=", trigger)] |
| 201 | + if backend: |
| 202 | + domain.append(("backend_id", "=", backend.id)) |
| 203 | + else: |
| 204 | + # We will only get confs that have backend_id = False |
| 205 | + # or are equal to self.type_id.backend_id.id |
| 206 | + backend_ids = self.mapped("type_id.backend_id.id") |
| 207 | + backend_ids.append(False) |
| 208 | + domain.append(("backend_id", "in", backend_ids)) |
| 209 | + return self.filtered_domain(domain) |
0 commit comments