KERNEL: allow directory for import csv
[odoo/odoo.git] / bin / tools / convert.py
1 #----------------------------------------------------------
2 # Convert 
3 #----------------------------------------------------------
4 import re
5 import StringIO,xml.dom.minidom
6 import osv,ir,pooler
7
8 import csv
9 import os.path
10
11 from config import config
12
13 class ConvertError(Exception):
14         def __init__(self, doc, orig_excpt):
15                 self.d = doc
16                 self.orig = orig_excpt
17         
18         def __str__(self):
19                 return 'Exception:\n\t%s\nUsing file:\n%s' % (self.orig, self.d)
20
21 def _eval_xml(self,node, pool, cr, uid, idref):
22         if node.nodeType == node.TEXT_NODE:
23                 return node.data.encode("utf8")
24         elif node.nodeType == node.ELEMENT_NODE:
25                 if node.nodeName in ('field','value'):
26                         t = node.getAttribute('type') or 'char'
27                         if len(node.getAttribute('search')):
28                                 f_search = node.getAttribute("search").encode('utf-8')
29                                 f_model = node.getAttribute("model").encode('ascii')
30                                 f_use = node.getAttribute("use").encode('ascii')
31                                 f_name = node.getAttribute("name").encode('utf-8')
32                                 if len(f_use)==0:
33                                         f_use = "id"
34                                 q = eval(f_search, idref)
35                                 ids = pool.get(f_model).search(cr, uid, q)
36                                 if f_use<>'id':
37                                         ids = map(lambda x: x[f_use], pool.get(f_model).read(cr, uid, ids, [f_use]))
38                                 _cols = pool.get(f_model)._columns
39                                 if (f_name in _cols) and _cols[f_name]._type=='many2many':
40                                         return ids
41                                 f_val = False
42                                 if len(ids):
43                                         f_val = ids[0]
44                                         if isinstance(f_val, tuple):
45                                                 f_val = f_val[0]
46                                 return f_val
47                         a_eval = node.getAttribute('eval')
48                         if len(a_eval):
49                                 import time
50                                 idref['time'] = time
51                                 idref['ref'] = lambda x: self.id_get(cr, False, x)
52                                 return eval(a_eval, idref)
53                         if t == 'xml':
54                                 def _process(s, idref):
55                                         m = re.findall('[^%]%\((.*?)\)[ds]', s)
56                                         for id in m:
57                                                 if not id in idref:
58                                                         idref[id]=self.id_get(cr, False, id)
59                                         return s % idref
60                                 txt = '<?xml version="1.0"?>\n'+_process("".join([i.toxml().encode("utf8") for i in node.childNodes]), idref)
61 #                               txt = '<?xml version="1.0"?>\n'+"".join([i.toxml().encode("utf8") for i in node.childNodes]) % idref
62
63                                 return txt
64                         if t in ('char', 'int', 'float'):
65                                 d = ""
66                                 for n in [i for i in node.childNodes]:
67                                         d+=str(_eval_xml(self,n,pool,cr,uid,idref))
68                                 if t == 'int':
69                                         d = d.strip()
70                                         if d=='None':
71                                                 return None
72                                         else:
73                                                 d=int(d.strip())
74                                 elif t=='float':
75                                         d=float(d.strip())
76                                 return d
77                         elif t in ('list','tuple'):
78                                 res=[]
79                                 for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=='value')]:
80                                         res.append(_eval_xml(self,n,pool,cr,uid,idref))
81                                 if t=='tuple':
82                                         return tuple(res)
83                                 return res
84                 elif node.nodeName=="getitem":
85                         for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]:
86                                 res=_eval_xml(self,n,pool,cr,uid,idref)
87                         if not res:
88                                 raise LookupError
89                         elif node.getAttribute('type') in ("int", "list"):
90                                 return res[int(node.getAttribute('index'))]
91                         else:
92                                 return res[node.getAttribute('index').encode("utf8")]
93                 elif node.nodeName=="function":
94                         args = []
95                         a_eval = node.getAttribute('eval')
96                         if len(a_eval):
97                                 idref['ref'] = lambda x: self.id_get(cr, False, x)
98                                 args = eval(a_eval, idref)
99                         for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]:
100                                 args.append(_eval_xml(self,n, pool, cr, uid, idref))
101                         model = pool.get(node.getAttribute('model'))
102                         method = node.getAttribute('name')
103                         res = getattr(model, method)(cr, uid, *args)
104                         return res
105
106 escape_re = re.compile(r'(?<!\\)/')
107 def escape(x):
108         return x.replace('\\/', '/')
109
110 class xml_import(object):
111         def _tag_delete(self, cr, rec, data_node=None):
112                 d_model = rec.getAttribute("model")
113                 d_search = rec.getAttribute("search")
114                 ids = self.pool.get(d_model).search(cr,self.uid,eval(d_search))
115                 if len(ids):
116                         self.pool.get(d_model).unlink(cr, self.uid, ids)
117                         #self.pool.get('ir.model.data')._unlink(cr, self.uid, d_model, ids, direct=True)
118                 return False
119
120         def _tag_report(self, cr, rec, data_node=None):
121                 res = {}
122                 for dest,f in (('name','string'),('model','model'),('report_name','name')):
123                         res[dest] = rec.getAttribute(f).encode('utf8')
124                         assert res[dest], "Attribute %s of report is empty !" % (f,)
125                 for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl')):
126                         if rec.hasAttribute(field):
127                                 res[dest] = rec.getAttribute(field).encode('utf8')
128                 if rec.hasAttribute('auto'):
129                         res['auto'] = eval(rec.getAttribute('auto'))
130                 xml_id = rec.getAttribute('id').encode('utf8')
131                 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.report.xml", self.module, res, xml_id, mode=self.mode)
132                 self.idref[xml_id] = id
133                 if not rec.hasAttribute('menu') or eval(rec.getAttribute('menu')):
134                         keyword = str(rec.getAttribute('keyword') or 'client_print_multi')
135                         keys = [('action',keyword),('res_model',res['model'])]
136                         value = 'ir.actions.report.xml,'+str(id)
137                         replace = rec.hasAttribute('replace') and rec.getAttribute("replace")
138                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True)
139                 return False
140
141         def _tag_function(self, cr, rec, data_node=None):
142                 _eval_xml(self,rec, self.pool, cr, self.uid, self.idref)
143                 return False
144
145         def _tag_wizard(self, cr, rec, data_node=None):
146                 string = rec.getAttribute("string").encode('utf8')
147                 model = rec.getAttribute("model").encode('utf8')
148                 name = rec.getAttribute("name").encode('utf8')
149                 xml_id = rec.getAttribute('id').encode('utf8')
150                 multi = rec.hasAttribute('multi') and  eval(rec.getAttribute('multi'))
151                 res = {'name': string, 'wiz_name': name, 'multi':multi}
152
153                 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, mode=self.mode)
154                 self.idref[xml_id] = id
155                 # ir_set
156                 if not rec.hasAttribute('menu') or eval(rec.getAttribute('menu')):
157                         keyword = str(rec.getAttribute('keyword') or 'client_action_multi')
158                         keys = [('action',keyword),('res_model',model)]
159                         value = 'ir.actions.wizard,'+str(id)
160                         replace = rec.hasAttribute('replace') and rec.getAttribute("replace")
161                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True)
162                 return False
163
164         def _tag_ir_set(self, cr, rec, data_node=None):
165                 if not self.mode=='init':
166                         return False
167                 res = {}
168                 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
169                         f_name = field.getAttribute("name").encode('utf-8')
170                         f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
171                         res[f_name] = f_val
172                 self.pool.get('ir.model.data').ir_set(cr, self.uid, res['key'], res['key2'], res['name'], res['models'], res['value'], replace=res.get('replace',True), isobject=res.get('isobject', False), meta=res.get('meta',None))
173                 return False
174
175         def _tag_workflow(self, cr, rec, data_node=None):
176                 import netsvc
177                 model = str(rec.getAttribute('model'))
178                 wf_service = netsvc.LocalService("workflow")
179                 wf_service.trg_validate(self.uid, model,
180                         self.id_get(cr, model, rec.getAttribute('ref')),
181                         str(rec.getAttribute('action')), cr)
182                 return False
183
184         def _tag_menuitem(self, cr, rec, data_node=None):
185                 rec_id = rec.getAttribute("id").encode('ascii')
186                 m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8')))
187                 pid = False
188                 for idx, menu_elem in enumerate(m_l):
189                         if pid:
190                                 cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem))
191                         else:
192                                 cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,))
193                         res = cr.fetchone()
194                         if idx==len(m_l)-1:
195                                 # we are at the last menu element/level (it's a leaf)
196                                 values = {'parent_id': pid,'name':menu_elem}
197
198                                 if rec.hasAttribute('action'):
199                                         a_action = rec.getAttribute('action').encode('utf8')
200                                         a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
201                                         icons = {
202                                                 "act_window": 'STOCK_NEW',
203                                                 "report.xml": 'STOCK_PASTE',
204                                                 "wizard": 'STOCK_EXECUTE',
205                                         }
206                                         values['icon'] = icons.get(a_type,'STOCK_NEW')
207                                         if a_type=='act_window':
208                                                 a_id = self.id_get(cr, 'ir.actions.%s'% a_type, a_action)
209                                                 cr.execute('select view_type,view_mode from ir_act_window where id=%d', (int(a_id),))
210                                                 action_type,action_mode = cr.fetchone()
211                                                 if action_type=='tree':
212                                                         values['icon'] = 'STOCK_INDENT'
213                                                 elif action_mode and action_mode.startswith('tree'):
214                                                         values['icon'] = 'STOCK_JUSTIFY_FILL'
215                                                 elif action_mode and action_mode.startswith('graph'):
216                                                         values['icon'] = 'terp-account'
217                                 if rec.hasAttribute('sequence'):
218                                         values['sequence'] = int(rec.getAttribute('sequence'))
219                                 if rec.hasAttribute('icon'):
220                                         values['icon'] = str(rec.getAttribute('icon'))
221                                 if rec.hasAttribute('groups'):
222                                         g_names = rec.getAttribute('groups').split(',')
223                                         g_ids = []
224                                         for group in g_names:
225                                                 g_ids.extend(self.pool.get('res.groups').search(cr, self.uid, [('name', '=', group)]))
226                                         values['groups_id'] = [(6, 0, g_ids)]
227                                 xml_id = rec.getAttribute('id').encode('utf8')
228                                 pid = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.ui.menu', self.module, values, xml_id, idx==len(m_l)-1, mode=self.mode, res_id=res and res[0] or False)
229                         elif res:
230                                 # the menuitem already exists
231                                 pid = res[0]
232                                 xml_id = idx==len(m_l)-1 and rec.getAttribute('id').encode('utf8')
233                                 try:
234                                         npid = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1)
235                                 except:
236                                         print 'Menu Error', self.module, xml_id, idx==len(m_l)-1
237                         else:
238                                 # the menuitem does't exist but we are in branch (not a leaf)
239                                 pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
240                 if rec_id and pid:
241                         self.idref[rec_id] = pid
242
243                 if rec.hasAttribute('action') and pid:
244                         a_action = rec.getAttribute('action').encode('utf8')
245                         a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
246                         a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action)
247                         action = "ir.actions.%s,%d" % (a_type, a_id)
248                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True)
249                 return ('ir.ui.menu', pid)
250
251         def _tag_record(self, cr, rec, data_node=None):
252                 rec_model = rec.getAttribute("model").encode('ascii')
253                 model = self.pool.get(rec_model)
254                 assert model, "The model %s does not exist !" % (rec_model,)
255                 rec_id = rec.getAttribute("id").encode('ascii')
256
257 #               if not rec_id and not data_node.getAttribute('noupdate'):
258 #                       print "Warning", rec_model
259
260                 if data_node.getAttribute('noupdate') and not self.mode == 'init':
261                         # check if the xml record has an id string
262                         if rec_id:
263                                 id = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, rec_model, self.module, rec_id)
264                                 # check if the resource already existed at the last update
265                                 if id:
266                                         # if it existed, we don't update the data, but we need to 
267                                         # know the id of the existing record anyway
268                                         self.idref[rec_id] = id
269                                         return None
270                                 else:
271                                         # if the resource didn't exist
272                                         if rec.getAttribute("forcecreate"):
273                                                 # we want to create it, so we let the normal "update" behavior happen
274                                                 pass
275                                         else:
276                                                 # otherwise do nothing
277                                                 return None
278                         else:
279                                 # otherwise it is skipped
280                                 return None
281                                 
282                 res = {}
283                 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
284 #TODO: most of this code is duplicated above (in _eval_xml)...
285                         f_name = field.getAttribute("name").encode('utf-8')
286                         f_ref = field.getAttribute("ref").encode('ascii')
287                         f_search = field.getAttribute("search").encode('utf-8')
288                         f_model = field.getAttribute("model").encode('ascii')
289                         if not f_model and model._columns.get(f_name,False):
290                                 f_model = model._columns[f_name]._obj
291                         f_use = field.getAttribute("use").encode('ascii') or 'id'
292                         f_val = False
293
294                         if len(f_search):
295                                 q = eval(f_search, self.idref)
296                                 field = []
297                                 assert f_model, 'Define an attribute model="..." in your .XML file !'
298                                 f_obj = self.pool.get(f_model)
299                                 # browse the objects searched
300                                 s = f_obj.browse(cr, self.uid, f_obj.search(cr, self.uid, q))
301                                 # column definitions of the "local" object
302                                 _cols = self.pool.get(rec_model)._columns
303                                 # if the current field is many2many
304                                 if (f_name in _cols) and _cols[f_name]._type=='many2many':
305                                         f_val = [(6, 0, map(lambda x: x[f_use], s))]
306                                 elif len(s):
307                                         # otherwise (we are probably in a many2one field),
308                                         # take the first element of the search
309                                         f_val = s[0][f_use]
310                         elif len(f_ref):
311                                 if f_ref=="null":
312                                         f_val = False
313                                 else:
314                                         f_val = self.id_get(cr, f_model, f_ref)
315                         else:
316                                 f_val = _eval_xml(self,field, self.pool, cr, self.uid, self.idref)
317                                 if model._columns.has_key(f_name):
318                                         if isinstance(model._columns[f_name], osv.fields.integer):
319                                                 f_val = int(f_val)
320                         res[f_name] = f_val
321                 id = self.pool.get('ir.model.data')._update(cr, self.uid, rec_model, self.module, res, rec_id or False, not data_node.getAttribute('noupdate'), noupdate=data_node.getAttribute('noupdate'), mode=self.mode )
322                 if rec_id:
323                         self.idref[rec_id] = id
324                 return rec_model, id
325
326         def id_get(self, cr, model, id_str):
327                 if id_str in self.idref:
328                         return self.idref[id_str]
329                 mod = self.module
330                 if '.' in id_str:
331                         mod,id_str = id_str.split('.')
332                 result = self.pool.get('ir.model.data')._get_id(cr, self.uid, mod, id_str)
333                 return self.pool.get('ir.model.data').read(cr, self.uid, [result], ['res_id'])[0]['res_id']
334
335         def parse(self, xmlstr):
336                 d = xml.dom.minidom.parseString(xmlstr)
337                 de = d.documentElement
338                 for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="data")]:
339                         for rec in n.childNodes:
340                                 if rec.nodeType == rec.ELEMENT_NODE:
341                                         if rec.nodeName in self._tags:
342                                                 self._tags[rec.nodeName](self.cr, rec, n)
343                                                 #try:
344                                                 #       self._tags[rec.nodeName](self.cr, rec, n)
345                                                 #except:
346                                                 #       #print rec.toxml().decode('latin1')
347                                                 #       raise
348                 self.cr.commit()
349                 return True
350
351         def __init__(self, cr, module, idref, mode):
352                 self.mode = mode
353                 self.module = module
354                 self.cr = cr
355                 self.idref = idref
356                 self.pool = pooler.get_pool(cr.dbname)
357 #               self.pool = osv.osv.FakePool(module)
358                 self.uid = 1
359                 self._tags = {
360                         'menuitem': self._tag_menuitem,
361                         'record': self._tag_record,
362                         'report': self._tag_report,
363                         'wizard': self._tag_wizard,
364                         'delete': self._tag_delete,
365                         'ir_set': self._tag_ir_set,
366                         'function': self._tag_function,
367                         'workflow': self._tag_workflow,
368                 }
369
370 #
371 # Import a CSV file:
372 #     quote: "
373 #     delimiter: ,
374 #     encoding: UTF8
375 #
376 def convert_csv_import(cr, module, fname, csvcontent, idref={}, mode='init'):
377         if mode != 'init':
378                 return
379         model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]
380         #model = fname.split('.')[0].replace('_', '.')
381
382         #remove folder path from model
383         head, model = os.path.split(model)
384
385         pool = pooler.get_pool(cr.dbname)
386 #       pool = osv.osv.FakePool(module)
387
388         input=StringIO.StringIO(csvcontent)
389         data = list(csv.reader(input, quotechar='"', delimiter=','))
390
391         datas = []
392         for line in data:
393                 datas.append( map(lambda x:x.decode('utf8').encode('utf8'), line))
394
395         uid = 1
396         pool.get(model).import_data(cr, uid, data[0], datas[1:])
397         cr.commit()
398
399 #
400 # xml import/export
401 #
402 def convert_xml_import(cr, module, xmlstr, idref={}, mode='init'):
403         obj = xml_import(cr, module, idref, mode)
404         obj.parse(xmlstr)
405         del obj
406         return True
407
408 def convert_xml_export(res):
409         uid=1
410         pool=pooler.get_pool(cr.dbname)
411         cr=pooler.db.cursor()
412         idref = {}
413         d = xml.dom.minidom.getDOMImplementation().createDocument(None, "terp", None)
414         de = d.documentElement
415         data=d.createElement("data")
416         de.appendChild(data)
417         de.appendChild(d.createTextNode('Some textual content.'))
418         cr.commit()
419         cr.close()
420