/* static/js/main.js */functionpopupfun(prod_id){window.open("pick/"+prod_id,"Add to cart","status=1,height:500,width:300,toolbar=0,resizeable=0");returnfalse;}
# orders/views.py@login_requireddefpick_product(request,id):ifrequest.method=="POST":qty=to_num(request.POST['qty'])ifqtyisNoneorqty==0:returnHttpResponse("<script>window.close();</script>")toppings=clean_form_data(request.POST)n_topping=Product.objects.get(id=id).n_toppingifsum(toppings.values())!=n_topping:returnHttpResponse("<script>alert('This product should have "+str(n_topping)+" topping\(s\).')</script>")additions=clean_form_data(request.POST,{'ptn':r'addition_(\d+)$','rpl':r'\1'})# prepare carttry:cart=Cart.objects.get(user=request.user)exceptCart.DoesNotExist:cart=Cart.objects.create(user=request.user)product=Product.objects.get(pk=id)item=Item(product=product,quantity=qty,price=product.price)# judge if duplicateditm_dup=Falseitm_trk={'product':item.product.id,'price':item.price,'topping':dict(),'addition':dict()}iflen(toppings)>0:forkeyintoppings:topping=Topping.objects.get(id=to_num(key))itm_trk['topping'][key]=toppings[key]itm_trk['price']+=topping.price*toppings[key]iflen(additions)>0:forkeyinadditions:addition=Addition.objects.get(id=to_num(key))itm_trk['addition'][key]=additions[key]itm_trk['price']+=addition.price*additions[key]## if duplicate, add 1foritmincart.cartitem_set.all():itm_str=show_item(itm.item)ifitm_trk==itm_str:itm_dup=Trueitm.quantity+=qtyitm.save()break## if not duplicate, insert recordifnotitm_dup:item.save()iflen(toppings)>0:forkeyintoppings:topping=Topping.objects.get(id=to_num(key))ItemTopping.objects.create(item=item,topping=topping,quantity=toppings[key])item.price+=topping.price*toppings[key]iflen(additions)>0:forkeyinadditions:addition=Addition.objects.get(id=to_num(key))ItemAddition.objects.create(item=item,addition=addition,quantity=additions[key])item.price+=addition.price*additions[key]item.save()CartItem.objects.create(cart=cart,item=item,quantity=qty)returnredirect(reverse('cart'))else:products=Product.objects.get(id=id)toppings=Topping.objects.all()additions=Addition.objects.filter(size=products.size)returnrender(request,"orders/pick_product.html",{"product":products,"toppings":toppings,"additions":additions})
/* static/js/cart/js */document.addEventListener('DOMContentLoaded',()=>{update_price();document.addEventListener('change',evt=>{if(evt.target.id=='check_all'){batch_check(evt.target.checked);update_price();};if(evt.target.dataset.class=='qty'||evt.target.dataset.class=='order'){update_price();};});document.getElementById('btn_submit').addEventListener('click',evt=>{letselect=document.getElementById('select_price').innerHTML;if(Number(select)==0){evt.preventDefault();alert("Please select at least 1 item.");};});});functionupdate_price(){varprice=0;varselected=0;document.querySelectorAll('input').forEach(elem=>{if(elem.dataset.class=='qty'||elem.dataset.class=='order'){letitem_id=elem.dataset.item;letunit_price=document.getElementById("product_price_"+item_id).innerHTML;letqty=document.getElementById('product_'+item_id).value;letitem_price=Number(qty)*Number(unit_price);if(elem.dataset.class=='order'){if(elem.checked){selected+=item_price;};}else{price+=item_price;};};});document.getElementById("total_price").innerHTML=price.toFixed(2);document.getElementById("select_price").innerHTML=selected.toFixed(2);};functionbatch_check(check=true){document.querySelectorAll('input').forEach(elem=>{if(elem.dataset.class=='order'){elem.checked=check};});};
# orders/views.py@login_requireddefcart(request):ifrequest.method=="POST":# save the formcart=Cart.objects.get(user=request.user)items=clean_form_data(request.POST,{'ptn':r'product_(\d+)$','rpl':r'\1'},del_val=())orders=clean_form_data(request.POST,{'ptn':r'order_product_(\d+)$','rpl':r'\1'})cart_items=cart.cartitem_set.all()forkeyinitems:item=cart_items.get(item=Item.objects.get(pk=to_num(key)))ifitems[key]==0:item.delete()Item.objects.filter(pk=to_num(key)).delete()else:ifitem.quantity!=items[key]:item.quantity=items[key]item.updated=datetime.datetime.now()item.save()cart.save()cart_det=show_cart(request.user)if'btn_save'inrequest.POST:returnrender(request,"orders/cart.html",{'items':cart_det['items'],'message':['success','Cart saved.'],'cart_sum':cart_det['price']})elif'btn_submit'inrequest.POST:iflen(orders)>0:order=Order.objects.create(user=request.user,price=0)forkeyinorders:item=cart_items.get(item=Item.objects.get(pk=to_num(key)))OrderItem.objects.create(order=order,quantity=item.quantity,item=Item.objects.get(pk=to_num(key)))order.quantity+=item.quantityorder.price+=item.item.price*item.quantityitem.delete()order.save()returnrender(request,'orders/orders.html',{'orders':Order.objects.filter(user=request.user),'message':None})else:cart_det=show_cart(request.user)returnrender(request,"orders/cart.html",{'items':cart_det['items'],'message':None,'cart_sum':cart_det['price']})
/* static/js/orders.js */document.querySelectorAll('button').forEach(elem=>{constbtn_dict={'btn_pay':'pay','btn_cancel':'cancel','btn_delete':'delete'};if(['btn_pay','btn_cancel','btn_delete'].indexOf(elem.id)>=0){elem.addEventListener('click',evt=>{if(!check_clickable(btn_dict[elem.id])){evt.preventDefault();alert('No order is selected or \r\n
not all the selected orders can '+btn_dict[elem.id]+'.');};});}elseif(['pay','cancel','delete'].indexOf(elem.name)>=0){elem.addEventListener('click',confirm_submit);};});functioncheck_clickable(state){/* check if the pay_all, cancel_all, delete_all buttons are clickable */varo=true;varany_checked=false;constdict={'pay':['Pending','Failed'],'cancel':['Pending','Failed'],'delete':['Failed','Cancelled']};document.querySelectorAll('input').forEach(elem=>{if(elem.dataset.class=='order'){if(elem.checked){any_checked=true;letitem_id=elem.dataset.item;letitem_status=document.getElementById('status_'+item_id).innerHTML;if(!item_statusindict[state]){o=false;returnfalse;};};};});if(!any_checked){o=false;};returno;};functionconfirm_submit(evt){varwin=window.confirm("Confirm with the operation?");if(!win){evt.preventDefault();};};
# orders/views/py@login_requireddeforders(request):ifrequest.method=="POST":ifany(_inrequest.POSTfor_in('btn_pay','btn_cancel','btn_delete')):orders=clean_form_data(request.POST,{'ptn':r'order_(\d+)$','rpl':r'\1'})if'btn_pay'inrequest.POST:raiseHttp404('Payment function is not available now.')else:forkeyinorders:order=Order.objects.get(pk=to_num(key))if'btn_delete'inrequest.POST:order_items=order.orderitem_set.all()foritminorder_items:Item.object.get(pk=itm.item.id).delete()order.delete()elif'btn_cancel'inrequest.POST:order.status='Cancelled'order.updated=datetime.datetime.now()order.save()btn=[_for_in('pay','cancel','delete')if_inrequest.POST]iflen(btn)>0:order_id=request.POST[btn[0]]if'pay'inrequest.POST:raiseHttp404('Payment function is not available now.')else:order=Order.objects.get(pk=to_num(order_id))if'delete'inrequest.POST:order_items=order.orderitem_set.all()foritminorder_items:Item.objects.get(pk=itm.item.id).delete()order.delete()elif'cancel'inrequest.POST:order.status='Cancelled'order.updated=datetime.datetime.now()order.save()returnrender(request,"orders/orders.html",{'orders':Order.objects.filter(user=request.user),'message':['success','Orders modified.']})else:orders=Order.objects.filter(user=request.user)returnrender(request,"orders/orders.html",{'orders':orders})
# orders/views.py@login_requireddeforder(request,id):ifrequest.method=="POST":ifany(_inrequest.POSTfor_in('btn_save','btn_pay','btn_cancel','btn_delete')):order=Order.objects.get(pk=id)items=clean_form_data(request.POST,{'ptn':r'product_(\d+)$','rpl':r'\1'},del_val=('0',''))order_items=order.orderitem_set.all()order.quantity=order.price=0forkeyinitems:item=Item.objects.get(pk=to_num(key))order_item=order_items.get(item=item)ifitems[key]==0:order_item.delete()item.delete()else:iforder_item.quantity!=items[key]:order_item.quantity=items[key]order_item.updated=order.updated=datetime.datetime.now()order_item.save()order.quantity+=items[key]order.price+=item.price*items[key]order.save()if'btn_pay'inrequest.POST:raiseHttp404('Payment function is not available now.')elif'btn_delete'inrequest.POST:order.delete()returnredirect(reverse('orders'))elif'btn_cancel'inrequest.POST:order.status='Cancelled'order.save()returnrender(request,'orders/order.html',{'items':order.orderitem_set.all(),'order':order,'id':id,'message':['success','Modification saved.']})else:order=Order.objects.get(pk=id)returnrender(request,"orders/order.html",{'items':order.orderitem_set.all(),'order':order})