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.

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