1 #----------------------------------------------------------
3 #----------------------------------------------------------
5 import StringIO,xml.dom.minidom
11 from config import config
14 # Number of imported lines between two commit (see convert_csv_import()):
18 class ConvertError(Exception):
19 def __init__(self, doc, orig_excpt):
21 self.orig = orig_excpt
24 return 'Exception:\n\t%s\nUsing file:\n%s' % (self.orig, self.d)
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')
39 q = eval(f_search, idref)
40 ids = pool.get(f_model).search(cr, uid, q)
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':
49 if isinstance(f_val, tuple):
52 a_eval = node.getAttribute('eval')
56 idref['ref'] = lambda x: self.id_get(cr, False, x)
61 logger = netsvc.Logger()
62 logger.notifyChannel("init", netsvc.LOG_INFO, 'could not find pytz library')
63 class pytzclass(object):
67 return eval(a_eval, idref)
69 def _process(s, idref):
70 m = re.findall('[^%]%\((.*?)\)[ds]', s)
73 idref[id]=self.id_get(cr, False, id)
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
79 if t in ('char', 'int', 'float'):
81 for n in [i for i in node.childNodes]:
82 d+=str(_eval_xml(self,n,pool,cr,uid,idref))
92 elif t in ('list','tuple'):
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))
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)
104 elif node.getAttribute('type') in ("int", "list"):
105 return res[int(node.getAttribute('index'))]
107 return res[node.getAttribute('index').encode("utf8")]
108 elif node.nodeName=="function":
110 a_eval = node.getAttribute('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)
121 escape_re = re.compile(r'(?<!\\)/')
123 return x.replace('\\/', '/')
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))
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)
135 def _tag_report(self, cr, rec, data_node=None):
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)
158 def _tag_function(self, cr, rec, data_node=None):
159 _eval_xml(self,rec, self.pool, cr, self.uid, self.idref)
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}
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
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)
181 def _tag_ir_set(self, cr, rec, data_node=None):
182 if not self.mode=='init':
185 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
186 f_name = field.getAttribute("name").encode('utf-8')
187 f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
189 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))
192 def _tag_workflow(self, cr, rec, data_node=None):
194 model = str(rec.getAttribute('model'))
195 wf_service = netsvc.LocalService("workflow")
196 wf_service.trg_validate(self.uid, model,
197 self.id_get(cr, model, rec.getAttribute('ref')),
198 str(rec.getAttribute('action')), cr)
201 def _tag_menuitem(self, cr, rec, data_node=None):
202 rec_id = rec.getAttribute("id").encode('ascii')
203 m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8')))
205 for idx, menu_elem in enumerate(m_l):
207 cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem))
209 cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,))
212 # we are at the last menu element/level (it's a leaf)
213 values = {'parent_id': pid,'name':menu_elem}
215 if rec.hasAttribute('action'):
216 a_action = rec.getAttribute('action').encode('utf8')
217 a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
219 "act_window": 'STOCK_NEW',
220 "report.xml": 'STOCK_PASTE',
221 "wizard": 'STOCK_EXECUTE',
223 values['icon'] = icons.get(a_type,'STOCK_NEW')
224 if a_type=='act_window':
225 a_id = self.id_get(cr, 'ir.actions.%s'% a_type, a_action)
226 cr.execute('select view_type,view_mode from ir_act_window where id=%d', (int(a_id),))
227 action_type,action_mode = cr.fetchone()
228 if action_type=='tree':
229 values['icon'] = 'STOCK_INDENT'
230 elif action_mode and action_mode.startswith('tree'):
231 values['icon'] = 'STOCK_JUSTIFY_FILL'
232 elif action_mode and action_mode.startswith('graph'):
233 values['icon'] = 'terp-account'
234 if rec.hasAttribute('sequence'):
235 values['sequence'] = int(rec.getAttribute('sequence'))
236 if rec.hasAttribute('icon'):
237 values['icon'] = str(rec.getAttribute('icon'))
238 if rec.hasAttribute('groups'):
239 g_names = rec.getAttribute('groups').split(',')
241 for group in g_names:
242 g_ids.extend(self.pool.get('res.groups').search(cr, self.uid, [('name', '=', group)]))
243 values['groups_id'] = [(6, 0, g_ids)]
244 xml_id = rec.getAttribute('id').encode('utf8')
245 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)
247 # the menuitem already exists
249 xml_id = idx==len(m_l)-1 and rec.getAttribute('id').encode('utf8')
251 npid = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1)
253 print 'Menu Error', self.module, xml_id, idx==len(m_l)-1
255 # the menuitem does't exist but we are in branch (not a leaf)
256 pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
258 self.idref[rec_id] = pid
260 if rec.hasAttribute('action') and pid:
261 a_action = rec.getAttribute('action').encode('utf8')
262 a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
263 a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action)
264 action = "ir.actions.%s,%d" % (a_type, a_id)
265 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True)
266 return ('ir.ui.menu', pid)
268 def _tag_record(self, cr, rec, data_node=None):
269 rec_model = rec.getAttribute("model").encode('ascii')
270 model = self.pool.get(rec_model)
271 assert model, "The model %s does not exist !" % (rec_model,)
272 rec_id = rec.getAttribute("id").encode('ascii')
274 # if not rec_id and not data_node.getAttribute('noupdate'):
275 # print "Warning", rec_model
277 if data_node.getAttribute('noupdate') and not self.mode == 'init':
278 # check if the xml record has an id string
280 id = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, rec_model, self.module, rec_id)
281 # check if the resource already existed at the last update
283 # if it existed, we don't update the data, but we need to
284 # know the id of the existing record anyway
285 self.idref[rec_id] = id
288 # if the resource didn't exist
289 if rec.getAttribute("forcecreate"):
290 # we want to create it, so we let the normal "update" behavior happen
293 # otherwise do nothing
296 # otherwise it is skipped
300 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
301 #TODO: most of this code is duplicated above (in _eval_xml)...
302 f_name = field.getAttribute("name").encode('utf-8')
303 f_ref = field.getAttribute("ref").encode('ascii')
304 f_search = field.getAttribute("search").encode('utf-8')
305 f_model = field.getAttribute("model").encode('ascii')
306 if not f_model and model._columns.get(f_name,False):
307 f_model = model._columns[f_name]._obj
308 f_use = field.getAttribute("use").encode('ascii') or 'id'
312 q = eval(f_search, self.idref)
314 assert f_model, 'Define an attribute model="..." in your .XML file !'
315 f_obj = self.pool.get(f_model)
316 # browse the objects searched
317 s = f_obj.browse(cr, self.uid, f_obj.search(cr, self.uid, q))
318 # column definitions of the "local" object
319 _cols = self.pool.get(rec_model)._columns
320 # if the current field is many2many
321 if (f_name in _cols) and _cols[f_name]._type=='many2many':
322 f_val = [(6, 0, map(lambda x: x[f_use], s))]
324 # otherwise (we are probably in a many2one field),
325 # take the first element of the search
331 f_val = self.id_get(cr, f_model, f_ref)
333 f_val = _eval_xml(self,field, self.pool, cr, self.uid, self.idref)
334 if model._columns.has_key(f_name):
335 if isinstance(model._columns[f_name], osv.fields.integer):
338 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 )
340 self.idref[rec_id] = id
343 def id_get(self, cr, model, id_str):
344 if id_str in self.idref:
345 return self.idref[id_str]
348 mod,id_str = id_str.split('.')
349 result = self.pool.get('ir.model.data')._get_id(cr, self.uid, mod, id_str)
350 return self.pool.get('ir.model.data').read(cr, self.uid, [result], ['res_id'])[0]['res_id']
352 def parse(self, xmlstr):
353 d = xml.dom.minidom.parseString(xmlstr)
354 de = d.documentElement
355 for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="data")]:
356 for rec in n.childNodes:
357 if rec.nodeType == rec.ELEMENT_NODE:
358 if rec.nodeName in self._tags:
359 self._tags[rec.nodeName](self.cr, rec, n)
361 # self._tags[rec.nodeName](self.cr, rec, n)
363 # #print rec.toxml().decode('latin1')
368 def __init__(self, cr, module, idref, mode):
373 self.pool = pooler.get_pool(cr.dbname)
374 # self.pool = osv.osv.FakePool(module)
377 'menuitem': self._tag_menuitem,
378 'record': self._tag_record,
379 'report': self._tag_report,
380 'wizard': self._tag_wizard,
381 'delete': self._tag_delete,
382 'ir_set': self._tag_ir_set,
383 'function': self._tag_function,
384 'workflow': self._tag_workflow,
393 def convert_csv_import(cr, module, fname, csvcontent, idref={}, mode='init'):
396 model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]
397 #model = fname.split('.')[0].replace('_', '.')
399 #remove folder path from model
400 head, model = os.path.split(model)
402 pool = pooler.get_pool(cr.dbname)
403 # pool = osv.osv.FakePool(module)
405 input=StringIO.StringIO(csvcontent)
406 reader = csv.reader(input, quotechar='"', delimiter=',')
407 fields = reader.next()
412 datas.append( map(lambda x:x.decode('utf8').encode('utf8'), line))
413 if len(datas) > COMMIT_STEP:
414 pool.get(model).import_data(cr, uid, fields, datas)
419 pool.get(model).import_data(cr, uid, fields, datas)
425 def convert_xml_import(cr, module, xmlstr, idref={}, mode='init'):
426 obj = xml_import(cr, module, idref, mode)
431 def convert_xml_export(res):
433 pool=pooler.get_pool(cr.dbname)
434 cr=pooler.db.cursor()
436 d = xml.dom.minidom.getDOMImplementation().createDocument(None, "terp", None)
437 de = d.documentElement
438 data=d.createElement("data")
440 de.appendChild(d.createTextNode('Some textual content.'))