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.

153 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 models, fields, api, _
  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:
  80. return False
  81. @api.model
  82. def select_or_create_state(
  83. self, row, country, code_row_index=4, name_row_index=3):
  84. states = self.env['res.country.state'].search([
  85. ('country_id', '=', country.id),
  86. ('code', '=', row[code_row_index]),
  87. ])
  88. if len(states) > 1:
  89. raise UserError(
  90. _("Too many states with code %s for country %s")
  91. % (row[code_row_index], country.code))
  92. if len(states) == 1:
  93. return states[0]
  94. else:
  95. return self.env['res.country.state'].create({
  96. 'name': row[name_row_index],
  97. 'code': row[code_row_index],
  98. 'country_id': country.id
  99. })
  100. @api.multi
  101. def run_import(self):
  102. self.ensure_one()
  103. zip_model = self.env['res.better.zip']
  104. country_code = self.country_id.code
  105. config_url = self.env['ir.config_parameter'].get_param(
  106. 'geonames.url',
  107. default='http://download.geonames.org/export/zip/%s.zip')
  108. url = config_url % country_code
  109. logger.info('Starting to download %s' % url)
  110. res_request = requests.get(url)
  111. if res_request.status_code != requests.codes.ok:
  112. raise UserError(
  113. _('Got an error %d when trying to download the file %s.')
  114. % (res_request.status_code, url))
  115. # Store current record list
  116. zips_to_delete = zip_model.search(
  117. [('country_id', '=', self.country_id.id)])
  118. f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
  119. tempdir = tempfile.mkdtemp(prefix='openerp')
  120. f_geonames.extract('%s.txt' % country_code, tempdir)
  121. logger.info('The geonames zipfile has been decompressed')
  122. data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
  123. data_file.seek(0)
  124. logger.info('Starting to create the better zip entries')
  125. max_import = self.env.context.get('max_import', 0)
  126. reader = unicodecsv.reader(data_file, encoding='utf-8', delimiter=' ')
  127. for i, row in enumerate(reader):
  128. zip_code = self.create_better_zip(row, self.country_id)
  129. if zip_code in zips_to_delete:
  130. zips_to_delete -= zip_code
  131. if max_import and (i + 1) == max_import:
  132. break
  133. data_file.close()
  134. if zips_to_delete and not max_import:
  135. zips_to_delete.unlink()
  136. logger.info('%d better zip entries deleted for country %s' %
  137. (len(zips_to_delete), self.country_id.name))
  138. logger.info(
  139. 'The wizard to create better zip entries from geonames '
  140. 'has been successfully completed.')
  141. return True