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.

149 lines
5.7 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Base Location Geonames Import module for OpenERP
  5. # Copyright (C) 2014 Akretion (http://www.akretion.com)
  6. # @author Alexis de Lattre <alexis.delattre@akretion.com>
  7. # Copyright (C) 2014 Agile Business Group (http://www.agilebg.com)
  8. # @author Lorenzo Battistini <lorenzo.battistini@agilebg.com>
  9. #
  10. # This program is free software: you can redistribute it and/or modify
  11. # it under the terms of the GNU Affero General Public License as
  12. # published by the Free Software Foundation, either version 3 of the
  13. # License, or (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU Affero General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Affero General Public License
  21. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. ##############################################################################
  24. from openerp import models, fields, api, _
  25. from openerp.exceptions import Warning
  26. import requests
  27. import tempfile
  28. import StringIO
  29. import unicodecsv
  30. import zipfile
  31. import os
  32. import logging
  33. logger = logging.getLogger(__name__)
  34. class BetterZipGeonamesImport(models.TransientModel):
  35. _name = 'better.zip.geonames.import'
  36. _description = 'Import Better Zip from Geonames'
  37. _rec_name = 'country_id'
  38. country_id = fields.Many2one('res.country', 'Country', required=True)
  39. @api.model
  40. def transform_city_name(self, city, country):
  41. """Override it for transforming city name (if needed)
  42. :param city: Original city name
  43. :param country: Country record
  44. :return: Transformed city name
  45. """
  46. return city
  47. @api.model
  48. def _domain_search_better_zip(self, row, country):
  49. return [('name', '=', row[1]),
  50. ('city', '=', self.transform_city_name(row[2], country)),
  51. ('country_id', '=', country.id)]
  52. @api.model
  53. def _prepare_better_zip(self, row, country):
  54. state = self.select_or_create_state(row, country)
  55. vals = {
  56. 'name': row[1],
  57. 'city': self.transform_city_name(row[2], country),
  58. 'state_id': state.id,
  59. 'country_id': country.id,
  60. }
  61. return vals
  62. @api.model
  63. def create_better_zip(self, row, country):
  64. if row[0] != country.code:
  65. raise Warning(
  66. _("The country code inside the file (%s) doesn't "
  67. "correspond to the selected country (%s).")
  68. % (row[0], country.code))
  69. logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
  70. if row[1] and row[2]:
  71. zip_model = self.env['res.better.zip']
  72. zips = zip_model.search(self._domain_search_better_zip(
  73. row, country))
  74. if zips:
  75. return zips[0]
  76. else:
  77. vals = self._prepare_better_zip(row, country)
  78. if vals:
  79. return zip_model.create(vals)
  80. else:
  81. return False
  82. @api.model
  83. def select_or_create_state(
  84. self, row, country, code_row_index=4, name_row_index=3):
  85. states = self.env['res.country.state'].search([
  86. ('country_id', '=', country.id),
  87. ('code', '=', row[code_row_index]),
  88. ])
  89. if len(states) > 1:
  90. raise Warning(
  91. _("Too many states with code %s for country %s")
  92. % (row[code_row_index], country.code))
  93. if len(states) == 1:
  94. return states[0]
  95. else:
  96. return self.env['res.country.state'].create({
  97. 'name': row[name_row_index],
  98. 'code': row[code_row_index],
  99. 'country_id': country.id
  100. })
  101. @api.one
  102. def run_import(self):
  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 Warning(
  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. for row in unicodecsv.reader(
  126. data_file, encoding='utf-8', delimiter=' '):
  127. zip = self.create_better_zip(row, self.country_id)
  128. if zip in zips_to_delete:
  129. zips_to_delete -= zip
  130. data_file.close()
  131. if zips_to_delete:
  132. zips_to_delete.unlink()
  133. logger.info('%d better zip entries deleted for country %s' %
  134. (len(zips_to_delete), self.country_id.name))
  135. logger.info(
  136. 'The wizard to create better zip entries from geonames '
  137. 'has been successfully completed.')
  138. return True