Beispiel #1
0
def geocode(str, max_size=DEFAULT_RESULT_MAX_SIZE, add_geohash=True, resolve_to_ids=False, constrain_to_city=None):
    """
    default geocoder
    """
    from common.models import City, Country

    results = telmap_geocode(str, max_size, constrain_to_city)
    logging.info(u"geocoding results for %s: %s\n" % (str, results))

    if add_geohash or resolve_to_ids:
        for result in results:
            if add_geohash:
                result["geohash"] = geohash_encode(result["lon"], result["lat"])

            if resolve_to_ids:
                result["country"] = Country.get_id_by_code(result["country"])

                if is_in_hebrew(result["city"]):
                    result["city"] = City.get_id_by_name_and_country(
                        result["city"], result["country"], add_if_not_found=True
                    )
                else:
                    # try to reverse geocode to get city name in Hebrew
                    reverse_geocode_result = reverse_geocode(result["lat"], result["lon"])
                    if reverse_geocode_result:
                        result["city"] = reverse_geocode_result["city"]
                    else:
                        logging.error("failed to get Hebrew city name from reverse geocode")
                        result["city"] = City.get_id_by_name_and_country(
                            result["city"], result["country"], add_if_not_found=True
                        )

    return results
def resolve_city(cache, name, country):
    if name in cache:
        return cache[name]
    else:
        city_id = City.get_id_by_name_and_country(name, country.id, True)
        city = City.objects.get(id=city_id)
        cache[name] = city
        return city
def resolve_city(cache, name, country):
    if name in cache:
        return cache[name]
    else:
        city_id = City.get_id_by_name_and_country(name, country.id, True)
        city = City.objects.get(id=city_id)
        cache[name] = city
        return city
Beispiel #4
0
def geocode(str,
            max_size=DEFAULT_RESULT_MAX_SIZE,
            add_geohash=True,
            resolve_to_ids=False,
            constrain_to_city=None):
    """
    default geocoder
    """
    from common.models import City, Country

    results = telmap_geocode(str, max_size, constrain_to_city)
    logging.info(u"geocoding results for %s: %s\n" % (str, results))

    if add_geohash or resolve_to_ids:
        for result in results:
            if add_geohash:
                result["geohash"] = geohash_encode(result["lon"],
                                                   result["lat"])

            if resolve_to_ids:
                result["country"] = Country.get_id_by_code(result["country"])

                if is_in_hebrew(result["city"]):
                    result["city"] = City.get_id_by_name_and_country(
                        result["city"],
                        result["country"],
                        add_if_not_found=True)
                else:
                    # try to reverse geocode to get city name in Hebrew
                    reverse_geocode_result = reverse_geocode(
                        result["lat"], result["lon"])
                    if reverse_geocode_result:
                        result["city"] = reverse_geocode_result["city"]
                    else:
                        logging.error(
                            "failed to get Hebrew city name from reverse geocode"
                        )
                        result["city"] = City.get_id_by_name_and_country(
                            result["city"],
                            result["country"],
                            add_if_not_found=True)

    return results
Beispiel #5
0
    def create(self, request, *args, **kwargs):
        api_user = kwargs["api_user"]
        request_data = request.data.get("request")
        if not request_data:
            return rc.BAD_REQUEST

        language_code = request_data.get("language_code")
        translation.activate(language_code)

        passenger = None
        phone_number = request_data.get("phone_number")
        login_token = request_data.get("login_token")

        try:
            if login_token: #TODO_WB: merge needed to make this work
                passenger = Passenger.objects.get(login_token=login_token)
            elif phone_number and not api_user.phone_validation_required:
                passenger = Passenger.objects.get(phone=phone_number) 
        except Passenger.DoesNotExist:
            pass

        if not passenger:
            return rc.NOT_FOUND #TODO_WB: is this the right response

        order_data = {}
        for address_type in ('from', 'to'):
            for att, val in request_data[address_type].items():
                order_data[address_type + "_" + att] = val or ""

            if not is_valid_address(order_data, address_type):
                res = rc.BAD_REQUEST
                res.write(" %s\n" % ErrorCodes.INVALID_ADDRESS)
                return res

            order_data[address_type + "_country"] = Country.get_id_by_code(order_data[address_type + "_country"])
            order_data[address_type + "_city"] = City.get_id_by_name_and_country(order_data[address_type + "_city"], order_data[address_type + "_country"], add_if_not_found=True)

        order_form = OrderForm(data=order_data, passenger=passenger)
        if order_form.is_valid():

            order = order_form.save()
            order.api_user = api_user
            order.passenger = passenger
            order.language_code = language_code
            order.save()
            book_order_async(order)
            log_event(EventType.ORDER_BOOKED, order=order)
            return rc.CREATED
        else:
            response = rc.BAD_REQUEST
            response.write(" %s\n" % order_form.errors.as_text())
            return response
