def getAddressByName(self, params): ''' Return provinces, districts, towns by address name. ''' data, province, district = {}, None, None if params.get('province'): provinceText = convertStrProvince( unicodeString(params.get('province')).lower()) provinces = self.provinceRepo.getAllProvince() province = next((prov for prov in provinces if unicodeString( prov.name).lower().replace(' ', '_') in provinceText), None) if province: data['districts'] = to_list(province.districts) else: data['districts'] = [] else: data['districts'] = [] if province and params.get('district'): districtText = convertStrDistrict( unicodeString(params.get('district')).lower()) try: districtText = int(districtText) district = self.districtRepo.getDistrictBySlugIsNum( str(districtText), province.id) except: district = self.districtRepo.getDistrictBySlug( districtText, province.id) if district: data['towns'] = to_list(district.towns) else: data['towns'] = [] else: data['towns'] = [] return data
def validAddress(self, params): """ Validate address with province, district, town """ if params.get('province') is None or params.get('province') == '': return provinceText = convertStrProvince( unicodeString(params.get('province').strip().lower())) province = self.provinceRepo.getProvinceBySlug(provinceText) if province is None: raise Exception("Incorect name with province {}".format( params.get('province'))) if params.get('district') and params.get('district') != '': districtSlugs = list(map(lambda d: d.slug, province.districts)) districtText = convertStrDistrict( unicodeString(params.get('district').strip().lower())) districtText = str(int( districtText)) if districtText.isnumeric() else districtText if districtText not in districtSlugs: raise Exception( "Cannot found district {} in province {}".format( params.get('district'), params.get('province'))) if params.get('town') and params.get('town') != '': district = self.districtRepo.getDistrictBySlug( districtText, province.id) townSlugs = list(map(lambda t: t.slug, district.towns)) townText = convertStrTown( unicodeString(params.get('town').strip().lower())) townText = str(int(townText)) if townText.isnumeric() else townText if townText not in townSlugs: raise Exception("Cannot found town {} in district {}".format( params.get('town'), params.get('district')))
def generateCustomerGroup(self, params): """ Generate customer group id from province, district, town address. The address come from import customer group like "Hà Nội#Ba Đình |Hà Nội#Hoàng Mai|Hà Nội# Tây Hồ". Return array customer group ids. """ result, prov, dist, town = [], None, None, None address = params.get('address').split('|') for add in address: addPrams = add.split('#') if len(addPrams) == 1: [prov] = addPrams provinceText = convertStrProvince( unicodeString(prov).strip().lower()) if redis_client.hget("province", provinceText): result.append( f"{redis_client.hget('province', provinceText).decode('utf-8')}" ) else: province = self.provinceRepo.getProvinceBySlug( provinceText) redis_client.hmset( "province", { f"{provinceText}": province.id, f"districts_{provinceText}": json.dumps(to_list( province.districts)).encode('utf-8') }) redis_client.expire("province", 3600) result.append(f"{province.id}") elif len(addPrams) == 2: [prov, dist] = addPrams provinceText = convertStrProvince( unicodeString(prov).strip().lower()) districtText = convertStrDistrict( unicodeString(dist).strip().lower()) if redis_client.hget( "province", provinceText) and redis_client.hget( "province", f"districts_{provinceText}"): districts = json.loads( redis_client.hget( "province", f"districts_{provinceText}").decode('utf-8')) districtId = next( (d['id'] for d in districts if str(d['slug']) == districtText), "") result.append( f"{redis_client.hget('province', provinceText).decode('utf-8')}-{districtId}" ) else: province = self.provinceRepo.getProvinceBySlug( provinceText) redis_client.hmset( "province", { f"{provinceText}": province.id, f"districts_{provinceText}": json.dumps(to_list( province.districts)).encode('utf-8') }) redis_client.expire("province", 3600) districtId = next((d.id for d in province.districts if str(d.slug) == districtText), "") result.append(f"{province.id}-{districtId}") else: [prov, dist, town] = addPrams provinceText = convertStrProvince( unicodeString(prov).strip().lower()) districtText = convertStrDistrict( unicodeString(dist).strip().lower()) districtText = str( int(districtText)) if districtText.isnumeric( ) else districtText townText = convertStrTown(unicodeString(town).strip().lower()) townText = str( int(townText)) if townText.isnumeric() else townText if redis_client.hget( "province", provinceText) and redis_client.hget( "province", f"districts_{provinceText}") and redis_client.hget( "district", f"towns_{districtText}"): districts = json.loads( redis_client.hget( "province", f"districts_{provinceText}").decode('utf-8')) towns = json.loads( redis_client.hget( "district", f"towns_{districtText}").decode('utf-8')) distId = next((d['id'] for d in districts if d['slug'] == districtText)) townId = next( (t['id'] for t in towns if t['slug'] == townText)) result.append( f"{redis_client.hget('province', provinceText).decode('utf-8')}-{distId}-{townId}" ) else: province = self.provinceRepo.getProvinceBySlug( provinceText) district = self.districtRepo.getDistrictBySlug( districtText, province.id) redis_client.hmset( "province", { f"{provinceText}": province.id, f"districts_{provinceText}": json.dumps(to_list( province.districts)).encode('utf-8') }) redis_client.expire("province", 3600) redis_client.hmset( "district", { f"towns_{districtText}": json.dumps(to_list(district.towns)).encode('utf-8') }) redis_client.expire("district", 3600) distId = next((d.id for d in province.districts if d.slug == districtText)) townId = next( (t.id for t in district.towns if t.slug == townText)) result.append(f"{province.id}-{distId}-{townId}") return result
def getAddressObject(self, params): """ Auto correct province, district, town, street address from GG API or original Address """ data, province, district, town = {}, None, None, None # Parse address from GG API if params.get('province'): provinceText = " ".join(params.get('province').split()).split(' ') provinceText = "_".join( list( map(lambda o: unicodeString(o).strip().lower(), provinceText))).replace(" ", "_") provinces = self.provinceRepo.getAllProvince() province = next((prov for prov in provinces if unicodeString( prov.name).lower().replace(' ', '_') in provinceText or ( acronymWords(prov.name.lower()) == 'hcm' and acronymWords(prov.name.lower()) in provinceText)), None) data['province'] = { "name": province.name, "id": province.id } if province else { "id": None, "name": params.get('province') } if province and params.get('district'): districtText = " ".join(params.get('district').split()).split(' ') districtText = "_".join( list( map(lambda o: unicodeString(o).strip().lower(), districtText))).replace(" ", "_") district = self.getDistrict(province, districtText) data['district'] = { "id": district.id, "name": district.name } if district else { "id": None, "name": params.get('district') } if province and district and params.get('town'): townText = " ".join(params.get('town').split()).split(' ') townText = "_".join( list(map(lambda o: unicodeString(o).strip().lower(), townText))).replace(" ", "_") town = self.getTown(district, townText) data['town'] = { "id": town.id, "name": town.name } if town else { "name": params.get('town'), "id": None } # Parse address from origin address if params.get('address'): originAddress = params.get('address', None) if originAddress: tempOriginAddress = " ".join(originAddress.split()).split(',') tempAddress = list( map(lambda o: unicodeString(o).strip().lower(), tempOriginAddress)) tempAddress = tempAddress[::-1] tempOriginAddress = tempOriginAddress[::-1] originAddress = "_".join( list( map(lambda o: unicodeString(o).strip().lower(), originAddress.split()))).replace(" ", "_") if tempAddress[0] == 'vn' or tempAddress[ 0] == 'vietnam' or tempAddress[0] == 'viet nam': tempOriginAddress = tempOriginAddress[1:] if originAddress and province is None: provinces = self.provinceRepo.getAllProvince() province = next( (prov for prov in provinces if " ".join(unicodeString(prov.name).lower().split() ).replace(' ', '_') in originAddress or (acronymWords(prov.name.lower()) == 'hcm' and acronymWords(prov.name.lower()) in originAddress)), None) data['province'] = { "id": province.id, "name": province.name } if province else ({ "name": tempOriginAddress[0], "id": None } if len(tempOriginAddress) > 0 else { "name": "", "id": None }) if originAddress and province and district is None: district = self.getDistrict(province, originAddress) data['district'] = { "id": district.id, "name": district.name } if district else ({ "name": tempOriginAddress[1], "id": None } if len(tempOriginAddress) > 1 else { "name": "", "id": None }) if originAddress and province and district and town is None: town = self.getTown(district, originAddress) data['town'] = { "id": town.id, "name": town.name } if town else ({ "id": None, "name": tempOriginAddress[2] } if len(tempOriginAddress) > 2 else { "name": "", "id": None }) if len(tempOriginAddress) and data.get('province') is None: data['province'] = {"name": tempOriginAddress[0], "id": None} if len(tempOriginAddress) > 1 and data.get('district') is None: data['district'] = {"name": tempOriginAddress[1], "id": None} if len(tempOriginAddress) > 2 and data.get('town') is None: data['town'] = {"name": tempOriginAddress[2], "id": None} if len(tempOriginAddress) > 3: streetAddress = tempOriginAddress[3:] data['street_address'] = ",".join(streetAddress[::-1]) data['country'] = {"id": 1, "name": 'Việt Nam'} return province, district, town, data
def test_convert_str_province(self): input_str = ["Thành phố Hà Nội", "Hà Nội", "tp. Hà Nội", "tp Hà Nội", "tỉnh Hà Nội", "t Hà Nội", "t. Hà Nội"] output_str = list(map(lambda str: convertStrProvince(unicodeString(str.lower())), input_str)) self.assertTrue(all(str == output_str[0] for str in output_str))
def test_unicode_string(self): str_input = "Việt Nam" self.assertEqual(unicodeString(str_input), "Viet Nam")
def test_convert_str_town(self): input_str = ["Phường Đốc Ngữ", "Xã Đốc Ngữ", "Thị trấn Đốc Ngữ", "p Đốc Ngữ", "x Đốc Ngữ", "tt Đốc Ngữ", "p. Đốc Ngữ", "x. Đốc Ngữ", "tt. Đốc Ngữ"] output_str = list(map(lambda s: convertStrTown(unicodeString(s.lower())), input_str)) self.assertEqual(len(set(output_str)), 1)
def test_convert_str_district(self): input_str = ["Quận Ba Đình", "q Ba Đình", "q. Ba Đình", "thị xã Ba Đình", "tx Ba Đình", "tx. Ba đình", "huyện Ba đình", "h Ba Đình", "h. Ba Đình", "thành phố ba đình", "tp Ba đình", "tp. Ba đình"] output_str = list(map(lambda s: convertStrDistrict(unicodeString(s.lower())), input_str)) self.assertTrue(all(str == output_str[0] for str in output_str))