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.

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