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.8 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 zipfile
  30. import os
  31. import logging
  32. try:
  33. import unicodecsv
  34. except ImportError:
  35. unicodecsv = None
  36. logger = logging.getLogger(__name__)
  37. class BetterZipGeonamesImport(models.TransientModel):
  38. _name = 'better.zip.geonames.import'
  39. _description = 'Import Better Zip from Geonames'
  40. _rec_name = 'country_id'
  41. country_id = fields.Many2one('res.country', 'Country', required=True)
  42. @api.model
  43. def transform_city_name(self, city, country):
  44. """Override it for transforming city name (if needed)
  45. :param city: Original city name
  46. :param country: Country record
  47. :return: Transformed city name
  48. """
  49. return city
  50. @api.model
  51. def _domain_search_better_zip(self, row, country):
  52. return [('name', '=', row[1]),
  53. ('city', '=', self.transform_city_name(row[2], country)),
  54. ('country_id', '=', country.id)]
  55. @api.model
  56. def _prepare_better_zip(self, row, country):
  57. state = self.select_or_create_state(row, country)
  58. vals = {
  59. 'name': row[1],
  60. 'city': self.transform_city_name(row[2], country),
  61. 'state_id': state.id,
  62. 'country_id': country.id,
  63. }
  64. return vals
  65. @api.model
  66. def create_better_zip(self, row, country):
  67. if row[0] != country.code:
  68. raise Warning(
  69. _("The country code inside the file (%s) doesn't "
  70. "correspond to the selected country (%s).")
  71. % (row[0], country.code))
  72. logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
  73. if row[1] and row[2]:
  74. zip_model = self.env['res.better.zip']
  75. zips = zip_model.search(self._domain_search_better_zip(
  76. row, country))
  77. if zips:
  78. return zips[0]
  79. else:
  80. vals = self._prepare_better_zip(row, country)
  81. if vals:
  82. return zip_model.create(vals)
  83. else:
  84. return False
  85. @api.model
  86. def select_or_create_state(
  87. self, row, country, code_row_index=4, name_row_index=3):
  88. states = self.env['res.country.state'].search([
  89. ('country_id', '=', country.id),
  90. ('code', '=', row[code_row_index]),
  91. ])
  92. if len(states) > 1:
  93. raise Warning(
  94. _("Too many states with code %s for country %s")
  95. % (row[code_row_index], country.code))
  96. if len(states) == 1:
  97. return states[0]
  98. else:
  99. return self.env['res.country.state'].create({
  100. 'name': row[name_row_index],
  101. 'code': row[code_row_index],
  102. 'country_id': country.id
  103. })
  104. @api.one
  105. def run_import(self):
  106. zip_model = self.env['res.better.zip']
  107. country_code = self.country_id.code
  108. config_url = self.env['ir.config_parameter'].get_param(
  109. 'geonames.url',
  110. default='http://download.geonames.org/export/zip/%s.zip')
  111. url = config_url % country_code
  112. logger.info('Starting to download %s' % url)
  113. res_request = requests.get(url)
  114. if res_request.status_code != requests.codes.ok:
  115. raise Warning(
  116. _('Got an error %d when trying to download the file %s.')
  117. % (res_request.status_code, url))
  118. # Store current record list
  119. zips_to_delete = zip_model.search(
  120. [('country_id', '=', self.country_id.id)])
  121. f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
  122. tempdir = tempfile.mkdtemp(prefix='openerp')
  123. f_geonames.extract('%s.txt' % country_code, tempdir)
  124. logger.info('The geonames zipfile has been decompressed')
  125. data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
  126. data_file.seek(0)
  127. logger.info('Starting to create the better zip entries')
  128. for row in unicodecsv.reader(
  129. data_file, encoding='utf-8', delimiter=' '):
  130. zip = self.create_better_zip(row, self.country_id)
  131. if zip in zips_to_delete:
  132. zips_to_delete -= zip
  133. data_file.close()
  134. if zips_to_delete:
  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