def add_address(request):
    street = json.loads(request.body)['street']
    number = json.loads(request.body)['number']
    complement = json.loads(request.body)['complement']
    neighborhood = json.loads(request.body)['neighborhood']
    city = json.loads(request.body)['city']
    state = json.loads(request.body)['state']
    energy_company = json.loads(request.body)['energyCompany']
    try:
        address = Address(user=request.user,
                          street=street,
                          number=number,
                          complement=complement,
                          neighborhood=neighborhood,
                          city=city,
                          state=state,
                          energy_company=energy_company)
        address.save()

        if address:
            return JsonResponse({
                'success': True,
            })
    except:
        return JsonResponse({
            'success': False,
        })
    return JsonResponse({
        'success': False,
    })
Пример #2
0
def address(request):
    if request.method == 'GET':
        adrid = request.GET.get('id')
        if adrid:
            address = Address.objects.get(pk=adrid)
            data = {
                'address': address
            }
            return render(request, 'user/editaddress.html', context=data)
        else:
            return render(request, 'user/addaddress.html')
    if request.method == 'POST':
        a_name = request.POST.get('username')
        a_phone = request.POST.get('phone')
        a_address = request.POST.get('address')
        adrid = request.POST.get('adrid')
        token = request.POST.get('token')
        user = cache.get(token)
        if adrid:
            address = Address.objects.get(pk=adrid)
            address.a_name = a_name
            address.a_phone = a_phone
            address.a_address = a_address
        else:
            address = Address()
            address.a_name = a_name
            address.a_phone = a_phone
            address.a_address = a_address
            address.a_user_id = user
        address.save()
        data = {
            'status': 200,
            'msg': '保存成功'
        }
        return JsonResponse(data=data)
Пример #3
0
def generate_object_item_delivery():
    idelivr = ItemDelivery()
    type_d = generate_type_driver()
    idelivr.load = generate_load_transport(type_d)
    idelivr.name = generate_name_item_delivery(type_d)
    # TODO: change to all BR, for a while, just CG.
    lat_o, lng_o = random_lat_lon()
    lat_t, lng_t = random_lat_lon()
    idelivr.lat = lat_o
    idelivr.lng = lng_o
    address = Address()
    address.lat = lat_t
    address.lng = lng_t
    idelivr.address = geolocation_reverse(lat_o, lng_o)
    address.address = geolocation_reverse(lat_t, lng_t)
    address.save()
    idelivr.target = address
    idelivr.save()
    for i in range(generate_stops_number()):
        lat_stop, lng_stop = random_lat_lon()
        stop = Stop()
        stop.lat = lat_stop
        stop.lng = lng_stop
        stop.item_delivery = idelivr
        stop.save()
    idelivr.distance = get_distance_total_idelivery(idelivr)
    idelivr.save()
    idelivr.amount_receivable = Money(
        generate_profit_item_delivery(type_d, idelivr.distance) +
        get_cost_travel(generate_kml_transport(type_d), idelivr.distance,
                        type_d), 'BRL')
    idelivr.save()
    return idelivr
Пример #4
0
def index(request):
    address = ''
    try:
        address = request.GET['address']

        add = Address(address=address)
        add.save()
    except MultiValueDicKeyError:
        pass
    return HttpResponse('{"Hello":"' + address + '"}')
Пример #5
0
 def post(self, request):
     serializer = AddressSerializer(data=request.data)
     if serializer.is_valid():
         a = Address(Street_add=request.data['street_add'],
                     city=request.data['city'],
                     state=request.data['state'],
                     pincode=request.data['pincode'],
                     country=request.data['country'])
         a.save()
         p = Profile.objects.get(user=self.request.user)
         p.company_add = a
         p.save()
         return Response(data=request.data)
     return Response(data="wrong parameters")
