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.

64 lines
2.2 KiB

  1. # Copyright (C) 2015 Forest and Biomass Romania
  2. # Copyright (C) 2020 NextERP Romania
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import logging
  5. from odoo import _, api, models
  6. from odoo.exceptions import UserError
  7. _logger = logging.getLogger(__name__)
  8. try:
  9. from stdnum.eu.vat import check_vies
  10. except ImportError:
  11. _logger.debug("Cannot import check_vies method from python stdnum.")
  12. class ResPartner(models.Model):
  13. _inherit = "res.partner"
  14. @api.model
  15. def _get_vies_data(self, vat, raise_if_fail=False):
  16. res = {}
  17. try:
  18. result = check_vies(vat)
  19. except Exception as e:
  20. _logger.warning("Failed to query VIES: %s" % e)
  21. if raise_if_fail:
  22. raise UserError(_("Failed to query VIES.\nTechnical error: %s.") % e)
  23. return res
  24. if result.valid and result.name:
  25. res["vat"] = vat
  26. # Update partner name if listed on VIES
  27. if result.name != "---":
  28. res["name"] = result.name.upper()
  29. # Update partner address if listed on VIES
  30. if result.address != "---":
  31. res["street"] = (
  32. result.address.replace("\n", " ").replace("\r", "").title()
  33. )
  34. # Get country by country code
  35. country = self.env["res.country"].search(
  36. [("code", "ilike", result.countryCode)]
  37. )
  38. if country:
  39. res["country_id"] = country[0].id
  40. return res
  41. @api.onchange("vat")
  42. def vies_vat_change(self):
  43. eu_group = self.env.ref("base.europe", raise_if_not_found=False)
  44. if eu_group:
  45. for partner in self:
  46. if not partner.vat or not partner.is_company:
  47. continue
  48. vat = partner.vat.strip().upper()
  49. vat_country, vat_number = self._split_vat(vat)
  50. vat_country = vat_country.upper()
  51. eu_countries = eu_group.country_ids.mapped("code")
  52. if vat_country and vat_country not in eu_countries:
  53. continue
  54. result = self._get_vies_data(vat)
  55. if result:
  56. partner.update(result)