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.

155 lines
5.7 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2014-2016 Akretion (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 odoo import _, api, fields, models, tools
  7. from odoo.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. letter_case = fields.Selection([
  25. ('unchanged', 'Unchanged'),
  26. ('title', 'Title Case'),
  27. ('upper', 'Upper Case'),
  28. ], string='Letter Case', default='unchanged',
  29. help="Converts retreived city and state names to Title Case "
  30. "(upper case on each first letter of a word) or Upper Case "
  31. "(all letters upper case).")
  32. @api.model
  33. def transform_city_name(self, city, country):
  34. """Override it for transforming city name (if needed)
  35. :param city: Original city name
  36. :param country: Country record
  37. :return: Transformed city name
  38. """
  39. return city
  40. @api.model
  41. def _domain_search_better_zip(self, row, country):
  42. return [('name', '=', row[1]),
  43. ('city', '=', self.transform_city_name(row[2], country)),
  44. ('country_id', '=', country.id)]
  45. @api.model
  46. def _prepare_better_zip(self, row, country):
  47. state = self.select_or_create_state(row, country)
  48. vals = {
  49. 'name': row[1],
  50. 'city': self.transform_city_name(row[2], country),
  51. 'state_id': state.id,
  52. 'country_id': country.id,
  53. }
  54. return vals
  55. @api.model
  56. def create_better_zip(self, row, country):
  57. if row[0] != country.code:
  58. raise UserError(
  59. _("The country code inside the file (%s) doesn't "
  60. "correspond to the selected country (%s).")
  61. % (row[0], country.code))
  62. logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
  63. if self.letter_case == 'title':
  64. row[2] = row[2].title()
  65. row[3] = row[3].title()
  66. elif self.letter_case == 'upper':
  67. row[2] = row[2].upper()
  68. row[3] = row[3].upper()
  69. if row[1] and row[2]:
  70. zip_model = self.env['res.better.zip']
  71. zips = zip_model.search(self._domain_search_better_zip(
  72. row, country))
  73. if zips:
  74. return zips[0]
  75. else:
  76. vals = self._prepare_better_zip(row, country)
  77. if vals:
  78. return zip_model.create(vals)
  79. else: # pragma: no cover
  80. return False
  81. @tools.ormcache('country_id', 'code')
  82. def _get_state(self, country_id, code, name):
  83. state = self.env['res.country.state'].search(
  84. [('country_id', '=', country_id),
  85. ('code', '=', code)], limit=1,
  86. )
  87. if state: # pragma: no cover
  88. return state
  89. else:
  90. return self.env['res.country.state'].create({
  91. 'name': name,
  92. 'code': code,
  93. 'country_id': country_id,
  94. })
  95. @api.model
  96. def select_or_create_state(
  97. self, row, country, code_row_index=4, name_row_index=3):
  98. return self._get_state(
  99. country.id, row[code_row_index], row[name_row_index],
  100. )
  101. @api.multi
  102. def run_import(self):
  103. self.ensure_one()
  104. zip_model = self.env['res.better.zip']
  105. country_code = self.country_id.code
  106. config_url = self.env['ir.config_parameter'].get_param(
  107. 'geonames.url',
  108. default='http://download.geonames.org/export/zip/%s.zip')
  109. url = config_url % country_code
  110. logger.info('Starting to download %s' % url)
  111. res_request = requests.get(url)
  112. if res_request.status_code != requests.codes.ok:
  113. raise UserError(
  114. _('Got an error %d when trying to download the file %s.')
  115. % (res_request.status_code, url))
  116. # Store current record list
  117. zips_to_delete = zip_model.search(
  118. [('country_id', '=', self.country_id.id)])
  119. f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
  120. tempdir = tempfile.mkdtemp(prefix='openerp')
  121. f_geonames.extract('%s.txt' % country_code, tempdir)
  122. logger.info('The geonames zipfile has been decompressed')
  123. data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
  124. data_file.seek(0)
  125. logger.info('Starting to create the better zip entries')
  126. max_import = self.env.context.get('max_import', 0)
  127. reader = unicodecsv.reader(data_file, encoding='utf-8', delimiter=' ')
  128. for i, row in enumerate(reader):
  129. zip_code = self.create_better_zip(row, self.country_id)
  130. if zip_code in zips_to_delete:
  131. zips_to_delete -= zip_code
  132. if max_import and (i + 1) == max_import:
  133. break
  134. data_file.close()
  135. if zips_to_delete and not max_import:
  136. zips_to_delete.unlink()
  137. logger.info('%d better zip entries deleted for country %s' %
  138. (len(zips_to_delete), self.country_id.name))
  139. logger.info(
  140. 'The wizard to create better zip entries from geonames '
  141. 'has been successfully completed.')
  142. return True