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.

256 lines
9.6 KiB

  1. # Copyright 2014-2016 Akretion (Alexis de Lattre
  2. # <alexis.delattre@akretion.com>)
  3. # Copyright 2014 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
  4. # Copyright 2017 Eficent Business and IT Consulting Services, S.L.
  5. # <contact@eficent.com>
  6. # Copyright 2018 Aitor Bouzas <aitor.bouzas@adaptivecity.com>
  7. # Copyright 2016-2020 Tecnativa - Pedro M. Baeza
  8. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  9. import csv
  10. import io
  11. import logging
  12. import os
  13. import tempfile
  14. import zipfile
  15. import requests
  16. from odoo import _, api, fields, models
  17. from odoo.exceptions import UserError
  18. logger = logging.getLogger(__name__)
  19. class CityZipGeonamesImport(models.TransientModel):
  20. _name = "city.zip.geonames.import"
  21. _description = "Import City Zips from Geonames"
  22. _rec_name = "country_id"
  23. country_id = fields.Many2one("res.country", "Country", required=True)
  24. code_row_index = fields.Integer(
  25. related="country_id.geonames_state_code_column", readonly=True
  26. )
  27. name_row_index = fields.Integer(related="country_id.geonames_state_name_column")
  28. letter_case = fields.Selection(
  29. [("unchanged", "Unchanged"), ("title", "Title Case"), ("upper", "Upper Case")],
  30. string="Letter Case",
  31. default="unchanged",
  32. help="Converts retreived city and state names to Title Case "
  33. "(upper case on each first letter of a word) or Upper Case "
  34. "(all letters upper case).",
  35. )
  36. @api.model
  37. def transform_city_name(self, city, country):
  38. """Override it for transforming city name (if needed)
  39. :param city: Original city name
  40. :param country: Country record
  41. :return: Transformed city name
  42. """
  43. res = city
  44. if self.letter_case == "title":
  45. res = city.title()
  46. elif self.letter_case == "upper":
  47. res = city.upper()
  48. return res
  49. @api.model
  50. def _domain_search_city_zip(self, row, city_id=False):
  51. domain = [("name", "=", row[1])]
  52. if city_id:
  53. domain += [("city_id", "=", city_id)]
  54. return domain
  55. @api.model
  56. def select_state(self, row, country):
  57. code = row[self.code_row_index or 4]
  58. return self.env["res.country.state"].search(
  59. [("country_id", "=", country.id), ("code", "=", code)], limit=1
  60. )
  61. @api.model
  62. def select_city(self, row, country, state_id):
  63. # This has to be done by SQL for performance reasons avoiding
  64. # left join with ir_translation on the translatable field "name"
  65. self.env.cr.execute(
  66. "SELECT id, name FROM res_city "
  67. "WHERE name = %s AND country_id = %s AND state_id = %s LIMIT 1",
  68. (self.transform_city_name(row[2], country), country.id, state_id),
  69. )
  70. row_city = self.env.cr.fetchone()
  71. return (row_city[0], row_city[1]) if row_city else (False, False)
  72. @api.model
  73. def select_zip(self, row, country, state_id):
  74. city_id, _ = self.select_city(row, country, state_id)
  75. return self.env["res.city.zip"].search(
  76. self._domain_search_city_zip(row, city_id)
  77. )
  78. @api.model
  79. def prepare_state(self, row, country):
  80. return {
  81. "name": row[self.name_row_index or 3],
  82. "code": row[self.code_row_index or 4],
  83. "country_id": country.id,
  84. }
  85. @api.model
  86. def prepare_city(self, row, country, state_id):
  87. vals = {
  88. "name": self.transform_city_name(row[2], country),
  89. "state_id": state_id,
  90. "country_id": country.id,
  91. }
  92. return vals
  93. @api.model
  94. def prepare_zip(self, row, city_id):
  95. vals = {"name": row[1], "city_id": city_id}
  96. return vals
  97. @api.model
  98. def get_and_parse_csv(self):
  99. country_code = self.country_id.code
  100. config_url = self.env["ir.config_parameter"].get_param(
  101. "geonames.url", default="http://download.geonames.org/export/zip/%s.zip"
  102. )
  103. url = config_url % country_code
  104. logger.info("Starting to download %s" % url)
  105. res_request = requests.get(url)
  106. if res_request.status_code != requests.codes.ok:
  107. raise UserError(
  108. _("Got an error %d when trying to download the file %s.")
  109. % (res_request.status_code, url)
  110. )
  111. f_geonames = zipfile.ZipFile(io.BytesIO(res_request.content))
  112. tempdir = tempfile.mkdtemp(prefix="odoo")
  113. f_geonames.extract("%s.txt" % country_code, tempdir)
  114. data_file = open(
  115. os.path.join(tempdir, "%s.txt" % country_code), "r", encoding="utf-8"
  116. )
  117. data_file.seek(0)
  118. reader = csv.reader(data_file, delimiter=" ")
  119. parsed_csv = [row for i, row in enumerate(reader)]
  120. data_file.close()
  121. logger.info("The geonames zipfile has been decompressed")
  122. return parsed_csv
  123. def _create_states(self, parsed_csv, search_states, max_import):
  124. # States
  125. state_vals_list = []
  126. state_dict = {}
  127. for i, row in enumerate(parsed_csv):
  128. if max_import and i == max_import:
  129. break
  130. state = self.select_state(row, self.country_id) if search_states else False
  131. if not state:
  132. state_vals = self.prepare_state(row, self.country_id)
  133. if state_vals not in state_vals_list:
  134. state_vals_list.append(state_vals)
  135. else:
  136. state_dict[state.code] = state.id
  137. created_states = self.env["res.country.state"].create(state_vals_list)
  138. for i, vals in enumerate(state_vals_list):
  139. state_dict[vals["code"]] = created_states[i].id
  140. return state_dict
  141. def _create_cities(self, parsed_csv, search_cities, max_import, state_dict):
  142. # Cities
  143. city_vals_list = []
  144. city_dict = {}
  145. for i, row in enumerate(parsed_csv):
  146. if max_import and i == max_import:
  147. break
  148. state_id = state_dict[row[self.code_row_index or 4]]
  149. city_id, city_name = (
  150. self.select_city(row, self.country_id, state_id)
  151. if search_cities
  152. else (False, False)
  153. )
  154. if not city_id:
  155. city_vals = self.prepare_city(row, self.country_id, state_id)
  156. if city_vals not in city_vals_list:
  157. city_vals_list.append(city_vals)
  158. else:
  159. city_dict[(city_name, state_id)] = city_id
  160. ctx = dict(self.env.context)
  161. ctx.pop("lang", None) # make sure no translation is added
  162. created_cities = self.env["res.city"].with_context(ctx).create(city_vals_list)
  163. for i, vals in enumerate(city_vals_list):
  164. city_dict[(vals["name"], vals["state_id"])] = created_cities[i].id
  165. return city_dict
  166. def run_import(self):
  167. self.ensure_one()
  168. parsed_csv = self.get_and_parse_csv()
  169. return self._process_csv(parsed_csv)
  170. def _process_csv(self, parsed_csv):
  171. state_model = self.env["res.country.state"]
  172. zip_model = self.env["res.city.zip"]
  173. res_city_model = self.env["res.city"]
  174. # Store current record list
  175. old_zips = set(
  176. zip_model.search([("city_id.country_id", "=", self.country_id.id)]).ids
  177. )
  178. search_zips = len(old_zips) > 0
  179. old_cities = set(
  180. res_city_model.search([("country_id", "=", self.country_id.id)]).ids
  181. )
  182. search_cities = len(old_cities) > 0
  183. current_states = state_model.search([("country_id", "=", self.country_id.id)])
  184. search_states = len(current_states) > 0
  185. max_import = self.env.context.get("max_import", 0)
  186. logger.info("Starting to create the cities and/or city zip entries")
  187. # Pre-create states and cities
  188. state_dict = self._create_states(parsed_csv, search_states, max_import)
  189. city_dict = self._create_cities(
  190. parsed_csv, search_cities, max_import, state_dict
  191. )
  192. # Zips
  193. zip_vals_list = []
  194. for i, row in enumerate(parsed_csv):
  195. if max_import and i == max_import:
  196. break
  197. # Don't search if there aren't any records
  198. zip_code = False
  199. state_id = state_dict[row[self.code_row_index or 4]]
  200. if search_zips:
  201. zip_code = self.select_zip(row, self.country_id, state_id)
  202. if not zip_code:
  203. city_id = city_dict[
  204. (self.transform_city_name(row[2], self.country_id), state_id)
  205. ]
  206. zip_vals = self.prepare_zip(row, city_id)
  207. if zip_vals not in zip_vals_list:
  208. zip_vals_list.append(zip_vals)
  209. else:
  210. old_zips.remove(zip_code.id)
  211. self.env["res.city.zip"].create(zip_vals_list)
  212. if not max_import:
  213. if old_zips:
  214. logger.info("removing city zip entries")
  215. self.env["res.city.zip"].browse(list(old_zips)).unlink()
  216. logger.info(
  217. "%d city zip entries deleted for country %s"
  218. % (len(old_zips), self.country_id.name)
  219. )
  220. old_cities -= set(city_dict.values())
  221. if old_cities:
  222. logger.info("removing city entries")
  223. self.env["res.city"].browse(list(old_cities)).unlink()
  224. logger.info(
  225. "%d res.city entries deleted for country %s"
  226. % (len(old_cities), self.country_id.name)
  227. )
  228. logger.info(
  229. "The wizard to create cities and/or city zip entries from "
  230. "geonames has been successfully completed."
  231. )
  232. return True