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