removed bad code
[odoo/odoo.git] / bin / osv / fields.py
index d6d23f7..800edf5 100644 (file)
@@ -1,22 +1,21 @@
-# -*- encoding: utf-8 -*-
+# -*- coding: utf-8 -*-
 ##############################################################################
-#
+#    
 #    OpenERP, Open Source Management Solution
-#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
-#    $Id$
+#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
 #
 #    This program is free software: you can redistribute it and/or modify
-#    it under the terms of the GNU General Public License as published by
-#    the Free Software Foundation, either version 3 of the License, or
-#    (at your option) any later version.
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
 #
 #    This program is distributed in the hope that it will be useful,
 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#    GNU General Public License for more details.
+#    GNU Affero General Public License for more details.
 #
-#    You should have received a copy of the GNU General Public License
-#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
 #
 ##############################################################################
 
@@ -80,6 +79,7 @@ class _column(object):
         self.read = False
         self.view_load = 0
         self.select = select
+        self.selectable = True
         for a in args:
             if args[a]:
                 setattr(self, a, args[a])
@@ -99,9 +99,9 @@ class _column(object):
     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         raise Exception(_('undefined get method !'))
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
-        res = obj.read(cr, uid, ids, [name])
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
+        res = obj.read(cr, uid, ids, [name], context=context)
         return [x[name] for x in res]
 
     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
@@ -267,8 +267,8 @@ class one2one(_column):
             id = cr.fetchone()[0]
             obj.write(cr, user, [id], act[1], context=context)
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
 
 
 class many2one(_column):
@@ -304,6 +304,7 @@ class many2one(_column):
         for id in ids:
             res.setdefault(id, '')
         obj = obj.pool.get(self._obj)
+
         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
         from orm import except_orm
         try:
@@ -313,7 +314,6 @@ class many2one(_column):
             iids = filter(None, res.values())
             for iiid in iids:
                 names[iiid] = '// Access Denied //'
-
         for r in res.keys():
             if res[r] and res[r] in names:
                 res[r] = (res[r], names[res[r]])
@@ -345,8 +345,8 @@ class many2one(_column):
             else:
                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
 
 
 class one2many(_column):
@@ -463,8 +463,8 @@ class one2many(_column):
                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
         return result
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
-        return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
+        return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
 
 
 #
@@ -506,12 +506,13 @@ class many2many(_column):
         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
         obj = obj.pool.get(self._obj)
 
-        d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
+        d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
         if d1:
-            d1 = ' and ' + d1
+            d1 = ' and ' + ' and '.join(d1)
+        else: d1 = ''
 
         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
-                FROM '+self._rel+' , '+obj._table+' \
+                FROM '+self._rel+' , '+(','.join(tables))+' \
                 WHERE '+self._rel+'.'+self._id1+' = ANY (%s) \
                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
@@ -527,6 +528,8 @@ class many2many(_column):
             return
         obj = obj.pool.get(self._obj)
         for act in values:
+            if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
+                continue
             if act[0] == 0:
                 idnew = obj.create(cr, user, act[2])
                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
@@ -542,10 +545,12 @@ class many2many(_column):
                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
             elif act[0] == 6:
 
-                d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
+                d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
                 if d1:
-                    d1 = ' and ' + d1
-                cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
+                    d1 = ' and ' + ' and '.join(d1)
+                else:
+                    d1 = ''
+                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)
 
                 for act_nbr in act[2]:
                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
@@ -553,8 +558,8 @@ class many2many(_column):
     #
     # TODO: use a name_search
     #
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
 
     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         result = {}
@@ -583,6 +588,16 @@ class many2many(_column):
                 obj.datas[id][name] = act[2]
 
 
+def get_nice_size(a):
+    (x,y) = a
+    if isinstance(y, (int,long)):
+        size = y
+    elif y:
+        size = len(y)
+    else:
+        size = 0
+    return (x, tools.human_size(size))
+
 # ---------------------------------------------------------
 # Function fields
 # ---------------------------------------------------------
@@ -606,12 +621,22 @@ class function(_column):
         self._multi = multi
         if 'relation' in args:
             self._obj = args['relation']
+            
+        if 'digits' in args:
+            self.digits = args['digits']
+        else:
+            self.digits = (16,2)    
+                
         self._fnct_inv_arg = fnct_inv_arg
         if not fnct_inv:
             self.readonly = 1
         self._type = type
         self._fnct_search = fnct_search
         self.store = store
+
+        if not fnct_search and not store:
+            self.selectable = False
+        
         if store:
             self._classic_read = True
             self._classic_write = True
@@ -623,11 +648,11 @@ class function(_column):
             self._symbol_f = float._symbol_f
             self._symbol_set = float._symbol_set
 
-    def search(self, cr, uid, obj, name, args):
+    def search(self, cr, uid, obj, name, args, context=None):
         if not self._fnct_search:
             #CHECKME: should raise an exception
             return []