def get_cities_for_country(request, station):
    selected_city = None
    try:
        c = Country.objects.filter(id=request.GET.get('country_id', '0')).get()
    except Country.DoesNotExist:
        return HttpResponseBadRequest('Invalid country passed')

    if station.country == c:
        selected_city = station.city.id

    result = { "options": City.city_choices(c) }
    if selected_city:
        result.update({ "selected_option": selected_city })

    return JSONResponse(result)
Beispiel #7
0
def reverse_geocode(latitude, longitude):
    from common.models import Country, City

    result = telmap_reverse_geocode(latitude, longitude)
    if result:
        house_number = result.get("house_number")
        if not house_number or not house_number.isdigit():
            return None

        result["country_name"] = result["country"]
        result["country"] = Country.get_id_by_code(result["country"])
        result["city_name"] = result["city"]
        result["city"] = City.get_id_by_name_and_country(result["city"], result["country"], add_if_not_found=True)
        result["geohash"] = geohash_encode(longitude, latitude)

    return result
Beispiel #8
0
def reverse_geocode(latitude, longitude):
    from common.models import Country, City

    result = telmap_reverse_geocode(latitude, longitude)
    if result:
        house_number = result.get("house_number")
        if not house_number or not house_number.isdigit():
            return None

        result["country_name"] = result["country"]
        result["country"] = Country.get_id_by_code(result["country"])
        result["city_name"] = result["city"]
        result["city"] = City.get_id_by_name_and_country(result["city"],
                                                         result["country"],
                                                         add_if_not_found=True)
        result["geohash"] = geohash_encode(longitude, latitude)

    return result
Beispiel #9
0
def get_business_order_form_data(request, passenger):
    form_data = request.POST.copy()
    country_id = Country.objects.get(code=settings.DEFAULT_COUNTRY_CODE).id

    if passenger.default_station and passenger.business.confine_orders:
        form_data["confining_station"] = passenger.default_station.id

    form_data["taxi_is_for"] = request.POST.get("taxi_is_for", "")
    form_data["comments"] = request.POST.get("comments", "")

    def resolve_lat_lon_or_default(city, street_address, house_number):
        lat = -1
        lon = -1
        street_address = street_address.strip()
        house_number = house_number.strip()
        address = "%s %s, %s" % (street_address, house_number, city.name)
        geocoding_results = geocode(address, resolve_to_ids=True)
        for result in geocoding_results:
            # make sure it is a match and not a suggestion
            if result["street_address"] == street_address and result[
                    "house_number"] == house_number:
                lat = result["lat"]
                lon = result["lon"]
                break

        return lat, lon

    from_city = City.by_id(form_data.get("from_city"))
    from_hn = re.search("(\d+)", form_data.get("from_street_address", ""))
    from_hn = str(from_hn.groups()[0] if from_hn else "")
    from_street_address = form_data.get("from_street_address",
                                        "").replace(from_hn, "")
    from_lat, from_lon = resolve_lat_lon_or_default(from_city,
                                                    from_street_address,
                                                    from_hn)
    form_data.update({
        "from_country":
        country_id,
        "from_raw":
        "%s %s %s" % (from_street_address, from_hn, from_city.name),
        "from_street_address":
        from_street_address,
        "from_house_number":
        from_hn,
        "from_lat":
        from_lat,
        "from_lon":
        from_lon,
        "from_geohash":
        geohash_encode(from_lon, from_lat),
    })

    to_city = City.by_id(form_data.get("to_city"))
    if to_city:
        to_hn = re.search("(\d+)", form_data.get("to_street_address", ""))
        to_hn = str(to_hn.groups()[0] if to_hn else "")
        to_street_address = form_data.get("to_street_address",
                                          "").replace(to_hn, "")
        to_lat, to_lon = resolve_lat_lon_or_default(to_city, to_street_address,
                                                    to_hn)
        form_data.update({
            "to_country":
            country_id,
            "to_raw":
            "%s %s %s" % (to_street_address, to_hn, to_city.name),
            "to_street_address":
            to_street_address,
            "to_house_number":
            to_hn,
            "to_lat":
            to_lat,
            "to_lon":
            to_lon,
            "to_geohash":
            geohash_encode(to_lon, to_lat)
        })

    return form_data
