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.

118 lines
4.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. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. from openerp import models, fields, api, _
  23. from openerp.exceptions import Warning
  24. import requests
  25. import tempfile
  26. import StringIO
  27. import unicodecsv
  28. import zipfile
  29. import os
  30. import logging
  31. logger = logging.getLogger(__name__)
  32. class better_zip_geonames_import(models.TransientModel):
  33. _name = 'better.zip.geonames.import'
  34. _description = 'Import Better Zip from Geonames'
  35. _rec_name = 'country_id'
  36. country_id = fields.Many2one('res.country', 'Country', required=True)
  37. @api.model
  38. def _prepare_better_zip(self, row, country_id, states):
  39. '''This function is designed to be inherited'''
  40. state_id = False
  41. if states and row[4] and row[4] in states:
  42. state_id = states[row[4].upper()]
  43. vals = {
  44. 'name': row[1],
  45. 'city': row[2],
  46. 'state_id': state_id,
  47. 'country_id': country_id,
  48. }
  49. return vals
  50. @api.model
  51. def create_better_zip(
  52. self, row, country_id, country_code, states):
  53. bzip_id = False
  54. if row[0] != country_code:
  55. raise Warning(
  56. _('Error:'),
  57. _("The country code inside the file (%s) doesn't "
  58. "correspond to the selected country (%s).")
  59. % (row[0], country_code))
  60. logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
  61. if row[1] and row[2]:
  62. vals = self._prepare_better_zip(row, country_id, states)
  63. if vals:
  64. bzip_id = self.env['res.better.zip'].create(vals)
  65. return bzip_id
  66. @api.one
  67. def run_import(self):
  68. bzip_obj = self.env['res.better.zip']
  69. country_id = self.country_id.id
  70. country_code = self.country_id.code.upper()
  71. url = 'http://download.geonames.org/export/zip/%s.zip' % country_code
  72. logger.info('Starting to download %s' % url)
  73. res_request = requests.get(url)
  74. if res_request.status_code != requests.codes.ok:
  75. raise Warning(
  76. _('Error:'),
  77. _('Got an error %d when trying to download the file %s.')
  78. % (res_request.status_code, url))
  79. bzip_ids_to_delete = bzip_obj.search([('country_id', '=', country_id)])
  80. if bzip_ids_to_delete:
  81. bzip_obj.unlink(bzip_ids_to_delete)
  82. logger.info(
  83. '%d better zip entries deleted for country %s'
  84. % (len(bzip_ids_to_delete), self.country_id.name))
  85. state_ids = self.env['res.country.state'].search(
  86. [('country_id', '=', country_id)])
  87. states = {}
  88. # key = code of the state ; value = ID of the state in OpenERP
  89. if state_ids:
  90. states_r = self.env['res.country.state'].read(
  91. state_ids, ['code', 'country_id'])
  92. for state in states_r:
  93. states[state['code'].upper()] = state['id']
  94. f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
  95. tempdir = tempfile.mkdtemp(prefix='openerp')
  96. f_geonames.extract('%s.txt' % country_code, tempdir)
  97. logger.info('The geonames zipfile has been decompressed')
  98. data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
  99. data_file.seek(0)
  100. logger.info(
  101. 'Starting to create the better zip entries %s state information'
  102. % (states and 'with' or 'without'))
  103. for row in unicodecsv.reader(
  104. data_file, encoding='utf-8', delimiter=' '):
  105. self.create_better_zip(row, country_id, country_code, states)
  106. data_file.close()
  107. logger.info(
  108. 'The wizard to create better zip entries from geonames '
  109. 'has been successfully completed.')
  110. return True