Пример #6
0
def index(request):
    address = ''
    try:
        address = request.GET['address']

        # DB insert           내가 생성한 변수
        add = Address(address=address)
        # 클래스가 가지고 있는 변수
        add.save()  # save >> Model에서 상속받은 method

    except MultiValueDictKeyError:
        pass
    return HttpResponse('{"Hello": "'\
                        + address + '"}')
Пример #7
0
def index(request):
    address = ''
    try:
        address = request.GET['address']

        # DB insert 데이터베이스에 저장
        add = Address(address=address)
        # class     views>index>address
        add.save()
    # models의 함수를 상속받아 실행 가능

    except MultiValueDictKeyError:
        pass

    return HttpResponse('{"Hello":"' + address + '"}')
Пример #8
0
def address(request):
    if request.POST:
        street = request.POST.get('street')
        address2 = request.POST.get('address2')
        city = request.POST.get('city')
        zip = request.POST.get('zip')
        state = request.POST.get('state')
        country = request.POST.get('country')
        request.session['street'] = street
        request.session['address2'] = address2
        request.session['city'] = city
        request.session['zip'] = zip
        request.session['state'] = state
        request.session['country'] = country
        add_obj = Address(street=street, address2=address2, city=city, zip=zip, state=state, country=country)
        add_obj.save()
        return HttpResponseRedirect('/gopay/')
    else:
        return render(request, 'address.html')
Пример #9
0
def process_checkout(request):
    addresses = Address.objects.filter(user_id=request.user.id)
    if addresses.exists():
        address = addresses[0]
        address.first_name = request.POST.get('first_name')
        address.last_name = request.POST.get('last_name')
        address.address_line_1 = request.POST.get('address_line_1')
        address.address_line_2 = request.POST.get('address_line_2')
        address.city = request.POST.get('city')
        address.province = request.POST.get('province')
        address.postal_code = request.POST.get('postal_code')
        address.phone_number = request.POST.get('phone_number')
    else:
        address = Address(first_name=request.POST.get('first_name'),
                          last_name=request.POST.get('last_name'),
                          address_line_1=request.POST.get('address_line_1'),
                          address_line_2=request.POST.get('address_line_2'),
                          city=request.POST.get('city'),
                          province=request.POST.get('province'),
                          postal_code=request.POST.get('postal_code'),
                          phone_number=request.POST.get('phone_number'),
                          user_id=request.user.id)
    address.save()

    carts = Cart.objects.filter(
        user_id=request.user.id).order_by('-created_on')
    if carts.exists():
        cart = carts[0]
        order = Order(user_id=cart.user_id)
        order.save()
        for cartItem in cart.cartitem_set.all():
            orderItem = OrderItem(product_id=cartItem.product.id,
                                  product_title=cartItem.product.title,
                                  product_image=cartItem.product.image.url,
                                  order=order,
                                  unit_price=cartItem.unit_price,
                                  quantity=cartItem.quantity,
                                  total=cartItem.total)
            orderItem.save()
        cart.delete()

    return redirect(checkout_success)
Пример #10
0
    def post(self, request):
        """
        create a new user with addresses
        """
        form = UserAddress(request.POST)
        if form.is_valid():
            try:
                address = Address()
                fk_user = User.objects.get(user=form.cleaned_data['user'])
                address.user = fk_user
                address.address = form.cleaned_data['address']
                address.save()
            except User.DoesNotExist:
                User(user=form.cleaned_data['user']).save()
                address = Address()
                fk_user = User.objects.get(user=form.cleaned_data['user'])
                address.user = fk_user
                address.address = form.cleaned_data['address']
                address.save()

        return redirect('/')
Пример #11
0
 def post(self):
     details = get_details_from_token(claims)
     args = self.parser.parse_args()
     town = args.get("town", "")
     street = args.get("street", "")
     phone = args.get("phone", "")
     if empty(phone) or empty(town) or empty(street):
         return {"message": "Please provide a phone, street and town"}, 400
     if not validate_phone(phone):
         return {"message": "Invalid phone number please provide a valid phone number starting with 07"}, 400
     address = Address(town, street, phone)
     if not details.get("id", ""):
         return {"message": "We could not verify your token please try again"}, 403
     saved = address.save(user_id=details.get("id", ""))
     if saved:
         return {"message": "The address was successfully saved", "data": address.json}, 200
     return {"message": "There was a problem saving the address to the database"}, 400
