You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

520 lines
19 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2017 Therp BV <http://therp.nl>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import logging
  5. try:
  6. import odoorpc
  7. except:
  8. logging.error('Unable to import odoorpc')
  9. import psycopg2
  10. import traceback
  11. from urlparse import urlparse
  12. from openerp import _, api, exceptions, fields, models, tools
  13. from collections import namedtuple
  14. import_context_tuple = namedtuple(
  15. 'import_context', [
  16. 'remote', 'model_line', 'ids', 'idmap', 'dummies', 'dummy_instances',
  17. 'to_delete', 'field_context',
  18. ]
  19. )
  20. class ImportContext(import_context_tuple):
  21. def with_field_context(self, *args):
  22. return ImportContext(*(self[:-1] + (field_context(*args),)))
  23. field_context = namedtuple(
  24. 'field_context', ['record_model', 'field_name', 'record_id'],
  25. )
  26. mapping_key = namedtuple('mapping_key', ['model_name', 'remote_id'])
  27. dummy_instance = namedtuple(
  28. 'dummy_instance', ['model_name', 'field_name', 'remote_id', 'dummy_id'],
  29. )
  30. class ImportOdooDatabase(models.Model):
  31. _name = 'import.odoo.database'
  32. _description = 'An Odoo database to import'
  33. url = fields.Char(required=True)
  34. database = fields.Char(required=True)
  35. user = fields.Char(default='admin', required=True)
  36. password = fields.Char(default='admin')
  37. import_line_ids = fields.One2many(
  38. 'import.odoo.database.model', 'database_id', string='Import models',
  39. )
  40. import_field_mappings = fields.One2many(
  41. 'import.odoo.database.field', 'database_id', string='Field mappings',
  42. )
  43. cronjob_id = fields.Many2one(
  44. 'ir.cron', string='Import job', readonly=True, copy=False,
  45. )
  46. cronjob_running = fields.Boolean(compute='_compute_cronjob_running')
  47. status_data = fields.Serialized('Status', readonly=True, copy=False)
  48. status_html = fields.Html(
  49. compute='_compute_status_html', readonly=True, sanitize=False,
  50. )
  51. @api.multi
  52. def action_import(self):
  53. """Create a cronjob to run the actual import"""
  54. self.ensure_one()
  55. if self.cronjob_id:
  56. return self.cronjob_id.write({
  57. 'numbercall': 1,
  58. 'doall': True,
  59. 'active': True,
  60. })
  61. return self.write({
  62. 'cronjob_id': self._create_cronjob().id,
  63. })
  64. @api.multi
  65. def _run_import(self, commit=True, commit_threshold=100):
  66. """Run the import as cronjob, commit often"""
  67. self.ensure_one()
  68. if not self.password:
  69. return
  70. # model name: [ids]
  71. remote_ids = {}
  72. # model name: count
  73. remote_counts = {}
  74. # model name: count
  75. done = {}
  76. # mapping_key: local_id
  77. idmap = {}
  78. # mapping_key: local_id
  79. # this are records created or linked when we need to fill a required
  80. # field, but the local record is not yet created
  81. dummies = {}
  82. # model name: [local_id]
  83. # this happens when we create a dummy we can throw away again
  84. to_delete = {}
  85. # dummy_instance
  86. dummy_instances = []
  87. remote = self._get_connection()
  88. self.write({'password': False})
  89. if commit and not tools.config['test_enable']:
  90. # pylint: disable=invalid-commit
  91. self.env.cr.commit()
  92. for model_line in self.import_line_ids:
  93. model = model_line.model_id
  94. remote_ids[model.model] = remote.execute(
  95. model.model, 'search',
  96. tools.safe_eval(model_line.domain) if model_line.domain else []
  97. )
  98. remote_counts[model.model] = len(remote_ids[model.model])
  99. self.write({
  100. 'status_data': {
  101. 'counts': remote_counts,
  102. 'ids': remote_ids,
  103. 'error': None,
  104. 'done': {},
  105. }
  106. })
  107. if commit and not tools.config['test_enable']:
  108. # pylint: disable=invalid-commit
  109. self.env.cr.commit()
  110. for model_line in self.import_line_ids:
  111. model = self.env[model_line.model_id.model]
  112. done[model._name] = 0
  113. chunk_len = commit and (commit_threshold or 1) or len(
  114. remote_ids[model._name]
  115. )
  116. for start_index in range(
  117. len(remote_ids[model._name]) / chunk_len + 1
  118. ):
  119. index = start_index * chunk_len
  120. ids = remote_ids[model._name][index:index + chunk_len]
  121. context = ImportContext(
  122. remote, model_line, ids, idmap, dummies, dummy_instances,
  123. to_delete, field_context(None, None, None),
  124. )
  125. try:
  126. self._run_import_model(context)
  127. except:
  128. error = traceback.format_exc()
  129. self.env.cr.rollback()
  130. self.write({
  131. 'status_data': dict(self.status_data, error=error),
  132. })
  133. # pylint: disable=invalid-commit
  134. self.env.cr.commit()
  135. raise
  136. done[model._name] += len(ids)
  137. self.write({'status_data': dict(self.status_data, done=done)})
  138. if commit and not tools.config['test_enable']:
  139. # pylint: disable=invalid-commit
  140. self.env.cr.commit()
  141. @api.multi
  142. def _run_import_model(self, context):
  143. """Import records of a configured model"""
  144. model = self.env[context.model_line.model_id.model]
  145. fields = self._run_import_model_get_fields(context)
  146. for data in context.remote.execute(
  147. model._name, 'read', context.ids, fields.keys()
  148. ):
  149. self._run_import_get_record(context, model, data)
  150. if (model._name, data['id']) in context.idmap:
  151. # there's a mapping for this record, nothing to do
  152. continue
  153. data = self._run_import_map_values(context, data)
  154. _id = data['id']
  155. record = self._create_record(context, model, data)
  156. self._run_import_model_cleanup_dummies(
  157. context, model, _id, record.id,
  158. )
  159. @api.multi
  160. def _create_record(self, context, model, record):
  161. """Create a record, add an xmlid"""
  162. _id = record.pop('id')
  163. xmlid = '%d-%s-%d' % (
  164. self.id, model._name.replace('.', '_'), _id,
  165. )
  166. if self.env.ref('base_import_odoo.%s' % xmlid, False):
  167. new = self.env.ref('base_import_odoo.%s' % xmlid)
  168. new.with_context(
  169. **self._create_record_context(model, record)
  170. ).write(record)
  171. else:
  172. new = model.with_context(
  173. **self._create_record_context(model, record)
  174. ).create(record)
  175. self.env['ir.model.data'].create({
  176. 'name': xmlid,
  177. 'model': model._name,
  178. 'module': 'base_import_odoo',
  179. 'res_id': new.id,
  180. 'noupdate': True,
  181. 'import_database_id': self.id,
  182. 'import_database_record_id': _id,
  183. })
  184. context.idmap[mapping_key(model._name, _id)] = new.id
  185. return new
  186. def _create_record_context(self, model, record):
  187. """Return a context that is used when creating a record"""
  188. context = {
  189. 'tracking_disable': True,
  190. }
  191. if model._name == 'res.users':
  192. context['no_reset_password'] = True
  193. return context
  194. @api.multi
  195. def _run_import_get_record(
  196. self, context, model, record, create_dummy=True,
  197. ):
  198. """Find the local id of some remote record. Create a dummy if not
  199. available"""
  200. _id = context.idmap.get((model._name, record['id']))
  201. if not _id:
  202. _id = context.dummies.get((model._name, record['id']))
  203. if _id:
  204. context.dummy_instances.append(
  205. dummy_instance(*(context.field_context + (_id,)))
  206. )
  207. if not _id:
  208. _id = self._run_import_get_record_mapping(
  209. context, model, record, create_dummy=create_dummy,
  210. )
  211. if not _id:
  212. xmlid = self.env['ir.model.data'].search([
  213. ('import_database_id', '=', self.id),
  214. ('import_database_record_id', '=', record['id']),
  215. ('model', '=', model._name),
  216. ], limit=1)
  217. if xmlid:
  218. _id = xmlid.res_id
  219. context.idmap[(model._name, record['id'])] = _id
  220. if not _id and create_dummy:
  221. _id = self._run_import_create_dummy(context, model, record)
  222. return _id
  223. @api.multi
  224. def _run_import_get_record_mapping(
  225. self, context, model, record, create_dummy=True,
  226. ):
  227. current_field = self.env['ir.model.fields'].search([
  228. ('name', '=', context.field_context.field_name),
  229. ('model_id.model', '=', context.field_context.record_model),
  230. ])
  231. mappings = self.import_field_mappings.filtered(
  232. lambda x:
  233. x.mapping_type == 'fixed' and
  234. x.model_id.model == model._name and
  235. (
  236. not x.field_ids or current_field in x.field_ids
  237. ) and x.local_id and
  238. (x.remote_id == record['id'] or not x.remote_id) or
  239. x.mapping_type == 'by_field' and
  240. x.model_id.model == model._name
  241. )
  242. _id = None
  243. for mapping in mappings:
  244. if mapping.mapping_type == 'fixed':
  245. assert mapping.local_id
  246. _id = mapping.local_id
  247. context.idmap[(model._name, record['id'])] = _id
  248. break
  249. elif mapping.mapping_type == 'by_field':
  250. assert mapping.field_ids
  251. if len(record) == 1:
  252. continue
  253. records = model.search([
  254. (field.name, '=', record[field.name])
  255. for field in mapping.field_ids
  256. ], limit=1)
  257. if records:
  258. _id = records.id
  259. context.idmap[(model._name, record['id'])] = _id
  260. break
  261. else:
  262. raise exceptions.UserError(_('Unknown mapping'))
  263. return _id
  264. @api.multi
  265. def _run_import_create_dummy(
  266. self, context, model, record, forcecreate=False,
  267. ):
  268. """Either misuse some existing record or create an empty one to satisfy
  269. required links"""
  270. dummy = model.search([
  271. (
  272. 'id', 'not in',
  273. [
  274. v for (model_name, remote_id), v
  275. in context.dummies.items()
  276. if model_name == model._name
  277. ] +
  278. [
  279. mapping.local_id for mapping
  280. in self.import_field_mappings
  281. if mapping.model_id.model == model._name and
  282. mapping.local_id
  283. ]
  284. ),
  285. ], limit=1)
  286. if dummy and not forcecreate:
  287. context.dummies[mapping_key(model._name, record['id'])] = dummy.id
  288. context.dummy_instances.append(
  289. dummy_instance(*(context.field_context + (dummy.id,)))
  290. )
  291. return dummy.id
  292. required = [
  293. name
  294. for name, field in model._fields.items()
  295. if field.required
  296. ]
  297. defaults = model.default_get(required)
  298. values = {'id': record['id']}
  299. for name, field in model._fields.items():
  300. if name not in required or name in defaults:
  301. continue
  302. value = None
  303. if field.type in ['char', 'text', 'html']:
  304. value = ''
  305. elif field.type in ['boolean']:
  306. value = False
  307. elif field.type in ['integer', 'float']:
  308. value = 0
  309. elif model._fields[name].type in ['date', 'datetime']:
  310. value = '2000-01-01'
  311. elif field.type in ['many2one']:
  312. new_context = context.with_field_context(
  313. model._name, name, record['id']
  314. )
  315. value = self._run_import_get_record(
  316. new_context,
  317. self.env[model._fields[name].comodel_name],
  318. {'id': record.get(name, [None])[0]},
  319. )
  320. elif field.type in ['selection'] and not callable(field.selection):
  321. value = field.selection[0][0]
  322. elif field.type in ['selection'] and callable(field.selection):
  323. value = field.selection(model)[0][0]
  324. values[name] = value
  325. dummy = self._create_record(context, model, values)
  326. context.dummies[mapping_key(model._name, record['id'])] = dummy.id
  327. context.to_delete.setdefault(model._name, [])
  328. context.to_delete[model._name].append(dummy.id)
  329. context.dummy_instances.append(
  330. dummy_instance(*(context.field_context + (dummy.id,)))
  331. )
  332. return dummy.id
  333. @api.multi
  334. def _run_import_map_values(self, context, data):
  335. model = self.env[context.model_line.model_id.model]
  336. for field_name in data.keys():
  337. if not isinstance(
  338. model._fields[field_name], fields._Relational
  339. ) or not data[field_name]:
  340. continue
  341. if model._fields[field_name].type == 'one2many':
  342. # don't import one2many fields, use an own configuration
  343. # for this
  344. data.pop(field_name)
  345. continue
  346. ids = data[field_name] if (
  347. model._fields[field_name].type != 'many2one'
  348. ) else [data[field_name][0]]
  349. new_context = context.with_field_context(
  350. model._name, field_name, data['id']
  351. )
  352. comodel = self.env[model._fields[field_name].comodel_name]
  353. data[field_name] = [
  354. self._run_import_get_record(
  355. new_context, comodel, {'id': _id},
  356. create_dummy=model._fields[field_name].required or
  357. any(
  358. m.model_id._name == comodel._name
  359. for m in self.import_line_ids
  360. ),
  361. )
  362. for _id in ids
  363. ]
  364. data[field_name] = filter(None, data[field_name])
  365. if model._fields[field_name].type == 'many2one':
  366. if data[field_name]:
  367. data[field_name] = data[field_name] and data[field_name][0]
  368. else:
  369. data[field_name] = None
  370. else:
  371. data[field_name] = [(6, 0, data[field_name])]
  372. for mapping in self.import_field_mappings:
  373. if mapping.model_id.model != model._name or\
  374. mapping.mapping_type != 'unique':
  375. continue
  376. for field in mapping.field_ids:
  377. value = data.get(field.name, '')
  378. counter = 1
  379. while model.with_context(active_test=False).search([
  380. (field.name, '=', data.get(field.name, value)),
  381. ]):
  382. data[field.name] = '%s (%d)' % (value, counter)
  383. counter += 1
  384. return data
  385. @api.multi
  386. def _run_import_model_get_fields(self, context):
  387. return {
  388. name: field
  389. for name, field
  390. in self.env[context.model_line.model_id.model]._fields.items()
  391. if not field.compute or field.related
  392. }
  393. @api.multi
  394. def _run_import_model_cleanup_dummies(
  395. self, context, model, remote_id, local_id
  396. ):
  397. for instance in context.dummy_instances:
  398. if (
  399. instance.model_name != model._name or
  400. instance.remote_id != remote_id
  401. ):
  402. continue
  403. if not context.idmap.get(instance.remote_id):
  404. continue
  405. model = self.env[instance.model_name]
  406. record = model.browse(context.idmap[instance.remote_id])
  407. field_name = instance.field_id.name
  408. if record._fields[field_name].type == 'many2one':
  409. record.write({field_name: local_id})
  410. elif record._fields[field_name].type == 'many2many':
  411. record.write({field_name: [
  412. (3, context.idmap[remote_id]),
  413. (4, local_id),
  414. ]})
  415. else:
  416. raise exceptions.UserError(
  417. _('Unhandled field type %s') %
  418. record._fields[field_name].type
  419. )
  420. context.dummy_instances.remove(instance)
  421. dummy_id = context.dummies[(record._model, remote_id)]
  422. if dummy_id in context.to_delete:
  423. model.browse(dummy_id).unlink()
  424. del context.dummies[(record._model, remote_id)]
  425. def _get_connection(self):
  426. self.ensure_one()
  427. url = urlparse(self.url)
  428. hostport = url.netloc.split(':')
  429. if len(hostport) == 1:
  430. hostport.append('80')
  431. host, port = hostport
  432. remote = odoorpc.ODOO(
  433. host,
  434. protocol='jsonrpc+ssl' if url.scheme == 'https' else 'jsonrpc',
  435. port=int(port),
  436. )
  437. remote.login(self.database, self.user, self.password)
  438. return remote
  439. @api.constrains('url', 'database', 'user', 'password')
  440. @api.multi
  441. def _constrain_url(self):
  442. for this in self:
  443. if this == self.env.ref('base_import_odoo.demodb', False):
  444. continue
  445. if tools.config['test_enable']:
  446. continue
  447. if not this.password:
  448. continue
  449. this._get_connection()
  450. @api.depends('status_data')
  451. @api.multi
  452. def _compute_status_html(self):
  453. for this in self:
  454. if not this.status_data:
  455. continue
  456. this.status_html = self.env.ref(
  457. 'base_import_odoo.view_import_odoo_database_qweb'
  458. ).render({'object': this})
  459. @api.depends('cronjob_id')
  460. @api.multi
  461. def _compute_cronjob_running(self):
  462. for this in self:
  463. if not this.cronjob_id:
  464. continue
  465. try:
  466. with self.env.cr.savepoint():
  467. self.env.cr.execute(
  468. 'select id from "%s" where id=%%s for update nowait' %
  469. self.env['ir.cron']._table,
  470. (this.cronjob_id.id,), log_exceptions=False,
  471. )
  472. except psycopg2.OperationalError:
  473. this.cronjob_running = True
  474. @api.multi
  475. def _create_cronjob(self):
  476. self.ensure_one()
  477. return self.env['ir.cron'].create({
  478. 'name': self.display_name,
  479. 'model': self._name,
  480. 'function': '_run_import',
  481. 'doall': True,
  482. 'args': str((self.ids,)),
  483. })
  484. @api.multi
  485. def name_get(self):
  486. return [
  487. (this.id, '%s@%s, %s' % (this.user, this.url, this.database))
  488. for this in self
  489. ]