iap_autocomplete_api.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import logging
  4. from odoo import api, models, exceptions, _
  5. from odoo.addons.iap.tools import iap_tools
  6. from requests.exceptions import HTTPError
  7. _logger = logging.getLogger(__name__)
  8. class IapAutocompleteEnrichAPI(models.AbstractModel):
  9. _name = 'iap.autocomplete.api'
  10. _description = 'IAP Partner Autocomplete API'
  11. _DEFAULT_ENDPOINT = 'https://partner-autocomplete.odoo.com'
  12. @api.model
  13. def _contact_iap(self, local_endpoint, action, params, timeout=15):
  14. if self.env.registry.in_test_mode():
  15. raise exceptions.ValidationError(_('Test mode'))
  16. account = self.env['iap.account'].get('partner_autocomplete')
  17. if not account.account_token:
  18. raise ValueError(_('No account token'))
  19. params.update({
  20. 'db_uuid': self.env['ir.config_parameter'].sudo().get_param('database.uuid'),
  21. 'account_token': account.account_token,
  22. 'country_code': self.env.company.country_id.code,
  23. 'zip': self.env.company.zip,
  24. })
  25. base_url = self.env['ir.config_parameter'].sudo().get_param('iap.partner_autocomplete.endpoint', self._DEFAULT_ENDPOINT)
  26. return iap_tools.iap_jsonrpc(base_url + local_endpoint + '/' + action, params=params, timeout=timeout)
  27. @api.model
  28. def _request_partner_autocomplete(self, action, params, timeout=15):
  29. """ Contact endpoint to get autocomplete data.
  30. :return tuple: results, error code
  31. """
  32. try:
  33. results = self._contact_iap('/iap/partner_autocomplete', action, params, timeout=timeout)
  34. except exceptions.ValidationError:
  35. return False, 'Insufficient Credit'
  36. except (ConnectionError, HTTPError, exceptions.AccessError, exceptions.UserError) as exception:
  37. _logger.warning('Autocomplete API error: %s', str(exception))
  38. return False, str(exception)
  39. except iap_tools.InsufficientCreditError as exception:
  40. _logger.warning('Insufficient Credits for Autocomplete Service: %s', str(exception))
  41. return False, 'Insufficient Credit'
  42. except ValueError:
  43. return False, 'No account token'
  44. return results, False