Пример #12
0
def process_order(request):
    print "placing order"

    try:
        phone_number = request.POST.get("phone_number")
        user_name = request.POST.get("userName")
        email = request.POST.get("email")
        app_version = request.POST.get("app_version")
        device_id = request.POST.get("device_id")
        app_id = request.POST.get("app_id")
        bring_change_of = int(request.POST.get("bring_change_of", "0"))
        address_str = request.POST.get("address")
        landmark = request.POST.get("landmark")
        location_show = request.POST.get("location_show")
        location_id = request.POST.get("location_id")
        api_key = request.POST.get("api_key")
        products = request.POST.get("products")
        tomorrow = request.POST.get("tomorrow")
        delivery_time = request.POST.get("delivery_time")
        # print request
        coupon_id = int(request.POST.get("coupon_id", "0"))

        coupon = None

        print "coupon"
        print phone_number
        user = User.objects.get(username=phone_number)
        if user:
            user.email = email
            user.first_name = user_name.title()
            user.save()
            user_profile = user.userprofile
            user_profile.app_version = app_version
            user_profile.app_id = app_id
            user_profile.device_id = device_id
            user_profile.save()
            if user.api_key.key != api_key:
                print "api key is not valid"
                data = simplejson.dumps({"status": "Not Valid Request"})
                return HttpResponse(data, content_type="application/json", status=403)
        else:
            print "User not found"
            data = simplejson.dumps({"status": "Not Valid Request"})
            return HttpResponse(data, content_type="application/json", status=403)

        print "user obj created"
        print coupon_id

        if coupon_id > 0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count += 1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon, user=user)
            print user
            if prev_order:
                if prev_order[0].status != 1:
                    print "coupon invalidation1"
                    coupon = None
            print coupon
        print "check for coupon"
        location = Location.objects.get(pk=location_id)
        address = Address.objects.filter(user=user, address=address_str, landmark=landmark)
        if address:
            address = address[0]
            address.location = location
            address.save()
        else:
            address = Address(
                user=user, address=address_str, landmark=landmark, location_show=location_show, location=location
            )
            address.save()
        print "address done"

        # print products
        products = products.split(",")
        product_ids = map(lambda x: x.split("::")[0], products)
        product_qns = map(lambda x: x.split("::")[1], products)
        print product_ids
        print product_qns
        order = Order(user=user, total_amount=0, address=address, status=3)
        if tomorrow == "1":
            print delivery_time
            if dt.datetime.now().hour > 20:
                order.delivery_time = dt.datetime.strptime(
                    str((dt.datetime.now() + dt.timedelta(days=1)).date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
            else:
                order.delivery_time = dt.datetime.strptime(
                    str(dt.datetime.now().date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
        else:
            order.delivery_time = dt.datetime.now() + dt.timedelta(hours=1)
        if bring_change_of:
            order.change_requested = bring_change_of
        order.save()
        invoice = Invoice(order=order, product_json="")
        invoice.save()
        print "order obj saved"
        total_amount = 0
        index = 0

        ordered_services = {}
        products_json = []
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append(
                {
                    "spid": prd.id,
                    "pid": prd.product.product.id,
                    "name": prd.product.product.name,
                    "price": prd.price,
                    "discount": prd.discount,
                    "qn": product_qns[index],
                    "size_id": prd.product.size.id,
                }
            )
            service = prd.product.product.category.service
            if "offer" in service.name.lower():
                OfferDeviceId(device_id=device_id).save()
                OfferProductOrderMapping(
                    device_id=device_id, order=order, offer_product=prd.offerproductmapping_set.all()[0]
                ).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)] = 0
            total_amount += int(product_qns[index]) * (prd.price - prd.discount)
            ordered_services[str(service.id)] += int(product_qns[index]) * (prd.price - prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order, store=store)
            if cart:
                cart = cart[0]
            else:
                cart = Cart(order=order, store=store)
                cart.save()

            OrderedProduct(product=prd, cart=cart, quantity=product_qns[index]).save()
            index += 1
        products_json = simplejson.dumps(products_json)
        invoice.product_json = products_json
        invoice.save()

        service_amount_ordered = []
        for key in ordered_services:
            service_amount_ordered.append(str(key) + ":" + str(ordered_services[key]))
        service_amount_ordered = ";;".join(service_amount_ordered)
        print total_amount

        final_amount = total_amount

        if coupon:
            if total_amount >= coupon.min_total:
                order.coupon_applied = coupon
                print "found coupon"
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(
                    coupon, user, location_id, int(app_version), final_amount, service_amount_ordered
                )["discount"]
                print "discount" + str(discount)
                final_amount -= discount

        print "passed coupon part"

        delivery_charges = {}
        for key in ordered_services:
            service = Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service, location=location)
            if lsm:
                lsm = lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True, is_active=True, lsm=lsm)
                print "done"
                if stl:
                    stl = stl[0]
                    if key not in delivery_charges:
                        delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": stl.delivery_min_amount}
                    if ordered_services[key] < stl.delivery_min_amount:
                        final_amount += -stl.delivery_charges
                        total_amount += stl.delivery_charges
                        delivery_charges[key]["delivery_charges"] = stl.delivery_charges
                else:
                    delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}
            else:
                delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}

        print "passed delivery part"

        order.total_amount = total_amount
        order.final_amount = final_amount
        order.delivery_charges = simplejson.dumps(delivery_charges)
        order.save()
        OrderActivity(order=order, user=order.user, actions=0, comment=" ").save()

        data = simplejson.dumps({"status": "done"})
        return HttpResponse(data, content_type="application/json", status=201)
    except Exception as process_order_function_error:
        print "process_order: " + str(process_order_function_error)
        data = simplejson.dumps({"status": "Server Error"})
        send_mail(
            "Order placing Error " + str(process_order_function_error),
            str(request) + "\n\n\n" + str(simplejson.dumps(request.POST)),
            "*****@*****.**",
            ["*****@*****.**"],
            fail_silently=False,
        )
        return HttpResponse(data, content_type="application/json", status=500)