-        return self._fnct_search(obj, cr, uid, obj, name, args)
+        return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
 
     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
         if not context:
@@ -653,7 +678,11 @@ class function(_column):
             
         if self._type == 'binary' and context.get('bin_size', False):
             # convert the data returned by the function with the size of that data...
-            res = dict(map(lambda (x, y): (x, tools.human_size(len(y or ''))), res.items()))
+            res = dict(map( get_nice_size, res.items()))
+        if self._type == "integer":
+            for r in res.keys():
+                # Converting value into string so that it does not affect XML-RPC Limits
+                res[r] = str(res[r])
         return res
     get_memory = get
 
@@ -712,14 +741,15 @@ class related(function):
                         t_id=t_data['id']
                         t_data = t_data[self.arg[i]]
                 if t_id:
-                    obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values})
+                    obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values}, context=context)
 
     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
         self._field_get2(cr, uid, obj, context)
         if not ids: return {}
         relation = obj._name
         res = {}.fromkeys(ids, False)
-        objlst = obj.browse(cr, uid, ids)
+
+        objlst = obj.browse(cr, uid, ids, context=context)
         for data in objlst:
             if not data:
                 continue
@@ -735,7 +765,7 @@ class related(function):
                 except:
                     t_data = False
                     break
-                if field_detail['type'] in ('one2many', 'many2many'):
+                if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
                     t_data = t_data[self.arg[i]][0]
                 else:
                     t_data = t_data[self.arg[i]]
@@ -751,12 +781,20 @@ class related(function):
                 for r in res:
                     if res[r]:
                         res[r] = (res[r], ng[res[r]])
+        elif self._type in ('one2many', 'many2many'):
+            for r in res:
+                if res[r]:
+                    res[r] = [x.id for x in res[r]]
+
         return res
 
     def __init__(self, *arg, **args):
         self.arg = arg
         self._relations = []
         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
+        if self.store is True:
+            # TODO: improve here to change self.store = {...} according to related objects
+            pass
 
     def _field_get2(self, cr, uid, obj, context={}):
         if self._relations:
@@ -774,6 +812,25 @@ class related(function):
                 self._relations[-1]['relation'] = f['relation']
 
 # ---------------------------------------------------------
+# Dummy fields
+# ---------------------------------------------------------
+
+class dummy(function):
+    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
+        return []
+
+    def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
+        return False
+
+    def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
+        return {}
+    
+    def __init__(self, *arg, **args):
+        self.arg = arg
+        self._relations = []
+        super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
+
+# ---------------------------------------------------------
 # Serialized fields
 # ---------------------------------------------------------
 class serialized(_column):
@@ -806,9 +863,12 @@ class property(function):
         if nid:
             default_val = property.browse(cr, uid, nid[0], context).value
 
-        company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
+        company_id = obj.pool.get('res.company')._company_default_get(cr, uid, obj._name, prop, context=context)
         res = False
-        newval = (id_val and obj_dest+','+str(id_val)) or False
+        if val[0]:
+            newval = (id_val and obj_dest+','+str(id_val)) or False
+        else:
+            newval = id_val or False
         if (newval != default_val) and newval:
             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
                     definition_id, context=context)
@@ -842,27 +902,28 @@ class property(function):
         for id in ids:
             res[id] = default_val
         for prop in property.browse(cr, uid, nids):
-            res[int(prop.res_id.split(',')[1])] = (prop.value and \
-                    int(prop.value.split(',')[1])) or False
-
-        obj = obj.pool.get(self._obj)
-
-        to_check = res.values()
-        if default_val and default_val not in to_check:
-            to_check += [default_val]
-        existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
-        
-        for id, res_id in res.items():
-            if res_id not in existing_ids:
-                cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
-                res[id] = default_val
-
-        names = dict(obj.name_get(cr, uid, existing_ids, context))
-        for r in res.keys():
-            if res[r] and res[r] in names:
-                res[r] = (res[r], names[res[r]])
+            if prop.value.find(',') >= 0:
+                res[int(prop.res_id.split(',')[1])] = (prop.value and \
+                        int(prop.value.split(',')[1])) or False
             else:
-                res[r] = False
+                res[int(prop.res_id.split(',')[1])] = prop.value or ''
+
+        if self._obj:
+            obj = obj.pool.get(self._obj)
+            to_check = res.values()
+            if default_val and default_val not in to_check:
+                to_check += [default_val]
+            existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
+            for id, res_id in res.items():
+                if res_id not in existing_ids:
+                    cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
+                    res[id] = default_val
+            names = dict(obj.name_get(cr, uid, existing_ids, context))
+            for r in res.keys():
+                if res[r] and res[r] in names:
+                    res[r] = (res[r], names[res[r]])
+                else:
+                    res[r] = False
         return res
 
     def _field_get(self, cr, uid, model_name, prop):