-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
source_mixin.py
193 lines (156 loc) · 6.4 KB
/
source_mixin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Author: Simone Orsi
# Copyright 2018 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models, tools
from ...utils.import_utils import gen_chunks
class ImportSourceConsumerMixin(models.AbstractModel):
"""Source consumer mixin.
Inheriting models can setup, configure and use import sources.
Relation towards source records is generic to grant maximum freedom
on which source type to use.
"""
_name = "import.source.consumer.mixin"
_description = "Import source consumer"
source_id = fields.Integer(string="Source ID", required=False, ondelete="cascade")
source_model = fields.Selection(
string="Source type", selection="_selection_source_ref_id"
)
source_ref_id = fields.Reference(
string="Source",
compute="_compute_source_ref_id",
selection="_selection_source_ref_id",
# NOTE: do not store a computed fields.Reference, Odoo crashes
# with an error message "Mixing appels and orange..." when performing
# a self.recompute() on such fields.
store=False,
)
source_config_summary = fields.Html(
compute="_compute_source_config_summary", readonly=True
)
@api.depends("source_model", "source_id")
def _compute_source_ref_id(self):
for item in self:
item.source_ref_id = False
if not item.source_id or not item.source_model:
continue
item.source_ref_id = "{0.source_model},{0.source_id}".format(item)
@api.model
@tools.ormcache("self")
def _selection_source_ref_id(self):
return [("import.source.csv", "CSV"), ("import.source.csv.std", "Odoo CSV")]
@api.depends("source_ref_id")
def _compute_source_config_summary(self):
for item in self:
item.source_config_summary = False
if not item.source_ref_id:
continue
item.source_config_summary = item.source_ref_id.config_summary
def open_source_config(self):
self.ensure_one()
action = self.env[self.source_model].get_formview_action()
action.update(
{
"views": [(self.env[self.source_model].get_config_view_id(), "form")],
"res_id": self.source_id,
"target": "new",
}
)
return action
def get_source(self):
"""Return the source to the consumer."""
return self.source_ref_id
class ImportSource(models.AbstractModel):
"""Define a source for an import.
A source model is responsible for:
* storing specific settings (chunk size, source params, etc)
* retrieve source lines (connect to an external service, or db or read CSV)
* yield lines in chunks
* display configuration summary on the recordset (via config summary)
* optionally, provide a reporter to create an extensive report for users.
"""
_name = "import.source"
_description = "Import source"
_source_type = "none"
_reporter_model = ""
name = fields.Char(compute="_compute_name", readony=True)
chunk_size = fields.Integer(required=True, default=500, string="Chunks Size")
config_summary = fields.Html(compute="_compute_config_summary", readonly=True)
# tmpl that renders configuration summary
_config_summary_template = "connector_importer.source_config_summary"
def _compute_name(self):
self.name = self._source_type
@property
def _config_summary_fields(self):
"""Fields automatically included in the summary.
Override it to add your custom fields automatically to the summary.
"""
return ["chunk_size"]
@api.depends()
def _compute_config_summary(self):
"""Generate configuration summary HTML.
Configurations parameters can vary depending on the kind of source.
To display meaningful information on the recordset
w/out hacking the recordset view each time
we generate a short HTML summary.
For instance, if you are connecting to an external db
you might want to show DSN, if you are loading a CSV
you might want to show delimiter, quotechar and so on.
To add your fields automatically to the summary,
just override `_config_summary_fields`.
They'll be automatically included in the summary.
"""
template = self.env.ref(self._config_summary_template)
for item in self:
item.config_summary = template.render(item._config_summary_data())
def _config_summary_data(self):
"""Collect data for summary."""
info = []
for fname in self._config_summary_fields:
info.append((fname, self[fname]))
return {
"source": self,
"summary_fields": self._config_summary_fields,
"fields_info": self.fields_get(self._config_summary_fields),
}
@api.model
def create(self, vals):
"""Override to update reference to source on the consumer."""
res = super().create(vals)
if self.env.context.get("active_model"):
# update reference on consumer
self.env[self.env.context["active_model"]].browse(
self.env.context["active_id"]
).source_id = res.id
return res
def get_lines(self):
"""Retrieve lines to import."""
self.ensure_one()
# retrieve lines
lines = self._get_lines()
# sort them
lines_sorted = self._sort_lines(lines)
# no chunk size means no chunk of lines
if not self.chunk_size:
yield list(lines)
for _i, chunk in enumerate(gen_chunks(lines_sorted, chunksize=self.chunk_size)):
# get out of chunk iterator
yield list(chunk)
def _get_lines(self):
"""Your duty here..."""
raise NotImplementedError()
def _sort_lines(self, lines):
"""Override to customize sorting."""
return lines
def get_config_view_id(self):
"""Retrieve configuration view."""
return (
self.env["ir.ui.view"]
.search([("model", "=", self._name), ("type", "=", "form")], limit=1)
.id
)
def get_reporter(self):
"""Retrieve a specific reporter for this source.
A report can be used to produce and extensive report for the end user.
See `reporter` models.
"""
return self.env.get(self._reporter_model)