3800775b30c2288761218e0482c1b440145d6dd4
[odoo/odoo.git] / bin / osv / fields.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 # . Fields:
23 #      - simple
24 #      - relations (one2many, many2one, many2many)
25 #      - function
26 #
27 # Fields Attributes:
28 #   _classic_read: is a classic sql fields
29 #   _type   : field type
30 #   readonly
31 #   required
32 #   size
33 #
34 import datetime as DT
35 import string
36 import netsvc
37 import sys
38
39 from psycopg2 import Binary
40 import warnings
41
42 import tools
43 from tools.translate import _
44
45 def _symbol_set(symb):
46     if symb == None or symb == False:
47         return None
48     elif isinstance(symb, unicode):
49         return symb.encode('utf-8')
50     return str(symb)
51
52
53 class _column(object):
54     _classic_read = True
55     _classic_write = True
56     _prefetch = True
57     _properties = False
58     _type = 'unknown'
59     _obj = None
60     _multi = False
61     _symbol_c = '%s'
62     _symbol_f = _symbol_set
63     _symbol_set = (_symbol_c, _symbol_f)
64     _symbol_get = None
65
66     def __init__(self, string='unknown', required=False, readonly=False, domain=None, context={}, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
67         self.states = states or {}
68         self.string = string
69         self.readonly = readonly
70         self.required = required
71         self.size = size
72         self.help = args.get('help', '')
73         self.priority = priority
74         self.change_default = change_default
75         self.ondelete = ondelete
76         self.translate = translate
77         self._domain = domain or []
78         self._context = context
79         self.write = False
80         self.read = False
81         self.view_load = 0
82         self.select = select
83         self.selectable = True
84         self.group_operator = args.get('group_operator', False)
85         for a in args:
86             if args[a]:
87                 setattr(self, a, args[a])
88
89     def restart(self):
90         pass
91
92     def set(self, cr, obj, id, name, value, user=None, context=None):
93         cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
94
95     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
96         raise Exception(_('Not implemented set_memory method !'))
97
98     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
99         raise Exception(_('Not implemented get_memory method !'))
100
101     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
102         raise Exception(_('undefined get method !'))
103
104     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
105         ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
106         res = obj.read(cr, uid, ids, [name], context=context)
107         return [x[name] for x in res]
108
109     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
110         raise Exception(_('Not implemented search_memory method !'))
111
112
113 # ---------------------------------------------------------
114 # Simple fields
115 # ---------------------------------------------------------
116 class boolean(_column):
117     _type = 'boolean'
118     _symbol_c = '%s'
119     _symbol_f = lambda x: x and 'True' or 'False'
120     _symbol_set = (_symbol_c, _symbol_f)
121
122 class integer_big(_column):
123     _type = 'integer_big'
124     _symbol_c = '%s'
125     _symbol_f = lambda x: int(x or 0)
126     _symbol_set = (_symbol_c, _symbol_f)
127     _symbol_get = lambda self,x: x or 0
128
129 class integer(_column):
130     _type = 'integer'
131     _symbol_c = '%s'
132     _symbol_f = lambda x: int(x or 0)
133     _symbol_set = (_symbol_c, _symbol_f)
134     _symbol_get = lambda self,x: x or 0
135
136
137 class reference(_column):
138     _type = 'reference'
139     def __init__(self, string, selection, size, **args):
140         _column.__init__(self, string=string, size=size, selection=selection, **args)
141
142
143 class char(_column):
144     _type = 'char'
145
146     def __init__(self, string, size, **args):
147         _column.__init__(self, string=string, size=size, **args)
148         self._symbol_set = (self._symbol_c, self._symbol_set_char)
149
150     # takes a string (encoded in utf8) and returns a string (encoded in utf8)
151     def _symbol_set_char(self, symb):
152         #TODO:
153         # * we need to remove the "symb==False" from the next line BUT
154         #   for now too many things rely on this broken behavior
155         # * the symb==None test should be common to all data types
156         if symb == None or symb == False:
157             return None
158
159         # we need to convert the string to a unicode object to be able
160         # to evaluate its length (and possibly truncate it) reliably
161         u_symb = tools.ustr(symb)
162
163         return u_symb[:self.size].encode('utf8')
164
165
166 class text(_column):
167     _type = 'text'
168
169 import __builtin__
170
171 class float(_column):
172     _type = 'float'
173     _symbol_c = '%s'
174     _symbol_f = lambda x: __builtin__.float(x or 0.0)
175     _symbol_set = (_symbol_c, _symbol_f)
176     _symbol_get = lambda self,x: x or 0.0
177
178     def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
179         _column.__init__(self, string=string, **args)
180         self.digits = digits
181         self.digits_compute = digits_compute
182
183
184     def digits_change(self, cr):
185         if self.digits_compute:
186             t = self.digits_compute(cr)
187             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
188             self.digits = t
189
190 class date(_column):
191     _type = 'date'
192     @staticmethod
193     def today(*args):
194         """ Returns the current date in a format fit for being a
195         default value to a ``date`` field.
196
197         This method should be provided as is to the _defaults dict, it
198         should not be called.
199         """
200         return DT.date.today().strftime(
201             tools.DEFAULT_SERVER_DATE_FORMAT)
202
203 class datetime(_column):
204     _type = 'datetime'
205     @staticmethod
206     def now(*args):
207         """ Returns the current datetime in a format fit for being a
208         default value to a ``datetime`` field.
209
210         This method should be provided as is to the _defaults dict, it
211         should not be called.
212         """
213         return DT.datetime.now().strftime(
214             tools.DEFAULT_SERVER_DATETIME_FORMAT)
215
216 class time(_column):
217     _type = 'time'
218     @staticmethod
219     def now( *args):
220         """ Returns the current time in a format fit for being a
221         default value to a ``time`` field.
222
223         This method should be proivided as is to the _defaults dict,
224         it should not be called.
225         """
226         return DT.datetime.now().strftime(
227             tools.DEFAULT_SERVER_TIME_FORMAT)
228
229 class binary(_column):
230     _type = 'binary'
231     _symbol_c = '%s'
232     _symbol_f = lambda symb: symb and Binary(symb) or None
233     _symbol_set = (_symbol_c, _symbol_f)
234     _symbol_get = lambda self, x: x and str(x)
235
236     _classic_read = False
237     _prefetch = False
238
239     def __init__(self, string='unknown', filters=None, **args):
240         _column.__init__(self, string=string, **args)
241         self.filters = filters
242
243     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
244         if not context:
245             context = {}
246         if not values:
247             values = []
248         res = {}
249         for i in ids:
250             val = None
251             for v in values:
252                 if v['id'] == i:
253                     val = v[name]
254                     break
255             if context.get('bin_size', False) and val:
256                 res[i] = tools.human_size(long(val))
257             else:
258                 res[i] = val
259         return res
260
261     get = get_memory
262
263
264 class selection(_column):
265     _type = 'selection'
266
267     def __init__(self, selection, string='unknown', **args):
268         _column.__init__(self, string=string, **args)
269         self.selection = selection
270
271 # ---------------------------------------------------------
272 # Relationals fields
273 # ---------------------------------------------------------
274
275 #
276 # Values: (0, 0,  { fields })    create
277 #         (1, ID, { fields })    update
278 #         (2, ID)                remove (delete)
279 #         (3, ID)                unlink one (target id or target of relation)
280 #         (4, ID)                link
281 #         (5)                    unlink all (only valid for one2many)
282 #
283 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
284 class one2one(_column):
285     _classic_read = False
286     _classic_write = True
287     _type = 'one2one'
288
289     def __init__(self, obj, string='unknown', **args):
290         warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
291         _column.__init__(self, string=string, **args)
292         self._obj = obj
293
294     def set(self, cr, obj_src, id, field, act, user=None, context=None):
295         if not context:
296             context = {}
297         obj = obj_src.pool.get(self._obj)
298         self._table = obj_src.pool.get(self._obj)._table
299         if act[0] == 0:
300             id_new = obj.create(cr, user, act[1])
301             cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
302         else:
303             cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
304             id = cr.fetchone()[0]
305             obj.write(cr, user, [id], act[1], context=context)
306
307     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
308         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
309
310
311 class many2one(_column):
312     _classic_read = False
313     _classic_write = True
314     _type = 'many2one'
315     _symbol_c = '%s'
316     _symbol_f = lambda x: x or None
317     _symbol_set = (_symbol_c, _symbol_f)
318
319     def __init__(self, obj, string='unknown', **args):
320         _column.__init__(self, string=string, **args)
321         self._obj = obj
322
323     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
324         obj.datas.setdefault(id, {})
325         obj.datas[id][field] = values
326
327     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
328         result = {}
329         for id in ids:
330             result[id] = obj.datas[id].get(name, False)
331         return result
332
333     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
334         context = context or {}
335         values = values or {}
336
337         res = {}
338         for r in values:
339             res[r['id']] = r[name]
340         for id in ids:
341             res.setdefault(id, '')
342         obj = obj.pool.get(self._obj)
343
344         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
345         # we use uid=1 because the visibility of a many2one field value (just id and name)
346         # must be the access right of the parent form and not the linked object itself.
347         records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
348         for id in res:
349             if res[id] in records:
350                 res[id] = (res[id], records[res[id]])
351             else:
352                 res[id] = False
353         return res
354
355     def set(self, cr, obj_src, id, field, values, user=None, context=None):
356         if not context:
357             context = {}
358         obj = obj_src.pool.get(self._obj)
359         self._table = obj_src.pool.get(self._obj)._table
360         if type(values) == type([]):
361             for act in values:
362                 if act[0] == 0:
363                     id_new = obj.create(cr, act[2])
364                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
365                 elif act[0] == 1:
366                     obj.write(cr, [act[1]], act[2], context=context)
367                 elif act[0] == 2:
368                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
369                 elif act[0] == 3 or act[0] == 5:
370                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
371                 elif act[0] == 4:
372                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
373         else:
374             if values:
375                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
376             else:
377                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
378
379     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
380         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
381
382
383 class one2many(_column):
384     _classic_read = False
385     _classic_write = False
386     _prefetch = False
387     _type = 'one2many'
388
389     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
390         _column.__init__(self, string=string, **args)
391         self._obj = obj
392         self._fields_id = fields_id
393         self._limit = limit
394         #one2many can't be used as condition for defaults
395         assert(self.change_default != True)
396
397     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
398         if not context:
399             context = {}
400         if self._context:
401             context = context.copy()
402             context.update(self._context)
403         if not values:
404             values = {}
405         res = {}
406         for id in ids:
407             res[id] = []
408         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
409         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
410             if r[self._fields_id] in res:
411                 res[r[self._fields_id]].append(r['id'])
412         return res
413
414     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
415         if not context:
416             context = {}
417         if self._context:
418             context = context.copy()
419         context.update(self._context)
420         if not values:
421             return
422         obj = obj.pool.get(self._obj)
423         for act in values:
424             if act[0] == 0:
425                 act[2][self._fields_id] = id
426                 obj.create(cr, user, act[2], context=context)
427             elif act[0] == 1:
428                 obj.write(cr, user, [act[1]], act[2], context=context)
429             elif act[0] == 2:
430                 obj.unlink(cr, user, [act[1]], context=context)
431             elif act[0] == 3:
432                 obj.datas[act[1]][self._fields_id] = False
433             elif act[0] == 4:
434                 obj.datas[act[1]] = id
435             elif act[0] == 5:
436                 for o in obj.datas.values():
437                     if o[self._fields_id] == id:
438                         o[self._fields_id] = False
439             elif act[0] == 6:
440                 for id2 in (act[2] or []):
441                     obj.datas[id2][self._fields_id] = id
442
443     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
444         raise _('Not Implemented')
445
446     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
447         if not context:
448             context = {}
449         if self._context:
450             context = context.copy()
451         context.update(self._context)
452         if not values:
453             values = {}
454
455         res = {}
456         for id in ids:
457             res[id] = []
458
459         ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
460         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
461             if r[self._fields_id] in res.values():
462                 res[r[self._fields_id]].append(r['id'])
463         return res
464
465     def set(self, cr, obj, id, field, values, user=None, context=None):
466         result = []
467         if not context:
468             context = {}
469         if self._context:
470             context = context.copy()
471         context.update(self._context)
472         context['no_store_function'] = True
473         if not values:
474             return
475         _table = obj.pool.get(self._obj)._table
476         obj = obj.pool.get(self._obj)
477         for act in values:
478             if act[0] == 0:
479                 act[2][self._fields_id] = id
480                 id_new = obj.create(cr, user, act[2], context=context)
481                 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
482             elif act[0] == 1:
483                 obj.write(cr, user, [act[1]], act[2], context=context)
484             elif act[0] == 2:
485                 obj.unlink(cr, user, [act[1]], context=context)
486             elif act[0] == 3:
487                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
488             elif act[0] == 4:
489                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
490             elif act[0] == 5:
491                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
492             elif act[0] == 6:
493                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
494                 ids2 = act[2] or [0]
495                 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
496                 ids3 = map(lambda x:x[0], cr.fetchall())
497                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
498         return result
499
500     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
501         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
502
503
504 #
505 # Values: (0, 0,  { fields })    create
506 #         (1, ID, { fields })    update (write fields to ID)
507 #         (2, ID)                remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
508 #         (3, ID)                unlink (delete the relationship between the two objects but does not delete ID)
509 #         (4, ID)                link (add a relationship)
510 #         (5, ID)                unlink all
511 #         (6, ?, ids)            set a list of links
512 #
513 class many2many(_column):
514     _classic_read = False
515     _classic_write = False
516     _prefetch = False
517     _type = 'many2many'
518     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
519         _column.__init__(self, string=string, **args)
520         self._obj = obj
521         if '.' in rel:
522             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
523                 'You used %s, which is not a valid SQL table name.')% (string,rel))
524         self._rel = rel
525         self._id1 = id1
526         self._id2 = id2
527         self._limit = limit
528
529     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
530         if not context:
531             context = {}
532         if not values:
533             values = {}
534         res = {}
535         if not ids:
536             return res
537         for id in ids:
538             res[id] = []
539         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
540         obj = obj.pool.get(self._obj)
541
542         d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
543         if d1:
544             d1 = ' and ' + ' and '.join(d1)
545         else: d1 = ''
546         query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
547                    FROM %(rel)s, %(tbl)s \
548                   WHERE %(rel)s.%(id1)s in %%s \
549                     AND %(rel)s.%(id2)s = %(tbl)s.id \
550                  %(d1)s  \
551                  %(limit)s \
552                   ORDER BY %(tbl)s.%(order)s \
553                  OFFSET %(offset)d' \
554             % {'rel': self._rel,
555                'tbl': obj._table,
556                'id1': self._id1,
557                'id2': self._id2,
558                'd1': d1,
559                'limit': limit_str,
560                'order': obj._order,
561                'offset': offset,
562               }
563         cr.execute(query, [tuple(ids)] + d2)
564         for r in cr.fetchall():
565             res[r[1]].append(r[0])
566         return res
567
568     def set(self, cr, obj, id, name, values, user=None, context=None):
569         if not context:
570             context = {}
571         if not values:
572             return
573         obj = obj.pool.get(self._obj)
574         for act in values:
575             if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
576                 continue
577             if act[0] == 0:
578                 idnew = obj.create(cr, user, act[2])
579                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
580             elif act[0] == 1:
581                 obj.write(cr, user, [act[1]], act[2], context=context)
582             elif act[0] == 2:
583                 obj.unlink(cr, user, [act[1]], context=context)
584             elif act[0] == 3:
585                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
586             elif act[0] == 4:
587                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
588             elif act[0] == 5:
589                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
590             elif act[0] == 6:
591
592                 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
593                 if d1:
594                     d1 = ' and ' + ' and '.join(d1)
595                 else:
596                     d1 = ''
597                 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+','.join(tables)+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
598
599                 for act_nbr in act[2]:
600                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
601
602     #
603     # TODO: use a name_search
604     #
605     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
606         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
607
608     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
609         result = {}
610         for id in ids:
611             result[id] = obj.datas[id].get(name, [])
612         return result
613
614     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
615         if not values:
616             return
617         for act in values:
618             # TODO: use constants instead of these magic numbers
619             if act[0] == 0:
620                 raise _('Not Implemented')
621             elif act[0] == 1:
622                 raise _('Not Implemented')
623             elif act[0] == 2:
624                 raise _('Not Implemented')
625             elif act[0] == 3:
626                 raise _('Not Implemented')
627             elif act[0] == 4:
628                 raise _('Not Implemented')
629             elif act[0] == 5:
630                 raise _('Not Implemented')
631             elif act[0] == 6:
632                 obj.datas[id][name] = act[2]
633
634
635 def get_nice_size(a):
636     (x,y) = a
637     if isinstance(y, (int,long)):
638         size = y
639     elif y:
640         size = len(y)
641     else:
642         size = 0
643     return (x, tools.human_size(size))
644
645 # ---------------------------------------------------------
646 # Function fields
647 # ---------------------------------------------------------
648 class function(_column):
649     _classic_read = False
650     _classic_write = False
651     _prefetch = False
652     _type = 'function'
653     _properties = True
654
655 #
656 # multi: compute several fields in one call
657 #
658     def __init__(self, fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, method=False, store=False, multi=False, **args):
659         _column.__init__(self, **args)
660         self._obj = obj
661         self._method = method
662         self._fnct = fnct
663         self._fnct_inv = fnct_inv
664         self._arg = arg
665         self._multi = multi
666         if 'relation' in args:
667             self._obj = args['relation']
668
669         self.digits = args.get('digits', (16,2))
670         self.digits_compute = args.get('digits_compute', None)
671
672         self._fnct_inv_arg = fnct_inv_arg
673         if not fnct_inv:
674             self.readonly = 1
675         self._type = type
676         self._fnct_search = fnct_search
677         self.store = store
678
679         if not fnct_search and not store:
680             self.selectable = False
681
682         if store:
683             if self._type != 'many2one':
684                 # m2o fields need to return tuples with name_get, not just foreign keys
685                 self._classic_read = True
686             self._classic_write = True
687             if type=='binary':
688                 self._symbol_get=lambda x:x and str(x)
689
690         if type == 'float':
691             self._symbol_c = float._symbol_c
692             self._symbol_f = float._symbol_f
693             self._symbol_set = float._symbol_set
694
695         if type == 'boolean':
696             self._symbol_c = boolean._symbol_c
697             self._symbol_f = boolean._symbol_f
698             self._symbol_set = boolean._symbol_set
699
700     def digits_change(self, cr):
701         if self.digits_compute:
702             t = self.digits_compute(cr)
703             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
704             self.digits = t
705
706
707     def search(self, cr, uid, obj, name, args, context=None):
708         if not self._fnct_search:
709             #CHECKME: should raise an exception
710             return []
711         return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
712
713     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
714         if not context:
715             context = {}
716         if not values:
717             values = {}
718         res = {}
719         if self._method:
720             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
721         else:
722             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
723
724         if self._type == "many2one" :
725             # Filtering only integer/long values if passed
726             res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
727
728             if res_ids:
729                 obj_model = obj.pool.get(self._obj)
730                 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
731                 for r in res.keys():
732                     if res[r] and res[r] in dict_names:
733                         res[r] = (res[r], dict_names[res[r]])
734
735         if self._type == 'binary' and context.get('bin_size', False):
736             # convert the data returned by the function with the size of that data...
737             res = dict(map( get_nice_size, res.items()))
738         if self._type == "integer":
739             for r in res.keys():
740                 # Converting value into string so that it does not affect XML-RPC Limits
741                 if isinstance(res[r],dict): # To treat integer values with _multi attribute
742                     for record in res[r].keys():
743                         res[r][record] = str(res[r][record])
744                 else:
745                     res[r] = str(res[r])
746         return res
747     get_memory = get
748
749     def set(self, cr, obj, id, name, value, user=None, context=None):
750         if not context:
751             context = {}
752         if self._fnct_inv:
753             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
754     set_memory = set
755
756 # ---------------------------------------------------------
757 # Related fields
758 # ---------------------------------------------------------
759
760 class related(function):
761
762     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
763         self._field_get2(cr, uid, obj, context)
764         i = len(self._arg)-1
765         sarg = name
766         while i>0:
767             if type(sarg) in [type([]), type( (1,) )]:
768                 where = [(self._arg[i], 'in', sarg)]
769             else:
770                 where = [(self._arg[i], '=', sarg)]
771             if domain:
772                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
773                 domain = []
774             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
775             i -= 1
776         return [(self._arg[0], 'in', sarg)]
777
778     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
779         self._field_get2(cr, uid, obj, context)
780         if type(ids) != type([]):
781             ids=[ids]
782         objlst = obj.browse(cr, uid, ids)
783         for data in objlst:
784             t_id = data.id
785             t_data = data
786             for i in range(len(self.arg)):
787                 if not t_data: break
788                 field_detail = self._relations[i]
789                 if not t_data[self.arg[i]]:
790                     if self._type not in ('one2many', 'many2many'):
791                         t_id = t_data['id']
792                     t_data = False
793                 elif field_detail['type'] in ('one2many', 'many2many'):
794                     if self._type != "many2one":
795                         t_id = t_data.id
796                         t_data = t_data[self.arg[i]][0]
797                     else:
798                         t_data = False
799                 else:
800                     t_id = t_data['id']
801                     t_data = t_data[self.arg[i]]
802             else:
803                 model = obj.pool.get(self._relations[-1]['object'])
804                 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
805
806     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
807         self._field_get2(cr, uid, obj, context)
808         if not ids: return {}
809         relation = obj._name
810         if self._type in ('one2many', 'many2many'):
811             res = dict([(i, []) for i in ids])
812         else:
813             res = {}.fromkeys(ids, False)
814
815         objlst = obj.browse(cr, 1, ids, context=context)
816         for data in objlst:
817             if not data:
818                 continue
819             t_data = data
820             relation = obj._name
821             for i in range(len(self.arg)):
822                 field_detail = self._relations[i]
823                 relation = field_detail['object']
824                 try:
825                     if not t_data[self.arg[i]]:
826                         t_data = False
827                         break
828                 except:
829                     t_data = False
830                     break
831                 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
832                     t_data = t_data[self.arg[i]][0]
833                 elif t_data:
834                     t_data = t_data[self.arg[i]]
835             if type(t_data) == type(objlst[0]):
836                 res[data.id] = t_data.id
837             elif t_data:
838                 res[data.id] = t_data
839         if self._type=='many2one':
840             ids = filter(None, res.values())
841             if ids:
842                 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
843                 for r in res:
844                     if res[r]:
845                         res[r] = (res[r], ng[res[r]])
846         elif self._type in ('one2many', 'many2many'):
847             for r in res:
848                 if res[r]:
849                     res[r] = [x.id for x in res[r]]
850         return res
851
852     def __init__(self, *arg, **args):
853         self.arg = arg
854         self._relations = []
855         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
856         if self.store is True:
857             # TODO: improve here to change self.store = {...} according to related objects
858             pass
859
860     def _field_get2(self, cr, uid, obj, context={}):
861         if self._relations:
862             return
863         obj_name = obj._name
864         for i in range(len(self._arg)):
865             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
866             self._relations.append({
867                 'object': obj_name,
868                 'type': f['type']
869
870             })
871             if f.get('relation',False):
872                 obj_name = f['relation']
873                 self._relations[-1]['relation'] = f['relation']
874
875 # ---------------------------------------------------------
876 # Dummy fields
877 # ---------------------------------------------------------
878
879 class dummy(function):
880     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
881         return []
882
883     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
884         return False
885
886     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
887         return {}
888
889     def __init__(self, *arg, **args):
890         self.arg = arg
891         self._relations = []
892         super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
893
894 # ---------------------------------------------------------
895 # Serialized fields
896 # ---------------------------------------------------------
897 class serialized(_column):
898     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
899         self._serialize_func = serialize_func
900         self._deserialize_func = deserialize_func
901         self._type = type
902         self._symbol_set = (self._symbol_c, self._serialize_func)
903         self._symbol_get = self._deserialize_func
904         super(serialized, self).__init__(string=string, **args)
905
906
907 # TODO: review completly this class for speed improvement
908 class property(function):
909
910     def _get_default(self, obj, cr, uid, prop_name, context=None):
911         return self._get_defaults(obj, cr, uid, [prop_name], context=None)[0][prop_name]
912
913     def _get_defaults(self, obj, cr, uid, prop_name, context=None):
914         prop = obj.pool.get('ir.property')
915         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
916         ids = prop.search(cr, uid, domain, context=context)
917         replaces = {}
918         default_value = {}.fromkeys(prop_name, False)
919         for prop_rec in prop.browse(cr, uid, ids, context=context):
920             if default_value.get(prop_rec.fields_id.name, False):
921                 continue
922             value = prop.get_by_record(cr, uid, prop_rec, context=context) or False
923             default_value[prop_rec.fields_id.name] = value
924             if value and (prop_rec.type == 'many2one'):
925                 replaces.setdefault(value._name, {})
926                 replaces[value._name][value.id] = True
927         return default_value, replaces
928
929     def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
930         prop = obj.pool.get('ir.property')
931         vids = [obj._name + ',' + str(oid) for oid in  ids]
932
933         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
934         #domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
935         if vids:
936             domain = [('res_id', 'in', vids)] + domain
937         return prop.search(cr, uid, domain, context=context)
938
939     # TODO: to rewrite more clean
940     def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
941         if context is None:
942             context = {}
943
944         nids = self._get_by_id(obj, cr, uid, [prop_name], [id], context)
945         if nids:
946             cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
947
948         default_val = self._get_default(obj, cr, uid, prop_name, context)
949
950         if id_val is not default_val:
951             def_id = self._field_get(cr, uid, obj._name, prop_name)
952             company = obj.pool.get('res.company')
953             cid = company._company_default_get(cr, uid, obj._name, def_id,
954                                                context=context)
955             propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
956                                                              context=context)
957             prop = obj.pool.get('ir.property')
958             return prop.create(cr, uid, {
959                 'name': propdef.name,
960                 'value': id_val,
961                 'res_id': obj._name+','+str(id),
962                 'company_id': cid,
963                 'fields_id': def_id,
964                 'type': self._type,
965             }, context=context)
966         return False
967
968
969     def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
970         properties = obj.pool.get('ir.property')
971         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
972         domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in  ids])]
973         nids = properties.search(cr, uid, domain, context=context)
974         default_val,replaces = self._get_defaults(obj, cr, uid, prop_name, context)
975
976         res = {}
977         for id in ids:
978             res[id] = default_val.copy()
979
980         brs = properties.browse(cr, uid, nids, context=context)
981         for prop in brs:
982             value = properties.get_by_record(cr, uid, prop, context=context)
983             res[prop.res_id.id][prop.fields_id.name] = value or False
984             if value and (prop.type == 'many2one'):
985                 replaces.setdefault(value._name, {})
986                 replaces[value._name][value.id] = True
987
988         for rep in replaces:
989             replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
990
991         for prop in prop_name:
992             for id in ids:
993                 if res[id][prop] and hasattr(res[id][prop], '_name'):
994                     res[id][prop] = (res[id][prop].id , replaces[res[id][prop]._name].get(res[id][prop].id, False))
995
996         return res
997
998
999     def _field_get(self, cr, uid, model_name, prop):
1000         if not self.field_id.get(cr.dbname):
1001             cr.execute('SELECT id \
1002                     FROM ir_model_fields \
1003                     WHERE name=%s AND model=%s', (prop, model_name))
1004             res = cr.fetchone()
1005             self.field_id[cr.dbname] = res and res[0]
1006         return self.field_id[cr.dbname]
1007
1008     def __init__(self, obj_prop, **args):
1009         # TODO remove obj_prop parameter (use many2one type)
1010         self.field_id = {}
1011         function.__init__(self, self._fnct_read, False, self._fnct_write,
1012                           obj_prop, multi='properties', **args)
1013
1014     def restart(self):
1015         self.field_id = {}
1016
1017
1018 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
1019