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.

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