update translations files
[odoo/odoo.git] / addons / base_module_record / base_module_record.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #                    Fabien Pinckaers <fp@tiny.Be>
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 from xml.dom import minidom
31 from osv import fields,osv
32 import netsvc
33 import pooler
34 import string
35
36 class base_module_record(osv.osv):
37     _name = "ir.module.record"
38     _columns = {
39
40     }
41     def __init__(self, pool, cr=None):
42         if super(base_module_record, self).__init__.func_code.co_argcount ==3:
43             super(base_module_record, self).__init__(pool,cr)
44         else:
45             super(base_module_record, self).__init__(pool)
46         self.recording = 0
47         self.recording_data = []
48         self.depends = {}
49
50     # To Be Improved
51     def _create_id(self, cr, uid, model, data):
52         i = 0
53         while True:
54             name = filter(lambda x: x in string.letters, (data.get('name','') or '').lower())
55             val = model.replace('.','_')+'_'+name+ str(i)
56             i+=1
57             if val not in self.ids.values():
58                 break
59         return val
60
61     def _get_id(self, cr, uid, model, id):
62         if (model,id) in self.ids:
63             return self.ids[(model,id)], False
64         dt = self.pool.get('ir.model.data')
65         dtids = dt.search(cr, uid, [('model','=',model), ('res_id','=',id)])
66         if not dtids:
67             return None, None
68         obj = dt.browse(cr, uid, dtids[0])
69         self.depends[obj.module] = True
70         return obj.module+'.'+obj.name, obj.noupdate
71
72     def _create_record(self, cr, uid, doc, model, data, record_id, noupdate=False):
73         record = doc.createElement('record')
74         record.setAttribute("id", record_id)
75         record.setAttribute("model", model)
76         lids  = self.pool.get('ir.model.data').search(cr, uid, [('model','=',model)])
77         res = self.pool.get('ir.model.data').read(cr, uid, lids[:1], ['module'])
78         if res:
79             self.depends[res[0]['module']]=True
80         record_list = [record]
81         fields = self.pool.get(model).fields_get(cr, uid)
82         for key,val in data.items():
83             if not (val or (fields[key]['type']=='boolean')):
84                 continue
85             if fields[key]['type'] in ('integer','float'):
86                 field = doc.createElement('field')
87                 field.setAttribute("name", key)
88                 field.setAttribute("eval", val and str(val) or 'False' )
89                 record.appendChild(field)
90             elif fields[key]['type'] in ('boolean',):
91                 field = doc.createElement('field')
92                 field.setAttribute("name", key)
93                 field.setAttribute("eval", val and '1' or '0' )
94                 record.appendChild(field)
95             elif fields[key]['type'] in ('many2one',):
96                 field = doc.createElement('field')
97                 field.setAttribute("name", key)
98                 if type(val) in (type(''),type(u'')):
99                     id = val
100                 else:
101                     id,update = self._get_id(cr, uid, fields[key]['relation'], val)
102                     noupdate = noupdate or update
103                 if not id:
104                     field.setAttribute("model", fields[key]['relation'])
105                     name = self.pool.get(fields[key]['relation']).browse(cr, uid, val).name
106                     print name
107                     field.setAttribute("search", "[('name','=','"+name+"')]")
108                 else:
109                     field.setAttribute("ref", id)
110                 record.appendChild(field)
111             elif fields[key]['type'] in ('one2many',):
112                 for valitem in (val or []):
113                     if valitem[0]==0:
114                         fname = self.pool.get(model)._columns[key]._fields_id
115                         valitem[2][fname] = record_id
116                         newid = self._create_id(cr, uid, fields[key]['relation'], valitem[2])
117                         childrecord, update = self._create_record(cr, uid, doc, fields[key]['relation'],valitem[2], newid)
118                         noupdate = noupdate or update
119                         record_list += childrecord
120                         self.ids[(fields[key]['relation'],newid)] = newid
121                     else:
122                         pass
123             elif fields[key]['type'] in ('many2many',):
124                 res = []
125                 for valitem in (val or []):
126                     if valitem[0]==6:
127                         for id2 in valitem[2]:
128                             id,update = self._get_id(cr, uid, fields[key]['relation'], id2)
129                             self.ids[(fields[key]['relation'],id)] = id
130                             noupdate = noupdate or update
131                             res.append(id)
132                         field = doc.createElement('field')
133                         field.setAttribute("name", key)
134                         field.setAttribute("eval", "[(6,0,["+','.join(map(lambda x: "ref('%s')" % (x,), res))+'])]')
135                         record.appendChild(field)
136             else:
137                 field = doc.createElement('field')
138                 field.setAttribute("name", key)
139
140                 if not isinstance(val, basestring):
141                     val = str(val)
142
143                 val = val and ('"""%s"""' % val.replace('\\', '\\\\').replace('"', '\"')) or 'False'
144                 if isinstance(val, basestring):
145                     val = val.decode('utf8')
146
147                 field.setAttribute(u"eval",  val)
148                 record.appendChild(field)
149         return record_list, noupdate
150
151     def _generate_object_xml(self, cr, uid, rec, recv, doc, result=None):
152         record_list = []
153         noupdate = False
154         if rec[4]=='write':
155             for id in rec[5]:
156                 id,update = self._get_id(cr, uid, rec[3], id)
157                 noupdate = noupdate or update
158                 if not id:
159                     continue
160                 record,update = self._create_record(cr, uid, doc, rec[3], rec[6], id)
161                 noupdate = noupdate or update
162                 record_list += record
163         elif rec[4]=='create':
164             id = self._create_id(cr, uid, rec[3],rec[5])
165             record,noupdate = self._create_record(cr, uid, doc, rec[3], rec[5], id)
166             self.ids[(rec[3],result)] = id
167             record_list += record
168         return record_list,noupdate
169     def _generate_assert_xml(self, rec, doc):
170         pass
171     def generate_xml(self, cr, uid):
172         # Create the minidom document
173         self.ids = {}
174         doc = minidom.Document()
175         terp = doc.createElement("terp")
176         doc.appendChild(terp)
177         for rec in self.recording_data:
178             if rec[0]=='workflow':
179                 rec_id,noupdate = self._get_id(cr, uid, rec[1][3], rec[1][5])
180                 if not rec_id:
181                     continue
182                 data = doc.createElement("data")
183                 terp.appendChild(data)
184                 wkf = doc.createElement('workflow')
185                 data.appendChild(wkf)
186                 wkf.setAttribute("model", rec[1][3])
187                 wkf.setAttribute("action", rec[1][4])
188                 if noupdate:
189                     data.setAttribute("noupdate", "1")
190                 wkf.setAttribute("ref", rec_id)
191             if rec[0]=='query':
192                 res_list,noupdate = self._generate_object_xml(cr, uid, rec[1], rec[2], doc, rec[3])
193                 data = doc.createElement("data")
194                 if noupdate:
195                     data.setAttribute("noupdate", "1")
196                 if res_list:
197                     terp.appendChild(data)
198                 for res in res_list:
199                     data.appendChild(res)
200             elif rec[0]=='assert':
201                 pass
202         res = doc.toprettyxml(indent="\t")
203         return  doc.toprettyxml(indent="\t").encode('utf8')
204 base_module_record()
205
206 def fnct_call(fnct):
207     def execute(*args, **argv):
208         res = fnct(*args, **argv)
209         pool = pooler.get_pool(args[0])
210         mod = pool.get('ir.module.record')
211         if mod and mod.recording:
212             if args[4] not in ('default_get','read','fields_view_get','fields_get','search','search_count','name_search','name_get','get','request_get', 'get_sc'):
213                 mod.recording_data.append(('query', args, argv,res))
214         return res
215     return execute
216
217 def fnct_call_workflow(fnct):
218     def exec_workflow(*args, **argv):
219         res = fnct(*args, **argv)
220         pool = pooler.get_pool(args[0])
221         mod = pool.get('ir.module.record')
222         if mod and mod.recording:
223             mod.recording_data.append(('workflow', args, argv))
224         return res
225     return exec_workflow
226
227 obj  = netsvc._service['object']
228 obj.execute = fnct_call(obj.execute)
229 obj.exportMethod(obj.execute)
230 obj.exec_workflow = fnct_call_workflow(obj.exec_workflow)
231 obj.exportMethod(obj.exec_workflow)
232
233 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
234