Beispiel #10
0
    def handle(self, *args, **options):
        # 城市
        cd = City(name='成都')
        bj = City(name='北京')

        cd.save()
        bj.save()

        # 区域
        area_smq = Area(city=cd, name='驷马桥')

        area_wks = Area(city=cd, name='五块石')

        area_smq.save()
        area_wks.save()

        # 商户类型
        merchant_category_yinshi = MerchantCategory(name='饮食')
        merchant_category_yule = MerchantCategory(name='娱乐')

        merchant_category_yinshi.save()
        merchant_category_yule.save()

        # 付款码
        pay_code = PaymentQRCode(uuid=uuid.uuid4())
        pay_code.save()

        # account
        merchant_account = Account(bank_name='招商银行成都分行高新支行',
                                   bank_card_number='7678442831579099123',
                                   bank_account_name='陈冠希',
                                   balance=10000,
                                   withdrawable_balance=8000)
        merchant_account.save()

        marketer_account = Account(bank_name='招商银行成都分行高新支行',
                                   bank_card_number='7678442831579099145',
                                   bank_account_name='流川枫',
                                   balance=10000,
                                   withdrawable_balance=8000)
        marketer_account.save()

        # 业务员
        marketer = Marketer(wechat_openid='saxsdadf00xx',
                            wechat_unionid='xx456asdfnn',
                            inviter_type=config.MARKETER_TYPES.SALESMAN,
                            status=config.SYSTEM_USER_STATUS.USING,
                            name='流川枫',
                            phone='18109045756',
                            account=marketer_account,
                            worker_number='tnt001')
        marketer.save()
        marketer.working_areas.add(area_wks)

        # 商户
        merchant = Merchant(
            status=config.MERCHANT_STATUS.USING,
            name='生如夏花泰式火锅(鹭洲里店)',
            account=merchant_account,
            payment_qr_code=pay_code,
            category=merchant_category_yinshi,
            contact_phone='18945236754',
            area=area_wks,
            address='成都市五块石北城天街98号',
            location_lon=10,
            location_lat=10,
            description='纯正泰式火锅,家门口的泰式美食旅行',
            avatar_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            photo_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            license_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg',  # noqa
            id_card_front_url=
            'http://img.wenzhangba.com/userup/883/1P4020F057-35O-0.jpg',
            id_card_back_url=
            'http://image2.sina.com.cn/dy/c/2004-03-29/U48P1T1D3073262F23DT20040329135445.jpg',  # noqa
            create_datetime=timezone.now())
        merchant.save()
        merchant.auditors.add(marketer)

        # 用户
        client = Client(openid='oUkVN5WSmOYbYSgR74rRPamWmoAM',
                        openid_channel=config.PAY_CHANNELS.WECHAT)
        client.save()

        # 优惠券rule
        coupon_rule = CouponRule(
            merchant=merchant,
            discount=10,
            min_charge=50,
            valid_strategy=config.VALID_STRATEGY.EXPIRATION,
            expiration_days=15,
            stock=30,
            photo_url=
            'https://img.meituan.net/msmerchant/96814ff238209b8b9ecc8144338f9c09253790.jpg'
        )  # noqa
        coupon_rule.save()

        coupon = Coupon(rule=coupon_rule,
                        client=client,
                        discount=10,
                        min_charge=50,
                        originator_merchant=merchant,
                        status=config.COUPON_STATUS.NOT_USED,
                        obtain_datetime=timezone.now())
        coupon.save()
def get_business_order_form_data(request, passenger):
    form_data = request.POST.copy()
    country_id = Country.objects.get(code=settings.DEFAULT_COUNTRY_CODE).id

    if passenger.default_station and passenger.business.confine_orders:
        form_data["confining_station"] = passenger.default_station.id

    form_data["taxi_is_for"] = request.POST.get("taxi_is_for", "")
    form_data["comments"] = request.POST.get("comments", "")

    def resolve_lat_lon_or_default(city, street_address, house_number):
        lat = -1
        lon = -1
        street_address = street_address.strip()
        house_number = house_number.strip()
        address = "%s %s, %s" % (street_address, house_number, city.name)
        geocoding_results = geocode(address, resolve_to_ids=True)
        for result in geocoding_results:
            # make sure it is a match and not a suggestion
            if result["street_address"] == street_address and result["house_number"] == house_number:
                lat = result["lat"]
                lon = result["lon"]
                break

        return lat, lon

    from_city = City.by_id(form_data.get("from_city"))
    from_hn = re.search("(\d+)", form_data.get("from_street_address", ""))
    from_hn = str(from_hn.groups()[0] if from_hn else "")
    from_street_address = form_data.get("from_street_address", "").replace(from_hn, "")
    from_lat, from_lon = resolve_lat_lon_or_default(from_city, from_street_address, from_hn)
    form_data.update(
        {
            "from_country": country_id,
            "from_raw": "%s %s %s" % (from_street_address, from_hn, from_city.name),
            "from_street_address": from_street_address,
            "from_house_number": from_hn,
            "from_lat": from_lat,
            "from_lon": from_lon,
            "from_geohash": geohash_encode(from_lon, from_lat),
        }
    )

    to_city = City.by_id(form_data.get("to_city"))
    if to_city:
        to_hn = re.search("(\d+)", form_data.get("to_street_address", ""))
        to_hn = str(to_hn.groups()[0] if to_hn else "")
        to_street_address = form_data.get("to_street_address", "").replace(to_hn, "")
        to_lat, to_lon = resolve_lat_lon_or_default(to_city, to_street_address, to_hn)
        form_data.update(
            {
                "to_country": country_id,
                "to_raw": "%s %s %s" % (to_street_address, to_hn, to_city.name),
                "to_street_address": to_street_address,
                "to_house_number": to_hn,
                "to_lat": to_lat,
                "to_lon": to_lon,
                "to_geohash": geohash_encode(to_lon, to_lat),
            }
        )

    return form_data