def get_coupon_code_discount(request): data = {} coupon_code = request.GET.get("code") username = request.GET.get("username") api_key = request.GET.get("api_key") location_id = request.GET.get("location_id") version = request.GET.get("version") # device_id = request.GET.get('device_id') total = request.GET.get("total") service_vs_total = request.GET.get("service_vs_total") user = User.objects.get(username=username) if not user: data = simplejson.dumps("not valid Request") return HttpResponse(data, content_type="application/json", status=403) if user.api_key.key != api_key: data = simplejson.dumps("not valid Request") return HttpResponse(data, content_type="application/json", status=403) coupon = Coupon.objects.filter(code__iexact=coupon_code, is_active=True) if coupon: coupon = coupon[0] res = verify_coupon( coupon=coupon, user=user, location=int(location_id), version=int(version), total=total, service_amount_ordered=service_vs_total, ) data["id"] = coupon.id data["discount"] = res["discount"] data = simplejson.dumps({"objects": data, "status": res["status"]}) else: data = simplejson.dumps({"objects": {"discount": 0}, "status": "Promo code is not valid"}) return HttpResponse(data, content_type="application/json")
def alter_list_data_to_serialize(self, request, data): # Example iteration through data index=0 status = 'Promo code is not Valid' for item in data['objects']: coupon = item.obj device_id = request.GET.get('device_id') contact = request.GET.get('contact') version = request.GET.get("version","") location = request.GET.get("location_id","") service_vs_total = request.GET.get("service_vs_total","") min_total = request.GET.get("total","") user = User.objects.filter(username=contact) print service_vs_total if version: version = int(version) if user and version>28: user=user[0] res = verify_coupon(coupon, user, int(location), int(version), min_total, service_vs_total ) status=res['status'] if res['discount'] ==0: del data['objects'][index] else: data['objects'][index].data['discount']=res['discount'] data['objects'][index].data['discount_type']=0 else: del data['objects'][index] status = "Coupon valid only on updated app" order = Order.objects.filter(Q(user__userprofile__contact= contact,coupon_applied=coupon)|Q(user__userprofile__device_id= device_id,coupon_applied=coupon)) if order: if order[0].status!=1: del data['objects'][index] index+=1 del data['meta'] data['status']=status return data
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)
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
def get_osm_info(self,id): # print id order = Order.objects.get(pk=id) invoice= order.invoice products=[] total_amount=0 order_products = simplejson.loads(invoice.product_json) # reduce db query # products = map(lambda x: x['spid'],order_products) # products = all_in_one=[] for p in order_products: dict_index = -1 service_dict={} product={} product['sp']=StoreProductMapping.objects.get(pk=p['spid']) prd = product['sp'] service = str(prd.product.product.category.service.id) if service not in map(lambda x: x['id'],all_in_one): service_dict['total']=0 service_dict['sub_total']=0 service_dict['id']=service service_dict['name']=str(prd.product.product.category.service.name) service_dict['items']=[] service_dict['coupon_code']="----" service_dict['coupon_discount']=0 service_dict['delivery_charges']=0 service_dict['store']=prd.store else: dict_index+=1 for elem in all_in_one: if service==elem['id']: service_dict=elem break if 'discount' in p: if p['discount']>0: product['normal_price']=p['price'] product['normal_total_price']=int(p['qn'])*p['price'] product['price']=p['price']-p['discount'] else: product['price']=p['price'] product['qn']=p['qn'] product['total_price']=int(p['qn'])*float(product['price']) product['size']={} mag = int(Size.objects.get(pk=p['size_id']).magnitude) if float(mag)!=Size.objects.get(pk=p['size_id']).magnitude: mag = Size.objects.get(pk=p['size_id']).magnitude product['size']['mag']= mag product['size']['unit']=Size.objects.get(pk=p['size_id']).unit product['image_link']=str(StoreProductMapping.objects.get(pk=p['spid']).product.image).replace('movinCartApp/','/') total_amount+=int(p['qn'])*float(product['price']) service_dict['total']+=int(p['qn'])*float(product['price']) service_dict['sub_total']+=int(p['qn'])*float(p['price']) service_dict['items'].append(product) products.append(product) if dict_index<0: all_in_one.append(service_dict) if order.delivery_time: delivery_time = order.delivery_time.strftime('%B %d, %Y, %I:%M %p') else: delivery_time = order.created_at + dt.timedelta(hours=1) delivery_time = delivery_time.strftime('%B %d, %Y, %I:%M %p') coupon = order.coupon_applied isDiscounted=False discount_money=0 coupon_code='No Coupon' total_without_discount=total_amount total_without_discount_without_delivery_charges=total_amount if coupon: service_amount_ordered=[] for a in all_in_one: service_amount_ordered.append(str(a['id'])+":"+str(a['total'])) service_amount_ordered=';;'.join(service_amount_ordered) coupon_code = coupon.code discount_money= verify_coupon(coupon,order.user,order.address.location_id,int(order.user.userprofile.app_version),order.final_amount,service_amount_ordered,flag=0)['discount'] total_amount-=discount_money discount_temp = discount_money for a in all_in_one: if discount_temp>0: # service_amount_ordered.append(str(a['id'])+":"+str(a['total'])) disc = verify_coupon(coupon,order.user,order.address.location_id,int(order.user.userprofile.app_version),int(float(a['total'])),str(a['id'])+":"+str(a['total']),flag=0)['discount'] print a['name'] print a['total'] print a['sub_total'] print disc print discount_temp print '---------------------------------------------------' if disc>discount_temp: disc=discount_temp a['total'] -= disc discount_temp-=disc if disc > 0: a['coupon_code']=coupon.code a['coupon_discount']=disc isDiscounted=True delivery_charges_dictionary_new=simplejson.loads(order.delivery_charges) delivery_charges=0 for key in delivery_charges_dictionary_new: if filter(lambda x:x['id']==key,all_in_one): filter(lambda x:x['id']==key,all_in_one)[0]['delivery_charges']+=delivery_charges_dictionary_new[key]['delivery_charges'] total_amount+=delivery_charges_dictionary_new[key]['delivery_charges'] total_without_discount+=delivery_charges_dictionary_new[key]['delivery_charges'] delivery_charges+=delivery_charges_dictionary_new[key]['delivery_charges'] change_req = "" if order.change_requested: change_req = "Bring change of : " + str(order.change_requested) else: if order.final_amount % 1000 < 100: bring_change_of = "100" elif order.final_amount % 1000 < 500: bring_change_of = "500" else: bring_change_of = "1000" change_req = "(Auto) Bring change of : " + str(bring_change_of) order_activities = OrderActivity.objects.filter(order=order).order_by('-created_at') context = { 'customer':order.user, 'order':order, 'products':products, 'total_amount':total_amount, 'total_without_discount':total_without_discount, 'delivery_time':delivery_time, 'isDiscounted':isDiscounted, 'discount_money':discount_money, 'coupon_code':coupon_code, 'all_in_one':all_in_one, 'total_without_discount_without_delivery_charges':total_without_discount_without_delivery_charges, 'delivery_charges':delivery_charges, 'change_req':change_req, 'order_activities':order_activities, } return context