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.

146 lines
5.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2014 Alexis de Lattre <alexis.delattre@akretion.com>
  3. # © 2014 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
  4. # © 2016 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
  5. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  6. from openerp import models, fields, api, _
  7. from openerp.exceptions import UserError
  8. import requests
  9. import tempfile
  10. import StringIO
  11. import zipfile
  12. import os
  13. import logging
  14. try:
  15. import unicodecsv
  16. except ImportError:
  17. unicodecsv = None
  18. logger = logging.getLogger(__name__)
  19. class BetterZipGeonamesImport(models.TransientModel):
  20. _name = 'better.zip.geonames.import'
  21. _description = 'Import Better Zip from Geonames'
  22. _rec_name = 'country_id'
  23. country_id = fields.Many2one('res.country', 'Country', required=True)
  24. title_case = fields.Boolean(
  25. string='Title Case',
  26. help='Converts retreived city and state names to Title Case.',
  27. )
  28. @api.model
  29. def transform_city_name(self, city, country):
  30. """Override it for transforming city name (if needed)
  31. :param city: Original city name
  32. :param country: Country record
  33. :return: Transformed city name
  34. """
  35. return city
  36. @api.model
  37. def _domain_search_better_zip(self, row, country):
  38. return [('name', '=', row[1]),
  39. ('city', '=', self.transform_city_name(row[2], country)),
  40. ('country_id', '=', country.id)]
  41. @api.model
  42. def _prepare_better_zip(self, row, country):
  43. state = self.select_or_create_state(row, country)
  44. vals = {
  45. 'name': row[1],
  46. 'city': self.transform_city_name(row[2], country),
  47. 'state_id': state.id,
  48. 'country_id': country.id,
  49. }
  50. return vals
  51. @api.model
  52. def create_better_zip(self, row, country):
  53. if row[0] != country.code:
  54. raise UserError(
  55. _("The country code inside the file (%s) doesn't "
  56. "correspond to the selected country (%s).")
  57. % (row[0], country.code))
  58. logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
  59. if (self.title_case):
  60. row[2] = row[2].title()
  61. row[3] = row[3].title()
  62. if row[1] and row[2]:
  63. zip_model = self.env['res.better.zip']
  64. zips = zip_model.search(self._domain_search_better_zip(
  65. row, country))
  66. if zips:
  67. return zips[0]
  68. else:
  69. vals = self._prepare_better_zip(row, country)
  70. if vals:
  71. return zip_model.create(vals)
  72. else:
  73. return False
  74. @api.model
  75. def select_or_create_state(
  76. self, row, country, code_row_index=4, name_row_index=3):
  77. states = self.env['res.country.state'].search([
  78. ('country_id', '=', country.id),
  79. ('code', '=', row[code_row_index]),
  80. ])
  81. if len(states) > 1:
  82. raise UserError(
  83. _("Too many states with code %s for country %s")
  84. % (row[code_row_index], country.code))
  85. if len(states) == 1:
  86. return states[0]
  87. else:
  88. return self.env['res.country.state'].create({
  89. 'name': row[name_row_index],
  90. 'code': row[code_row_index],
  91. 'country_id': country.id
  92. })
  93. @api.multi
  94. def run_import(self):
  95. self.ensure_one()
  96. zip_model = self.env['res.better.zip']
  97. country_code = self.country_id.code
  98. config_url = self.env['ir.config_parameter'].get_param(
  99. 'geonames.url',
  100. default='http://download.geonames.org/export/zip/%s.zip')
  101. url = config_url % country_code
  102. logger.info('Starting to download %s' % url)
  103. res_request = requests.get(url)
  104. if res_request.status_code != requests.codes.ok:
  105. raise UserError(
  106. _('Got an error %d when trying to download the file %s.')
  107. % (res_request.status_code, url))
  108. # Store current record list
  109. zips_to_delete = zip_model.search(
  110. [('country_id', '=', self.country_id.id)])
  111. f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
  112. tempdir = tempfile.mkdtemp(prefix='openerp')
  113. f_geonames.extract('%s.txt' % country_code, tempdir)
  114. logger.info('The geonames zipfile has been decompressed')
  115. data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
  116. data_file.seek(0)
  117. logger.info('Starting to create the better zip entries')
  118. max_import = self.env.context.get('max_import', 0)
  119. reader = unicodecsv.reader(data_file, encoding='utf-8', delimiter=' ')
  120. for i, row in enumerate(reader):
  121. zip_code = self.create_better_zip(row, self.country_id)
  122. if zip_code in zips_to_delete:
  123. zips_to_delete -= zip_code
  124. if max_import and (i + 1) == max_import:
  125. break
  126. data_file.close()
  127. if zips_to_delete and not max_import:
  128. zips_to_delete.unlink()
  129. logger.info('%d better zip entries deleted for country %s' %
  130. (len(zips_to_delete), self.country_id.name))
  131. logger.info(
  132. 'The wizard to create better zip entries from geonames '
  133. 'has been successfully completed.')
  134. return True