-
Notifications
You must be signed in to change notification settings - Fork 5
/
MetaAnalytic.py
565 lines (462 loc) · 21.7 KB
/
MetaAnalytic.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
from openerp import SUPERUSER_ID
from openerp.osv import fields
from openerp.tools import config
from openerp.addons.oemetasl import OEMetaSL
class AddMethod(object):
"""Utility decorator to add methods to an object or a class."""
def __init__(self, obj):
self.obj = obj
def __call__(self, func):
setattr(self.obj, func.func_name, func)
return func
class MetaAnalytic(OEMetaSL):
"""Allow the model to use the classes of the analytic_structure module
in a more streamlined way.
The metaclass' behavior is specified by adding the following attributes:
* _analytic: define the analytic structures to be used by the model.
* _dimensions: bind an analytic dimension to the model.
A description of the syntax expected for each attribute is available in
the README file.
Notes:
* This metaclass may directly modify attributes that are used by OpenERP,
specifically _columns and _inherits.
* New superclasses are used to define or override methods, in order to
avoid interacting with OEMetaSL or the model's own method (re)definitions.
"""
def __new__(cls, name, bases, nmspc):
analytic = nmspc.get('_analytic', {})
para = nmspc.get('_para_analytic', {})
dimension = nmspc.get('_dimension', {})
columns = nmspc.get('_columns', None)
if columns is None:
columns = {}
nmspc['_columns'] = columns
defaults = nmspc.get('_defaults', None)
if defaults is None:
defaults = {}
nmspc['_defaults'] = defaults
orm_name = nmspc.get('_name', None)
if orm_name is None:
orm_name = nmspc.get('_inherit')
# Analytic fields should be defined in the _analytic attribute.
if analytic or para:
bases = cls._setup_analytic_fields(
analytic, para, columns, defaults, orm_name, name, bases, nmspc
)
# The bound dimension should be defined in the _dimension attribute.
if dimension:
bases = cls._setup_bound_dimension(
dimension, columns, defaults, orm_name, name, bases, nmspc
)
return super(MetaAnalytic, cls).__new__(cls, name, bases, nmspc)
def __init__(self, name, bases, nmspc):
return super(MetaAnalytic, self).__init__(name, bases, nmspc)
@classmethod
def _setup_analytic_fields(
cls, analytic, para, columns, defaults, orm_name, name, bases, nmspc
):
"""Generate analytic and para-analytic fields on the model."""
# If _analytic uses a shortcut, convert it into a prefix-model mapping.
if analytic is True:
analytic = {'a': orm_name.replace('.', '_')}
elif isinstance(analytic, basestring):
analytic = {'a': analytic}
# Create a field that will be used for replacement in the view
if analytic:
columns['analytic_dimensions'] = fields.function(
lambda self, cr, uid, ids, *a: {i: '' for i in ids},
string=u"Analytic Dimensions",
readonly=True,
store=False,
)
col_pattern = '{pre}{n}_{suf}'
size = int(config.get_misc('analytic', 'analytic_size', 5))
# Generate the fields directly into the _columns attribute.
all_analytic = []
for prefix, model_name in analytic.iteritems():
# Analytic fields
all_analytic.append((model_name, prefix, 'id'))
for n in xrange(1, size + 1):
col_name = col_pattern.format(pre=prefix, n=n, suf='id')
domain_field = 'nd_id.ns{n}_id.model_name'.format(n=n)
columns[col_name] = fields.many2one(
'analytic.code',
"Generated Analytic Field",
domain=[
(domain_field, '=', model_name),
('view_type', '=', False),
('disabled_per_company', '=', False),
],
track_visibility='onchange',
)
for key, value in para.iteritems():
# Para-analytic fields
prefix, suffix = key
model_name = value['model']
all_analytic.append((model_name, prefix, suffix))
if suffix == 'id':
raise ValueError("Para-analytic suffix cannot be 'id'")
field_type = value['type']
args = value['args']
kwargs = value['kwargs']
for n in xrange(1, size + 1):
col_name = col_pattern.format(pre=prefix, n=n, suf=suffix)
columns[col_name] = field_type(*args, **kwargs)
if 'default' in value:
defaults[col_name] = value['default']
# In order to preserve inheritance, possible overrides, and OEMetaSL's
# expected behavior, work on a new class that inherits the given bases,
# then make our model class inherit from this class.
superclass_name = '_{name}_SuperAnalytic'.format(name=name)
# Set _register to False in order to prevent its instantiation.
superclass = type(superclass_name, bases, {'_register': False})
@AddMethod(superclass)
def fields_get(
self, cr, uid, allfields=None, context=None, write_access=True
):
"""Override this method to rename analytic fields."""
res = super(superclass, self).fields_get(
cr, uid, allfields=allfields, context=context,
write_access=write_access
)
analytic_osv = self.pool.get('analytic.structure')
for model_name, prefix, suffix in all_analytic:
res = analytic_osv.analytic_fields_get(
cr, uid, model_name, res, prefix, suffix, context=context
)
return res
@AddMethod(superclass)
def fields_view_get(
self, cr, uid, view_id=None, view_type='form', context=None,
toolbar=False, submenu=False
):
"""Override this method to hide unused analytic fields."""
res = super(superclass, self).fields_view_get(
cr, uid, view_id=view_id, view_type=view_type, context=context,
toolbar=toolbar, submenu=submenu
)
analytic_osv = self.pool.get('analytic.structure')
for model_name, prefix, suffix in all_analytic:
res = analytic_osv.analytic_fields_view_get(
cr, uid, model_name, res, prefix, suffix, context=context
)
return res
return (superclass,)
@classmethod
def _setup_bound_dimension(
cls, dimension, columns, defaults, orm_name, name, bases, nmspc
):
"""Bind a dimension to the model, creating a code for each record."""
if dimension is True:
dimension = {}
elif isinstance(dimension, basestring):
dimension = {'name': dimension}
dimension_name = dimension.get('name', None)
if dimension_name is None:
dimension_name = nmspc.get('_description', False) or orm_name
column = dimension.get('column', 'analytic_id')
ref_module = dimension.get('ref_module', '')
ref_id = dimension.get('ref_id', None)
if ref_id is None:
ref_id = orm_name.replace('.', '_') + "_analytic_dimension_id"
# To use an inherited, renamed parent field, you have to give its name.
sync_parent = dimension.get('sync_parent', False)
if sync_parent is True:
sync_parent = nmspc.get('_parent_name', 'parent_id')
rel_name = dimension.get('rel_name', tuple())
if rel_name is True:
rel_name = u"Name"
if isinstance(rel_name, basestring):
rel_name = (rel_name, 'name')
rel_description = dimension.get('rel_description', tuple())
if rel_description is True:
rel_description = u"Description"
if isinstance(rel_description, basestring):
rel_description = (rel_description, 'description')
rel_active = dimension.get('rel_active', tuple())
if rel_active is True:
rel_active = u"Active"
if isinstance(rel_active, basestring):
rel_active = (rel_active, 'active')
rel_view_type = dimension.get('rel_view_type', tuple())
if rel_view_type is True:
rel_view_type = u"View type"
if isinstance(rel_view_type, basestring):
rel_view_type = (rel_view_type, 'view_type')
rel_disabled_per_company = dimension.get(
'rel_disabled_per_company', tuple()
)
if rel_disabled_per_company is True:
rel_disabled_per_company = u"Disabled in my company"
if isinstance(rel_disabled_per_company, basestring):
rel_disabled_per_company = (
rel_disabled_per_company, 'disabled_per_company'
)
# By default, only use inherits if we can be sure there is no conflict
# on the required fields 'name' and 'nd_id'.
# There can still be conflicts on analytic_code's optional fields.
use_inherits = dimension.get('use_inherits', None)
if use_inherits is None:
use_inherits = not (
any(col in columns for col in ('name', 'nd_id'))
or nmspc.get('_inherits', False)
or nmspc.get('_inherit', False)
)
use_code_name_methods = dimension.get('use_code_name_methods', False)
code_ref_ids = dimension.get('code_ref_ids', False)
if code_ref_ids is True:
code_ref_ids = ref_id
code_ref_module = dimension.get('code_ref_module', '')
if use_inherits:
inherits = nmspc.get('_inherits', {})
inherits['analytic.code'] = column
nmspc['_inherits'] = inherits
# Default column for the underlying analytic code.
if column not in columns:
columns[column] = fields.many2one(
'analytic.code',
u"Bound Analytic Code",
required=True,
ondelete='restrict'
)
rel_cols = [
cols for cols in [
rel_name + ('name', 'char', True, ''),
rel_description + ('description', 'char', False, ''),
rel_active + ('active', 'boolean', False, True),
rel_view_type + ('view_type', 'boolean', False, False),
] if len(cols) == 6
]
if rel_cols:
# NOT a method nor a class member. 'self' is the analytic_code OSV.
def _record_from_code_id(self, cr, uid, ids, context=None):
"""Get the entries to update from the modified codes."""
osv = self.pool.get(orm_name)
domain = [(column, 'in', ids)]
return osv.search(cr, uid, domain, context=context)
for string, model_col, code_col, dtype, req, default in rel_cols:
columns[model_col] = fields.related(
column,
code_col,
string=string,
type=dtype,
relation="analytic.code",
required=req,
store={
'analytic.code': (
_record_from_code_id,
[code_col],
10
)
}
)
if model_col not in defaults:
defaults[model_col] = default
# In order to preserve inheritance, possible overrides, and OEMetaSL's
# expected behavior, work on a new class that inherits the given bases,
# then make our model class inherit from this class.
superclass_name = '_{name}_SuperDimension'.format(name=name)
# Set _register to False in order to prevent its instantiation.
superclass = type(superclass_name, bases, {'_register': False})
@AddMethod(superclass)
def __init__(self, pool, cr):
"""Load or create the analytic dimension bound to the model."""
super(superclass, self).__init__(pool, cr)
data_osv = self.pool['ir.model.data']
try:
self._bound_dimension_id = data_osv.get_object_reference(
cr, SUPERUSER_ID, ref_module, ref_id
)[1]
except ValueError:
vals = {'name': dimension_name, 'validated': True}
self._bound_dimension_id = data_osv._update(
cr, SUPERUSER_ID, 'analytic.dimension', ref_module, vals,
xml_id=ref_id, noupdate=True
)
if code_ref_ids:
prefix = config.get_misc('analytic', 'code_ref_prefix', False)
# This function is called as a method and can be overridden.
@AddMethod(superclass)
def _generate_code_ref_id(self, cr, uid, ids, context=None):
data_osv = self.pool['ir.model.data']
records = self.browse(cr, uid, ids, context=None)
if not isinstance(records, list):
records = [records]
for record in records:
code = record[column]
code_ref_id_builder = [prefix] if prefix else []
if 'company_id' in record and record.company_id:
code_ref_id_builder.append(record.company_id.code)
code_ref_id_builder.append('ANC')
code_ref_id_builder.append(code_ref_ids)
code_ref_id_builder.append(code.name)
vals = {
'name': "_".join(code_ref_id_builder),
'module': code_ref_module,
'model': 'analytic.code',
'res_id': code.id,
}
data_osv.create(cr, uid, vals, context=context)
@AddMethod(superclass)
def create(self, cr, uid, vals, context=None):
"""Create the analytic code."""
code_vals = {}
if sync_parent:
cp = self._get_code_parent(cr, uid, vals, context=context)
if cp is not None:
code_vals['code_parent_id'] = cp
# Direct changes to the 'bound analytic code' field are ignored
# unless the 'force_code_id' context key is passed as True.
force_code_id = vals.pop(column, False)
if context and context.get('force_code_id', False) == True:
self._force_code(cr, uid, force_code_id, code_vals, context)
vals[column] = force_code_id
else:
if use_inherits:
code_vals.update(vals)
else:
code_vals['name'] = vals.get('name')
# OpenERP bug: related fields do not work properly on creation.
for rel in rel_cols:
model_col, code_col = rel[1:3]
if model_col in vals:
code_vals[code_col] = vals[model_col]
elif model_col in self._defaults:
code_vals[code_col] = self._defaults[model_col]
# We have to create the code separately, even with inherits.
code_osv = self.pool['analytic.code']
code_vals['nd_id'] = self._bound_dimension_id
code_id = code_osv.create(cr, uid, code_vals, context=context)
vals[column] = code_id
res = super(superclass, self).create(
cr, uid, vals, context=context
)
if code_ref_ids:
self._generate_code_ref_id(cr, uid, res, context=context)
return res
@AddMethod(superclass)
def write(self, cr, uid, ids, vals, context=None):
"""Update the analytic code's name if it is not inherited,
and its parent code if parent-child relations are synchronized.
"""
code_vals = {}
new = False
if not isinstance(ids, (list, tuple)):
ids = [ids]
if sync_parent:
cp = self._get_code_parent(cr, uid, vals, context=context)
if cp is not None:
code_vals['code_parent_id'] = cp
# Direct changes to the 'bound analytic code' field are ignored
# unless the 'force_code_id' context key is passed as True.
force_code_id = vals.pop(column, False)
if context and context.get('force_code_id', False) == True:
self._force_code(cr, uid, force_code_id, code_vals, context)
vals[column] = force_code_id
elif use_inherits:
vals.update(code_vals)
else:
name_col = rel_name[1] if rel_name else 'name'
if name_col in vals:
code_vals['name'] = vals[name_col]
records = self.browse(cr, uid, ids, context=context)
code_ids = [getattr(rec, column).id for rec in records]
# If updating a single record with no code, create it.
code_osv = self.pool['analytic.code']
if code_ids == [False]:
new = ids[0]
code_vals['nd_id'] = self._bound_dimension_id
if 'name' not in code_vals:
code_vals['name'] = self.read(
cr, uid, new, [name_col], context=context
)[name_col]
vals[column] = code_osv.create(
cr, uid, code_vals, context=context
)
elif code_vals:
code_osv.write(
cr, uid, code_ids, code_vals, context=context
)
res = super(superclass, self).write(
cr, uid, ids, vals, context=context
)
if code_ref_ids and new is not False:
self._generate_code_ref_id(cr, uid, new, context=context)
return res
@AddMethod(superclass)
def _force_code(self, cr, uid, force_code_id, code_vals, context=None):
code_osv = self.pool['analytic.code']
if not force_code_id:
raise ValueError(
"An analytic code ID MUST be specified if the " \
"force_code_id key is enabled in the context"
)
force_code_dim = code_osv.read(
cr, uid, force_code_id, ['nd_id'], context=context
)['nd_id'][0]
if force_code_dim != self._bound_dimension_id:
raise ValueError(
"If specified, codes must belong to the bound " \
"analytic dimension {}".format(dimension_name)
)
if code_vals:
code_osv.write(
cr, uid, force_code_id, code_vals, context=context
)
if sync_parent:
# This function is called as a method and can be overridden.
@AddMethod(superclass)
def _get_code_parent(self, cr, uid, vals, context=None):
"""If parent_id is in the submitted values, return the analytic
code of this parent, to be used as the child's code's parent.
"""
parent_id = vals.get(sync_parent, None)
if parent_id is not None:
if parent_id:
res = self.read(
cr, uid, parent_id, [column], context=context
)[column]
return res[0] if res else False
else:
return False
return None
if use_code_name_methods:
@AddMethod(superclass)
def name_get(self, cr, uid, ids, context=None):
"""Return the analytic code's name."""
code_osv = self.pool.get('analytic.code')
code_reads = self.read(cr, uid, ids, [column], context=context)
c2m = { # Code IDs to model IDs
code_read[column][0]: code_read['id']
for code_read in code_reads
if code_read[column] is not False
}
names = code_osv.name_get(cr, uid, c2m.keys(), context=context)
return [(c2m[cid], name) for cid, name in names if cid in c2m]
@AddMethod(superclass)
def name_search(
self, cr, uid, name, args=None, operator='ilike', context=None,
limit=100
):
"""Return the records whose analytic code matches the name."""
code_osv = self.pool.get('analytic.code')
args.append(('nd_id', '=', self._bound_dimension_id))
names = code_osv.name_search(
cr, uid, name, args, operator, context, limit
)
if not names:
return []
dom = [(column, 'in', zip(*names)[0])]
ids = self.search(cr, uid, dom, context=context)
code_reads = self.read(cr, uid, ids, [column], context=context)
c2m = { # Code IDs to model IDs
code_read[column][0]: code_read['id']
for code_read in code_reads
if code_read[column] is not False
}
return [
(c2m[cid], cname)
for cid, cname in names
if cid in c2m
]
return (superclass,)