Пример #13
0
    def obj_create(self, bundle, request=None, **kwargs):
        # data={'status':'cant place order'}
        # return HttpResponse(data, content_type='application/json')
        print bundle.data
        phone_number =  bundle.data['phone_number']
        userName =  bundle.data['userName']
        email =  bundle.data['email']
        app_version =  bundle.data['app_version']
        device_id =  bundle.data['device_id']
        app_id =  bundle.data['app_id']
        bring_change_of =  int(bundle.data['bring_change_of'])

        address_str = bundle.data['address']
        landmark = bundle.data['landmark']
        location_show = bundle.data['location_show']
        location_id = bundle.data['location_id']
        coupon_id =""
        try:
            coupon_id = int(bundle.data['coupon_id'])
        except:
            pass

        coupon=None

        print 'coupon'
        print phone_number
        user = User.objects.filter(username=phone_number)
        print user
        print '----'
        if user:
            user=user[0]
            user.email = email
            user.first_name=userName.title()
            user.save()
            print 'user saved'
            userProfile =UserProfile.objects.filter(user=user)
            print 'userprofile'
            print userProfile
            print '----'
            if userProfile:
                userProfile = userProfile[0]
                userProfile.app_version=app_version
                userProfile.app_id=app_id
                userProfile.device_id=device_id
                userProfile.save()
            else:
                UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        else:
            user=User.objects.create_user(phone_number,email,phone_number)
            user.first_name=userName.title()
            user.save()
            UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        print 'user obj created'
        print coupon_id
        if coupon_id>0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count+=1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon,user=user)
            print user
            if prev_order:
                if prev_order[0].status!=1:
                    print 'coupon invalidation1'
                    coupon=None
            print coupon
        print 'check for coupon'
        location = Location.objects.get(pk=location_id)
        address  = Address.objects.filter(user =user ,address=address_str,landmark=landmark)
        if address:
            address=address[0]
        else:
            address  = Address(user =user ,address=address_str,landmark=landmark,location_show=location_show,location=location )
            address.save()
        print 'address done'
        products = bundle.data['products']
        # print products
        products = products.split(',')
        product_ids = map(lambda x:x.split('::')[0],products)
        product_qns = map(lambda x:x.split('::')[1],products)
        print product_ids
        print product_qns
        order = Order(user = user,total_amount=0,address=address,status=3)
        order.delivery_time=dt.datetime.now()+dt.timedelta(hours=1)
        order.save()
        print 'order obj saved'
        total_amount = 0
        index=0

        ordered_services={}
        products_json=[]
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append({'spid':prd.id,'pid':prd.product.product.id,'name':prd.product.product.name,'price':prd.price,'discount':prd.discount,'qn':product_qns[index],'size_id':prd.product.size.id})
            service = prd.product.product.category.service
            if 'offer' in service.name.lower():
                OfferProductOrderMapping(device_id=device_id,order=order,offer_product=prd.offerproductmapping_set.all()[0]).save()
                OfferDeviceId(device_id=device_id).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)]= 0
            total_amount+= int(product_qns[index])*(prd.price- prd.discount)
            ordered_services[str(service.id)]+= int(product_qns[index])*(prd.price- prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order,store=store)
            if cart:
                cart=cart[0]
            else:
                cart = Cart(order=order,store=store)
                cart.save()

            OrderedProduct(product=prd,cart=cart,quantity=product_qns[index]).save()
            index+=1
        service_amount_ordered=[]
        for key in ordered_services:
            service_amount_ordered.append(str(key)+":"+str(ordered_services[key]))
        service_amount_ordered=';;'.join(service_amount_ordered)
        print total_amount

        final_amount=total_amount
        if coupon:
            if total_amount>=coupon.min_total:
                order.coupon_applied=coupon
                print 'found coupon'
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(coupon,user,location_id,int(app_version),final_amount,service_amount_ordered)['discount']
                print "discount" + str(discount)
                final_amount-=discount
        print "passed coupon part"
        delivery_charges = 0
        delivery_charges_to_save_in_order={}
        for key in ordered_services:
            service=Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service,location=location)
            if lsm:
                lsm=lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True,is_active=True,lsm=lsm)
                print 'done'
                if stl:
                    stl=stl[0]
                    # print 'done1'
                    if key not in delivery_charges_to_save_in_order:
                        # print 'done10'
                        delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':stl.delivery_min_amount}
                        # print 'done11'
                    if ordered_services[key]<stl.delivery_min_amount:
                        # print 'done20'
                        final_amount+=-stl.delivery_charges
                        total_amount+=stl.delivery_charges
                        # print 'done21'
                        delivery_charges_to_save_in_order[key]['delivery_charges']=stl.delivery_charges
                        # print 'done22'
                else:
                    delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
            else:
                delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
        print "passed delivery part"
        order.total_amount=total_amount
        order.final_amount=final_amount
        if bring_change_of:
            order.change_requested=bring_change_of
        order.delivery_charges = simplejson.dumps(delivery_charges_to_save_in_order)
        order.save()
        products_json=simplejson.dumps(products_json)
        Invoice(order=order,product_json=products_json).save()
        bundle.obj=order
        OrderActivity(order=order,user=order.user,actions=0,comment=" ").save()
        print bundle
        return bundle