def modal(request): t = loader.get_template("orders/modalmenu.html") if request.method == "POST": i = int(request.POST["itemid"]) item = Menu.objects.get(id=i) cart = Cart.objects.get(user_id=request.user.id) r = { "item": item.item, "itemid": i, "category": item.category.item, "size": request.POST["size"], "price": float(request.POST["price"]), "quantity": int(request.POST["quantity"]), "cart": cart, "toppings": request.POST.getlist("toppings[]"), } form = CreateOrderItem(r, x=i) if form.is_valid(): r.pop("itemid") toppingspop = r.pop("toppings") orditem = OrderItem(**r) orditem.save() if len(toppingspop) > 0: orditem.toppings.set(toppingspop) orditem.save() return HttpResponse("it was a success!", status=200) else: return HttpResponse(t.render({"form": form}, request), status=422) elif request.method == "GET": i = int(request.GET["item"]) item = Menu.objects.get(id=i) form = CreateOrderItem(x=i, initial={"size": "Large"}) return HttpResponse(t.render({"item": item, "form": form}, request))
def new_order(request, pk): template = 'pos/new_order.html' form = OrderForm(request.POST or None) if request.method == 'POST': if form.is_valid(): table_order = Order.objects.filter(table=pk) latest = table_order.latest('created') if latest.paid == True: order = Order() else: order = latest order.number = Order.objects.count() + 1 order.table = Table.objects.get(number=pk) order.paid = False order.save() orderitem = OrderItem() product = form.cleaned_data.get('product') orderitem.product = Product.objects.get(title=product) orderitem.order = order orderitem.table = Table.objects.get(number=pk) orderitem.quantity = form.cleaned_data.get('quantity') orderitem.total_price = orderitem.quantity * orderitem.product.unit_price orderitem.discount = form.cleaned_data.get('discount') orderitem.notes = form.cleaned_data.get('notes') orderitem.save() return redirect('/table/' + pk) context = {'form': form} return render(request, template, context)
def save(self, user, commit=True): from django.contrib.contenttypes.models import ContentType # booking = super(BookingForm, self).save(commit=False) booking.booked_by = user open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] if commit: booking.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=booking.price.__unicode__(), value=(booking.price.value * booking.quantity), vat=booking.price.vat, content_type=ContentType.objects.get_for_model(booking), object_id=booking.id) order_item.save() return booking
def save(self, user, commit=True): from django.contrib.contenttypes.models import ContentType # booking = super(BookingForm, self).save(commit=False) booking.booked_by = user open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] if commit: booking.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=booking.price.__unicode__(), value=(booking.price.value*booking.quantity), vat=booking.price.vat, content_type=ContentType.objects.get_for_model(booking), object_id=booking.id ) order_item.save() return booking
def create_order(request): cart = request.data.get("cart") orderData = request.data.get("order") orderData['user'] = request.user serializers = OrderSerializer(orderData) print(orderData) order = Order.objects.create( firstname = orderData['firstname'], lastname = orderData['lastname'], email = orderData['email'], address = orderData['address'], city = orderData['city'], postal_code = orderData['postal_code'], user = request.user ) if cart: for item in cart: product = get_object_or_404(Product, id=item['id']) order_item = OrderItem( order=order, product = product, price = item['price'], quantity = item['quantity'] ) order_item.save() else: order.delete() return Response(status=HTTP_400_BAD_REQUEST,data='Cart is Empty') return Response({'order_no': order.id}, status=HTTP_201_CREATED)
def test_get_total_cost(self): for item in range(10): order_item = OrderItem(order=self.order, product=self.product, price=1, count=1) order_item.save() self.assertEqual(self.order.get_total_cost(), 10)
def _change_order_item_packed_state(order_item: OrderItem, packed_state: bool) -> None: """Изменение состояния упаковки строки заявки :param order_item: Строка заявки :param packed_state: Состояние """ order_item.packed = packed_state order_item.save(update_fields=['packed'])
def checkout(request): context = {} print('url = ',request.build_absolute_uri) cart_obj, cart_created = Cart.objects.new_or_get(request) billing_address_id = request.session.get('billing_address_id', None) shipping_address_id = request.session.get('shipping_address_id', None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.cart_items.count() == 0: return redirect('/') login_form = LoginForm() guest_form = GuestForm() if billing_profile : if not shipping_address_id : return redirect('addresses:shipping_address') if not billing_address_id: return redirect('addresses:billing_address') context['shipping_address'] = Address.objects.get(id=shipping_address_id, billing_profile=billing_profile) context['billing_address'] = Address.objects.get(id=billing_address_id, billing_profile=billing_profile) if request.method == "POST": if billing_profile is not None: print('billing exist') order_obj, new_obj = Order.objects.new_or_get(billing_profile, cart_obj) if shipping_address_id: print(shipping_address_id) order_obj.shipping_address = Address.objects.get(id=shipping_address_id) if billing_address_id: print(billing_address_id) order_obj.billing_address = Address.objects.get(id=billing_address_id) if billing_address_id or shipping_address_id: order_obj.save() order_item = OrderItem() for item in cart_obj.cart_items.all(): order_item = OrderItem() order_item.order = order_obj order_item.item = item.item order_item.quantity = item.quantity order_item.total = item.total order_item.save() cart_obj.cart_items.all().delete() del request.session['item_count'] return redirect("success") context['order'] = order_obj context['form'] = login_form context['guest_form'] = guest_form context['cart'] = cart_obj context['billing_profile'] = billing_profile return render(request, 'carts/checkout.html', context)
def process_order(request): context = RequestContext(request) user = request.user increment_clicks(user) profile = get_associated_profile(user) cart = get_cart(profile) items_to_package = [] total_price = 0 for item in CartItem.objects.all(): if item.cart == cart: items_to_package.append(item.item) total_price = total_price + item.item.price entry_id = request.POST.get("entry_id") entry = Entry.objects.get(id=entry_id) new_order = Order( user_profile=profile, restaurant=profile.restaurant, total=total_price, entry=entry, status="PDG", order_success=False, order_rating=0, ) new_order.save() order_dict = {} for item in items_to_package: if item.id in order_dict.keys(): order_dict[item.id] = order_dict[item.id] + 1 else: order_dict[item.id] = 1 order_items = [] for key in order_dict.keys(): item = Item.objects.get(id=key) quantity = order_dict[key] new_order_item = OrderItem(item=item, order=new_order, quantity=quantity) new_order_item.save() order_items.append(new_order_item) # cart.delete() # print order_dict.keys() cart_id = cart.id print cart.id return render_to_response( "confirm.html", {"total_price": total_price, "user": user, "profile": profile, "order_items": order_items, "cart_id": cart_id}, context, )
def change_cart_item(cls, cart_obj, product_item, is_added_to_cart): """ Change the cart item - Add more existed product to cart. - Add new product to cart. - Update product item quantity in cart. @param is_added_to_cart: A flag to determine add to cart or not @param cart_obj: Shopping cart object @param product_item: Product item data @return: Return `True` if the process completed successfully. """ try: cart_item_objs = OrderItem.objects.non_archived_only() \ .filter(order=cart_obj, product=product_item['product']) except EmptyCartException as e: raise e is_duplicated_item = len(cart_item_objs) > 1 is_one_item = len(cart_item_objs) == 1 # Do not allow duplicate cart item. if is_duplicated_item: raise DuplicateCartItemException( 'There are duplicate product item ' 'in the cart') if is_added_to_cart: if is_one_item: cart_item_objs.update(quantity=F('quantity') + 1) else: # There is no item in the cart. Create a new one. new_item_values = { 'order': cart_obj, 'product': Product.objects.get(pk=product_item['product']), 'quantity': 1 } cart_item_obj = OrderItem(**new_item_values) cart_item_obj.save() return True else: # Update cart item quantity if is_one_item: updated_data = {'quantity': product_item.get('quantity', None)} UpdatingCartItemSerializer(data=updated_data).is_valid( raise_exception=True) cart_item_objs.update(**updated_data) return True else: raise CartItemDoesNotExistException('Cart item not found')
def save(self, event, price, user, commit=True): from django.contrib.contenttypes.models import ContentType # booking = super(BookingForm, self).save(commit=False) booking.booked_by = user booking.event = event booking.price = price total_booked = 0 open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] for item in order.orderitem_set.all(): total_booked += item.content_object.quantity if not(event.pricing_set.all().filter(online_book=True) and not event.fully_booked): raise ValidationError( _('This event is fully booked'), code='Fully Booked' ) commit = False elif event.num_spaces < (booking.quantity + total_booked): places = booking.quantity + total_booked raise ValidationError( _('Not enough spaces for %(places)s people.'), code='No Space', params={'places': places}, ) commit = False if commit: booking.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=event.__unicode__(), value=(price.value*booking.quantity), vat=price.vat, content_type=ContentType.objects.get_for_model(booking), object_id=booking.id ) order_item.save() return booking
def order_add_var_item(request, pk, var_pk, restaurant_pk, menu_pk, **kwargs): product = Product.objects.get(pk=pk) variation = ProductVariation.objects.get(pk=var_pk) menu = Menu.objects.get(pk=menu_pk) restaurant = Restaurant.objects.get(pk=restaurant_pk) if request.user.is_authenticated: pass # TODO: Lógica para usuários autenticados try: order_slug = request.session["order_slug"] except KeyError: order = Order(restaurant=restaurant) order.save() request.session["order_slug"] = order_slug = order.slug order = Order.objects.get(slug=order_slug) if order.orderitem_set.all().filter(item=product, variation=variation).exists(): item = OrderItem.objects.get(order=order, item=product, variation=variation) item.quantity = item.quantity + 1 item.save() messages.info( request, f'{product.name} Já está no pedido. ' f'<a href="/orders/cart/{order_slug}/" ' f'class="alert-link">Ver pedido</a>.') return redirect( reverse('restaurant_menu', kwargs={ 'restaurant_slug': restaurant.slug, 'menu_slug': menu.slug })) else: item = OrderItem(order=order, item=product, unity_price=variation.price, variation=variation) item.save() messages.success( request, f'{item.item.name} adicionado ao pedido. ' f'<a href="/orders/cart/{order_slug}/" ' f'class="alert-link">Ver pedido</a>.') return redirect( reverse('restaurant_menu', kwargs={ 'restaurant_slug': restaurant.slug, 'menu_slug': menu.slug }))
def create(self, validated_data): print('>>>', validated_data) chef = validated_data.get('chef') consumer = validated_data.get('consumer') meal = validated_data.get('meal') quantity = validated_data.get('quantity') item = OrderItem(consumer=consumer, chef=chef, meal=meal, quantity=quantity) item.save() return item
def test_get_total_cost_product_different_count(self): for item in range(10): product = Product(product_name=str(item), product_image="", product_prices=5 * item, product_overview=str(item)) product.save() order_item = OrderItem(order=self.order, product=product, price=product.product_prices, count=item) order_item.save() # self.assertEqual(self.order.get_total_cost(), 1425)
def create_order_item(order, supplier, unit_cost=1.0, quantity=1, supplier_order=None, name=None): if not name: name = "test_ingredient_%d" % random.randint(0, 9999) ingredient, _ = Ingredient.objects.get_or_create( unit_cost=unit_cost, name=name, supplier=supplier) order_item = OrderItem( ingredient=ingredient, user_order=order, quantity=quantity, supplier_order=supplier_order) order_item.save() return order_item
def handle(self, *args, **kwargs): file_name = kwargs['file_name'] with open(f'{file_name}.csv') as csv_file: reader = csv.DictReader(csv_file) for row in reader: try: order_item = OrderItem(order_id=row['order_id'], product_name=row['product_name'], qty=row['qty']) order_item.save() except Exception as e: raise CommandError('OrderItem save fail') self.stdout.write( self.style.SUCCESS('%s.csv Data Feed Success!' % file_name))
def save(self, event, price, user, commit=True): from django.contrib.contenttypes.models import ContentType # booking = super(BookingForm, self).save(commit=False) booking.booked_by = user booking.event = event booking.price = price total_booked = 0 open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] for item in order.orderitem_set.all(): total_booked += item.content_object.quantity if not (event.pricing_set.all().filter(online_book=True) and not event.fully_booked): raise ValidationError(_('This event is fully booked'), code='Fully Booked') commit = False elif event.num_spaces < (booking.quantity + total_booked): places = booking.quantity + total_booked raise ValidationError( _('Not enough spaces for %(places)s people.'), code='No Space', params={'places': places}, ) commit = False if commit: booking.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=event.__unicode__(), value=(price.value * booking.quantity), vat=price.vat, content_type=ContentType.objects.get_for_model(booking), object_id=booking.id) order_item.save() return booking
def create_order(cart_id, user, context): cart = Cart.objects.get(id=cart_id) items = cart.get_items_and_quantities() profile = users.views.return_associated_profile_type(user) entry = cart.entry total = cart.get_total_price_of_cart() tax = cart.get_tax_for_cart() new_order = Order( profile=profile, total=total + tax, entry=entry, status='PDG', ) new_order.save() for item in items.keys(): new_order_item = OrderItem( item=item, order=new_order, quantity=items[item] ) item.number_ordered = item.number_ordered + 1 item.save() new_order_item.save() entry.available = entry.available - 1 entry.save() cart.cart_still_active = False cart.delete() profile = UserProfile.objects.get(user=user) send_receipt_text(profile, new_order) return render_to_response( 'successful_charge.html', { 'entry':entry, }, context)
def process_order(request): context = RequestContext(request) user = request.user profile = get_associated_profile(user) cart = get_cart(profile) items_to_package = [] total_price = 0 for item in CartItem.objects.all(): if item.cart == cart: items_to_package.append(item.item) total_price = total_price + item.item.price entry_id = request.POST.get("entry_id") entry = Entry.objects.get(id=entry_id) new_order = Order( user_profile=profile, restaurant=profile.restaurant, total=total_price, entry=entry, status="PDG", order_success=False, order_rating=0, ) new_order.save() order_dict = {} for item in items_to_package: if item.id in order_dict.keys(): order_dict[item.id] = order_dict[item.id] + 1 else: order_dict[item.id] = 1 for key in order_dict.keys(): item = Item.objects.get(id=key) quantity = order_dict[key] new_order_item = OrderItem(item=item, order=new_order, quantity=quantity) new_order_item.save() cart.delete() return redirect("checkout.views.checkout")
def save_order(stripe_response): # print("Fulfilling order") transaction_id = stripe_response.id user_id = stripe_response.metadata.user_id cart_id = stripe_response.metadata.cart_id # Fetch all record of cart try: cart_data = Cart.objects.get(id=cart_id) except Cart.DoesNotExist: cart_data = None if cart_data is not None: # Insert into orders table order = Order(user_id=user_id, total=cart_data.total, transaction_id=transaction_id) order.save() latest_order_id = Order.objects.latest('id') # Fetch all record of cart items try: cart_items = CartItem.objects.filter(cart_id=cart_data.id) except CartItem.DoesNotExist: cart_items = None if cart_items is not None: # Insert into order detail table for data in cart_items: product_info = Product.objects.get(id=data.product_id) order_item = OrderItem(order_id=latest_order_id.pk, product_id=data.product_id, quantity=data.quantity, product_price=product_info.price, product_total=data.product_total) order_item.save() # Removing the current cart and its item data cart_data.delete() cart_items.delete() return True
def post(self,request,pk=None,format=None): # print('Request data is ' + str(request.data)) # o_parameters = {"table_no":request.data['tableno']} # r = requests.post('http://127.0.0.1:8000/orders/o/',data=o_parameters) print('aa') check_ob = Order.objects.filter(table_no=request.data['tableno']).count() if(check_ob <=0 ): new_order = Order(table_no=request.data['tableno']) new_order.save() order = Order.objects.get(table_no=request.data['tableno']) print('bb') print(order) check_oi = OrderItem.objects.filter(order=order).count() orderi = OrderItem(order=order,quantity=request.data['quantity']) orderi.save() food = FoodItem.objects.get(name=request.data['name']) print(orderi.fooditem) orderi.fooditem.add(food) return Response('Success')
def post(self,request,pk=None,format=None): table_qs = Table.objects.filter(table_no = request.data['tableno']) table = list(table_qs)[0] # print(table) check_ob = Order.objects.filter(table_no=table).count() if(check_ob <=0 ): new_order = Order(table_no=table) new_order.save() order_qs = Order.objects.filter(table_no = table) order = list(order_qs)[0] print(order) food = FoodItem.objects.get(name=request.data['name']) print(food) orderi = OrderItem(order=order,fooditem=food,quantity=request.data['quantity']) orderi.save() return Response('Success')
def save(self, user, value, commit=True): from django.contrib.contenttypes.models import ContentType pricing = Pricing() pricing.value = value pricing.save() donation = super(PaymentForm, self).save(commit=False) donation.price = pricing donation.booked_by = user open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] if commit: donation.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=donation.__unicode__(), value=(pricing.value*donation.quantity), vat=donation.price.vat, content_type=ContentType.objects.get_for_model(donation), object_id=donation.id ) order_item.save() return pricing
def save(self, user, value, commit=True): from django.contrib.contenttypes.models import ContentType pricing = Pricing() pricing.value = value pricing.save() donation = super(PaymentForm, self).save(commit=False) donation.price = pricing donation.booked_by = user open_order_list = Order.objects.open_order(user=user) if open_order_list: order = open_order_list[0] if commit: donation.save() # Add to open order if not open_order_list: order = Order(ordered_by=user) order.save() order_item = OrderItem( order=order, description=donation.__unicode__(), value=(pricing.value * donation.quantity), vat=donation.price.vat, content_type=ContentType.objects.get_for_model(donation), object_id=donation.id) order_item.save() return pricing
def save_cart_as_order(cart): address = None if cart.get('details').get('delivery_address'): address = Address( street_one = cart.get('details').get('delivery_address').get('street_one'), street_two = cart.get('details').get('delivery_address').get('street_two'), city = cart.get('details').get('delivery_address').get('city'), state = cart.get('details').get('delivery_address').get('state'), zipcode = cart.get('details').get('delivery_address').get('zipcode'), ) address.save() customer = Customer( first_name = cart.get('details').get('contact_info').get('first_name'), last_name = cart.get('details').get('contact_info').get('last_name'), email = cart.get('details').get('contact_info').get('email'), phone_number = cart.get('details').get('contact_info').get('phone'), address = address, ) customer.save() order = Order( ref_code = create_ref_code(), customer = customer, ordered_date = timezone.now(), pickup = cart.get('details').get('pickup'), note = cart.get('details').get('note'), ) order.save() id_list = cart.get('details').get('item_id_list') for id in id_list: item = Item.objects.get(id=id) order_item = OrderItem( item = item, quantity = cart.get(str(id)).get('quantity'), note = cart.get(str(id)).get('note'), order = order, ) order_item.save() return order
def post(self, request, *args, **kwargs): cart = Cart(request.session) serializer = OrderSerializer(data=request.data) if serializer.is_valid(): order = serializer.save() for item in cart.items: instance = OrderItem( order=order, product=item.product, price=item.price, quantity=item.quantity ) instance.save() cart.clear() UserOrderNotification.apply_async((order.pk,), countdown=10) AdminOrderNotification.apply_async((order.pk,), countdown=10) return Response( status=status.HTTP_201_CREATED ) else: return Response( status=status.HTTP_422_UNPROCESSABLE_ENTITY )
def checkout(request): #assume credit card not recorded for customer until proven otherwise cc_reg = "btn btn-sm btn-success disabled" #get user object user = get_object_or_404(User, username=request.user) #set cost and amount variables global total_cost total_cost = 0 total_amount = 0 delivery_cost = 0 #if basket present if 'cart' in request.session: #Select all records from Cart_Item for current id items_in_cart = CartItem.objects.filter( cart_id=request.session['cart']) #for each cart item, use the stored product_id to retrive product details from product table products = Product.objects.filter( id__in=[item.product_id for item in items_in_cart]) #getting amount ordered of each product so can auto-fill checkout list for item in products: cartItem_amount = get_object_or_404( CartItem, product_id=item.id, cart_id=request.session['cart']) item.amount = cartItem_amount.amount item.cost = item.amount * item.price total_cost = total_cost + item.cost total_amount = total_amount + item.amount #add £2 deliver charge per item delivery_cost = total_amount * 2 total_cost = total_cost + delivery_cost pence_cost = int(total_cost * 100) if items_in_cart.exists(): #Check that credit card and address have been logged before allowing checkout (and enabling purchase button) if user.stripe_custID == "None": messages.error( request, "Please register a valid credit card in your profile") elif user.address_line1 == "None" or user.address_line2 == "None" or user.county == "None" or user.postcode == "None": messages.error( request, "Please register a delivery address in your profile") else: #enable purchase button cc_reg = "btn btn-sm btn-success" #if request method is POST some is trying to buy product if 'purchase' in request.POST: #set cost and amount variables to check if checkout amounts needs to be refreshed at checkout. # #On a multi-user system for a company with relatively small stock levels, between the customer #putting item(s) in cart and getting to checkout, their is the real risk that another customer purchase #could pull stock levels down to a level where the current customers order can't be met with existing #stock. This would then require extra time to restock, so the company would prefer the customer call them #so they can speak through the options. total_cost_refresh = 0 total_amount_refresh = 0 delivery_cost_refresh = 0 #Go through and check stock levels are still OK pre purchase #i.e has another customer made a purchase and reduced available stock levels below what can be fulfilled? refresh_checkout = False #This is a cart_items_to_refresh = [] for item in products: #Need to get current stock level current_product = get_object_or_404(Product, id=item.id) if item.amount > current_product.stock_level: refresh_checkout = True #Get the object that hold this amount value cartItem = get_object_or_404( CartItem, product_id=item.id, cart_id=request.session['cart']) #set it to the stock leve value (so that 'refresh_checkout' won't be true 2nd time around) cartItem.amount = current_product.stock_level #save it to database cartItem.save() #Also change value of item being iterated over item.amount = current_product.stock_level #tracking the items in order that need to be refreshed cart_items_to_refresh.append(current_product) item.cost = item.amount * item.price total_cost_refresh = total_cost_refresh + ( item.amount * item.price) total_amount_refresh = total_amount_refresh + item.amount #£2 deliver charge per item delivery_cost_refresh = total_amount_refresh * 2 total_cost_refresh = total_cost_refresh + delivery_cost_refresh if refresh_checkout == True: messages.error( request, "Other recent customer purchases mean we can no longer currently meet you order with our existing stock, your order has been updated to reflect current stock levels. Please contact us to discuss acquiring the additional items." ) #Need to amend cartItem to store new amount value, so that if purchase not made #but cart stored, the item is not deleted (on signing back in) unless #stock levels has actually gone below the amended amount for item in cart_items_to_refresh: current_product = get_object_or_404(Product, id=item.id) cart_item = get_object_or_404( CartItem, product_id=item.id, cart_id=request.session['cart']) #if the stock level is 0, remove from cart, no point in having it (would only confuse customer) if current_product.stock_level == 0: cart_item.delete() else: cart_item.amount = current_product.stock_level cart_item.save() #disable the purchase button if refrsh has meant the order is now for nothing (to prevent processing errors) if total_amount_refresh == 0: cc_reg = "btn btn-sm btn-success disabled" return render( request, "checkout/checkout.html", { "user": user, "products": products, "cc_reg": cc_reg, "total_cost": total_cost_refresh, "total_amount": total_amount_refresh, "delivery_cost": delivery_cost_refresh }) try: #Try to make payment! charge = stripe.Charge.create( amount=pence_cost, currency="gbp", customer=user.stripe_custID, ) messages.success(request, "Payment Successful") #Create order entries in database customer = get_object_or_404(User, username=request.user) new_order = Order(address_line1=user.address_line1, address_line2=user.address_line2, county=user.county, postcode=user.postcode, total=(pence_cost / 100), customer_id=customer.id) new_order.save() for item in products: new_orderItem = OrderItem(order_id=new_order.id, product=item, quantity=item.amount, price=item.price) new_orderItem.save() #Reduce the stock level #The amount won't be bigger than current stock levels due to pre-purchase stock #level checks (so no need to check here) current_product = get_object_or_404(Product, id=item.id) current_product.stock_level = current_product.stock_level - item.amount current_product.save() #"When Django deletes an object, by default it emulates the behavior of the SQL constraint ON DELETE #CASCADE – in other words, any objects which had foreign keys pointing at the object to be deleted #will be deleted along with it". So this command should remove the cart and associated cart items #from the database. Cart.objects.filter( id=request.session['cart']).delete() del request.session['cart'] #If the cart was from a stored version, remove it if user.saved_cart_id != 0: user.saved_cart_id = 0 user.save() #Send user to orders page after successful purchase return redirect("orders") #Gracefully catch error, inform customer of issue except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(request, err.get('message')) else: #this is enabling purchase button on initial page load (rather than when purchase has been pressed) #when credit card and address have been stored in database. cc_reg = "btn btn-sm btn-success" return render( request, "checkout/checkout.html", { "user": user, "products": products, "cc_reg": cc_reg, "total_cost": total_cost, "total_amount": total_amount, "delivery_cost": delivery_cost }) #empty cart, let use rknow else: messages.error( request, "Nothing in your cart, please add an item before attempting purchase" ) return render( request, "checkout/checkout.html", { "cc_reg": cc_reg, "total_cost": total_cost, "total_amount": total_amount, "delivery_cost": delivery_cost }) else: messages.error( request, "You don't have a cart yet, please create one by adding an item before attempting purchase" ) return render( request, "checkout/checkout.html", { "cc_reg": cc_reg, "total_cost": total_cost, "total_amount": total_amount, "delivery_cost": delivery_cost })
def populate(): """Populate the database with activity simulating last 365 days.""" # Start by dropping all the previous data main_tables = (Expense, Customer, Order, Item, StatusShift, Timetable, User) for table in main_tables: table.objects.all().delete() # Create a default user name user = User.objects.create_user(username='******', password='******') # random numbers upper bound u = len(WORDS) - 1 # Create some customers for name in NAMES: Customer.objects.create( name=name, address=multiword(), city=multiword(), phone=randint(20000, 2000000), email='{}@{}.com'.format(multiword(1), multiword(1)), cp=randint(1000, 99000), CIF=str(randint(10000, 99000)), notes=multiword(5), provider=randint(0, 1), ) # Create some items for _ in range(10): Item.objects.create( name=WORDS[randint(0, u)], item_type=randint(0, 18), foreing=randint(0, 1), price=randint(10, 150), fabrics=randint(1, 3), stocked=300, ) # Create daily activity for the last n days days = (date.today() - date(date.today().year, 1, 1)).days for n in range(days): print('.', end='') curr_datetime = timezone.now() - timedelta(days=days - n) order = Order.objects.create( inbox_date=curr_datetime, user=user, customer=choice(Customer.objects.filter(provider=False)), ref_name=multiword(), delivery=curr_datetime + timedelta(days=randint(7, 30)), status=randint(1, 6), waist=randint(60, 70), chest=randint(90, 120), hip=randint(90, 120), others=multiword(5), ) for i in range(randint(2, 4)): item = OrderItem( element=choice(Item.objects.all()), reference=order, qty=randint(1, 3), price=randint(10, 100), stock=randint(0, 1), ) item.clean() if randint(1, 15) > 1: item.crop = timedelta(seconds=1000 * randint(1, 3)) item.sewing = timedelta(seconds=1000 * randint(1, 3)) item.iron = timedelta(seconds=1000 * randint(1, 3)) item.save() # Add a comment if randint(1, 15) > 1: Comment.objects.create(creation=curr_datetime, user=user, reference=order, comment=multiword(10)) # Sell something active_orders = Order.live.all() sell_it = randint(1, 20) > 1 # p = 19/20 if sell_it and active_orders.exists(): order = active_orders.first() pay_method = choice(['C', 'T', 'V']) CashFlowIO.objects.create( creation=curr_datetime, order=order, amount=order.pending, pay_method=pay_method, ) if order.status != '7': order.deliver() # Creates status shift # Set status to 9 (invoiced) order.status = '9' order.save() i = Invoice(reference=order, issued_on=curr_datetime, amount=order.total, pay_method=pay_method) i.save(kill=True) # Update Item health [i.save() for i in Item.objects.all()] # Expend some money somewhere providers = Customer.objects.filter(provider=True) expense = Expense.objects.create( creation=curr_datetime, issuer=choice(providers), invoice_no=choice(WORDS), issued_on=curr_datetime, concept=multiword(2), amount=randint(180, 250), pay_method=choice(['C', 'T', 'V']), notes=multiword(5), ) if randint(1, 15) > 1: expense.kill() # Deliver a couple of orders without selling [order.deliver() for order in Order.live.all()[:3]]
def new_order(atg_order, tinla_profile, client): # Ensure that there is no profile with this atg login map_entry = None try: map_entry = AtgOrderMigrationMap.objects.select_related('order').get( atg_order = atg_order.order.order) log.info("Already migrated %s, skipping new_order" % atg_order.order.order) return map_entry.order except AtgOrderMigrationMap.DoesNotExist: pass # create new order order = Order() order.user = tinla_profile order.state = get_order_state(atg_order.order.order_state) order.timestamp = atg_order.order.atg_creation_date order.payment_realized_on = atg_order.order.atg_submitted_date order.modified_on = atg_order.order.last_modified_date order.reference_order_id = atg_order.order.order order.client = client order.save() # delivery info shipping = DcsppShipGroup.objects.filter(order_ref = atg_order.order.order) if shipping: shipping = shipping[0] dcspp_addr = DcsppShipAddr.objects.filter(shipping_group=shipping.shipping_group) if dcspp_addr: shipping = dcspp_addr[0] if shipping: addr = Address() addr.profile = tinla_profile addr.account = client.account_set.all()[0] addr.first_name = shipping.first_name addr.last_name = shipping.last_name addr.phone = shipping.phone_number addr.email = shipping.email addr.pincode = shipping.postal_code country, state, city = '', '', '' try: if shipping.county: country = get_country(shipping.county) if shipping.state and country: state = get_state(shipping.state.state_name, country) if shipping.city and state: city = get_city(shipping.city, state) if country: addr.country = country if state: addr.state = state if city: addr.city = city except: pass addr.save() del_info = DeliveryInfo() del_info.address = addr del_info.order = order del_info.save() order_items = atg_order.order.dcspporderitem_set.all() list_price_total, shipping_charges = Decimal(0), Decimal(0) for atg_oi in order_items: oi = OrderItem() ci = atg_oi.commerce_items oi.order = order oi.state = get_order_state(ci.state) try: src = SellerRateChart.objects.get(sku=ci.sku.sku.sku_id, seller__client = client) oi.seller_rate_chart = src except SellerRateChart.DoesNotExist: pass oi.list_price = ci.amount_info.list_price list_price_total += ci.amount_info.list_price oi.sale_price = ci.amount_info.sale_price del_item = FtbShipitemRel.objects.filter(relationship__commerce_item = atg_oi) if del_item: del_item = del_item[0] oi.shipping_charges = del_item.shipping_cost shipping_charges += del_item.shipping_cost "shipping found for ", atg_order.order oi.qty = ci.quantity oi.save() # amount info order_discount_total = Decimal(str(atg_order.ord_misc_field1)) sale_price_total = atg_order.order.price_info.raw_subtotal total_order_shipping = atg_order.order.price_info.shipping + shipping_charges order.shipping_charges = total_order_shipping order.list_price_total = list_price_total order.total = sale_price_total order.payable_amount = sale_price_total + total_order_shipping - order_discount_total order.save() print order.id print order.reference_order_id # map entry map_entry = AtgOrderMigrationMap(order = order, atg_order = atg_order.order.order) map_entry.save()
def process_order(request): context = RequestContext(request) user = request.user increment_clicks(user) profile = get_associated_profile(user) cart = get_cart(profile) items_to_package = [] total_price = 0 for item in CartItem.objects.all(): if item.cart == cart: items_to_package.append(item.item) total_price = total_price + item.item.price entry_id = request.POST.get('entry_id') entry = Entry.objects.get(id=entry_id) new_order = Order(user_profile=profile, restaurant=profile.restaurant, total = total_price, entry = entry, status = 'PDG', order_success = False, order_rating = 0 ) new_order.save() order_dict = {} for item in items_to_package: if item.id in order_dict.keys(): order_dict[item.id] = order_dict[item.id] + 1 else: order_dict[item.id] = 1 order_items = [] for key in order_dict.keys(): item = Item.objects.get(id=key) quantity = order_dict[key] new_order_item = OrderItem(item=item, order=new_order, quantity=quantity) new_order_item.save() order_items.append(new_order_item) #cart.delete() #print order_dict.keys() cart_id = cart.id #print cart.id total_price_display = new_order.view_order_total_in_usd() return render_to_response("confirm.html", {'total_price_display':total_price_display, 'total_price':total_price, 'user':user, 'profile':profile, 'order_items':order_items, 'cart_id':cart_id }, context)
def new_order(atg_order, tinla_profile, client): # Ensure that there is no profile with this atg login map_entry = None try: map_entry = AtgOrderMigrationMap.objects.select_related('order').get( atg_order=atg_order.order.order) log.info("Already migrated %s, skipping new_order" % atg_order.order.order) return map_entry.order except AtgOrderMigrationMap.DoesNotExist: pass # create new order order = Order() order.user = tinla_profile order.state = get_order_state(atg_order.order.order_state) order.timestamp = atg_order.order.atg_creation_date order.payment_realized_on = atg_order.order.atg_submitted_date order.modified_on = atg_order.order.last_modified_date order.reference_order_id = atg_order.order.order order.client = client order.save() # delivery info shipping = DcsppShipGroup.objects.filter(order_ref=atg_order.order.order) if shipping: shipping = shipping[0] dcspp_addr = DcsppShipAddr.objects.filter( shipping_group=shipping.shipping_group) if dcspp_addr: shipping = dcspp_addr[0] if shipping: addr = Address() addr.profile = tinla_profile addr.account = client.account_set.all()[0] addr.first_name = shipping.first_name addr.last_name = shipping.last_name addr.phone = shipping.phone_number addr.email = shipping.email addr.pincode = shipping.postal_code country, state, city = '', '', '' try: if shipping.county: country = get_country(shipping.county) if shipping.state and country: state = get_state(shipping.state.state_name, country) if shipping.city and state: city = get_city(shipping.city, state) if country: addr.country = country if state: addr.state = state if city: addr.city = city except: pass addr.save() del_info = DeliveryInfo() del_info.address = addr del_info.order = order del_info.save() order_items = atg_order.order.dcspporderitem_set.all() list_price_total, shipping_charges = Decimal(0), Decimal(0) for atg_oi in order_items: oi = OrderItem() ci = atg_oi.commerce_items oi.order = order oi.state = get_order_state(ci.state) try: src = SellerRateChart.objects.get(sku=ci.sku.sku.sku_id, seller__client=client) oi.seller_rate_chart = src except SellerRateChart.DoesNotExist: pass oi.list_price = ci.amount_info.list_price list_price_total += ci.amount_info.list_price oi.sale_price = ci.amount_info.sale_price del_item = FtbShipitemRel.objects.filter( relationship__commerce_item=atg_oi) if del_item: del_item = del_item[0] oi.shipping_charges = del_item.shipping_cost shipping_charges += del_item.shipping_cost "shipping found for ", atg_order.order oi.qty = ci.quantity oi.save() # amount info order_discount_total = Decimal(str(atg_order.ord_misc_field1)) sale_price_total = atg_order.order.price_info.raw_subtotal total_order_shipping = atg_order.order.price_info.shipping + shipping_charges order.shipping_charges = total_order_shipping order.list_price_total = list_price_total order.total = sale_price_total order.payable_amount = sale_price_total + total_order_shipping - order_discount_total order.save() print order.id print order.reference_order_id # map entry map_entry = AtgOrderMigrationMap(order=order, atg_order=atg_order.order.order) map_entry.save()
def create_order_from_cart(request, pay_method): #create a record in the Order table containing the cart_id #check that this cart_id isn't already in the table ok_to_create = True new_id = 0 cart_id = cart_extras.get_cart_id(request) cart_order_record = Order.objects.filter(cart_ID=cart_id) if (cart_order_record.exists()): #this should not be the norm so if this cart is already entered on an existing order this must mean that #the customer is in the same session and is creating ANOTHER order. #check if the existing order has any payment_status (if it has ANY payment status, then need to stop order) the_payment_status = get_cart_id_payment_status(cart_id) if not the_payment_status or the_payment_status == "CANCELLED": #the original order does not have a payment status or is has a cancelled status so this new one CAN be recreated #deleting the order will also delete the products associated with the order print( "this session id is already in the Order Table but in an unsuccessful Order" ) cart_order_record.delete() print("it is now deleted") else: #the original order has a payment status so it should not be over-written #UNLESS the user is using a DIFFERENT Payment Method (they may have changed their mind and selected the other option) #it CAN be overwritten if the payment type is different print( "this session id is already in the Order Table and has a payment status" ) the_payment_method = get_cart_id_payment_method(cart_id) if the_payment_method == pay_method: print("Do not over write it") ok_to_create = False else: print( "this session id is already in the Order Table but in an unsuccessful Order AND a different payment method" ) cart_order_record.delete() print("it is now deleted") if ok_to_create: order_complete = False cart_ID = cart_id order_discount_code = cart_extras.get_cart_discount_code(request) payment_method = pay_method shipping_name = cart_extras.get_shipping_address_name(request) shipping_address_line1 = cart_extras.get_shipping_address_line1( request) shipping_address_line2 = cart_extras.get_shipping_address_line2( request) shipping_address_city = cart_extras.get_shipping_address_city(request) shipping_address_state = cart_extras.get_shipping_address_state( request) shipping_address_postal_code = cart_extras.get_shipping_address_postal_code( request) shipping_address_country = cart_extras.get_shipping_address_country( request) customer_notes = cart_extras.get_customer_notes(request) shipping_type = cart_extras.get_postage_type(request) shipping_total = cart_extras.get_postage_cost(request) shipping_type_from_cart = shipping_extras.get_postage_type_display( shipping_type) shipping_total_from_cart = shipping_total discount_total = cart_extras.get_cart_discount_amount(request) order_discount_code = cart_extras.get_cart_discount_code(request) sub_total_from_cart = cart_extras.get_sub_total(request) final_total_from_cart = cart_extras.get_final_total(request) if pay_method == "FREE": payment_status = "FREE" else: payment_status = "PENDING" new_order = Order( cart_ID=cart_id, order_complete=order_complete, payment_method=payment_method, payment_status=payment_status, shipping_name=shipping_name, shipping_address_line1=shipping_address_line1, shipping_address_line2=shipping_address_line2, shipping_address_city=shipping_address_city, shipping_address_state=shipping_address_state, shipping_address_postal_code=shipping_address_postal_code, shipping_address_country=shipping_address_country, customer_notes=customer_notes, shipping_type=shipping_type, shipping_total=shipping_total, shipping_type_from_cart=shipping_type_from_cart, shipping_total_from_cart=shipping_total_from_cart, discount_total=discount_total, order_discount_code=order_discount_code, sub_total_from_cart=sub_total_from_cart, final_total_from_cart=final_total_from_cart) new_order.save() new_id = new_order.pk #print("The new ID is ") #print(new_id) if new_id: the_cart_items = cart_extras.get_cart_items_object(request) for item in the_cart_items: product_id = cart_extras.get_product_id(request, item) the_product = product_extras.get_product(product_id) product_quantity = cart_extras.get_product_quantity( request, item) product_price_for_order = product_extras.get_product_price( product_id) new_item = OrderItem( order_ID=new_order, product_ID=the_product, product_quantity=product_quantity, product_price_for_order=product_price_for_order) new_item.save() #check if this new_id (order_id) needs to be recorded in discount table #need to be only if a single-use discount code was used (so that it can't be reused) if order_discount_code: usage_frequency = discount_extras.get_usage_frequency( order_discount_code) #print(usage_frequency) if usage_frequency == "SINGLE_USE": discount_extras.add_single_use_order_id( order_discount_code, get_order(new_id)) return new_id
def order_create(request): config = OrderConfig.objects.get(id=1) access_token = Clover.objects.filter().latest('achieved').access_token clover = CloverApiClient(api_url=settings.CLOVER_API_URL, merchant_id=settings.CLOVER_MERCHANT_ID, api_key=access_token) cart = Cart(request) order_items_m = [] if request.method == 'POST': order_form = OrderForm(request.POST) card_form = CloverPayForm(request.POST) if order_form.is_valid() and card_form.is_valid(): order = order_form.save() # Create OrderItems for FF internal DB for item in cart: order_item = OrderItem(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) order_item.save() order_items_m.append(order_item.product.name) # Send to Clover PoS, total is converted to cents clover_order = clover.order_service.create_order({ 'state': 'open', 'title': str(order.id), 'total': (float(order.get_total_cost()) * 100), 'currency': 'USD', }) # Create Clover LineItem(s) for item in cart: if item['quantity'] > 1: for el in range(item['quantity']): clover.order_service.create_line_item( order_id=clover_order['id'], line_item={ 'name': str(item['product']), 'price': float(item['price'] * 100), }) else: clover.order_service.create_line_item( order_id=clover_order['id'], line_item={ 'name': str(item['product']), 'price': float(item['price'] * 100), }) # Clover CC Pay clover_pay = CloverPay(api_url=settings.CLOVER_API_URL, merchant_id=settings.CLOVER_MERCHANT_ID, api_key=access_token) card = card_form.cleaned_data secrets = clover_pay.get_secrets() card_number = card['card_number'].encode() # card_number = b'4242424242424242' modulus = int(secrets['modulus']) exponent = int(secrets['exponent']) prefix = secrets['prefix'].encode() RSAkey = RSA.construct((modulus, exponent)) cipher = PKCS1_OAEP.new(RSAkey) encrypted = cipher.encrypt(prefix + card_number) card_encrypted = b64encode(encrypted).decode() payload = { "orderId": clover_order['id'], "zip": card['zip_code'], "expMonth": card['exp_month'], "cvv": card['cvv'], "amount": (float(order.get_total_cost()) * 100), "currency": "usd", "last4": card['card_number'][-4:], "expYear": card['exp_year'], "first6": card['card_number'][0:6], "cardEncrypted": card_encrypted } payment = clover_pay.send_payment(payload) if payment['result'] == 'APPROVED': order.paid = True order.save() order.send_client_order_confirm_email(order_items_m, clover_order, payment) order.send_admin_order_confirm_emails(order_items_m, clover_order, payment) order.send_admin_order_confirm_sms(clover_order) cart.clear() return render(request, 'orders/order/created.html', {'config': config}) else: return render(request, 'orders/order/pay-error.html', {'config': config}) else: return render(request, 'orders/order/order-error.html', {'config': config}) else: order_form = OrderForm() card_form = CloverPayForm() return render( request, 'orders/order/create.html', { 'config': config, 'order_form': order_form, 'card_form': card_form, 'cart': cart, })
def create_sample_data(): now = datetime.now() this_m_first = datetime(now.year, now.month, 1) this_m_first = timezone.make_aware(this_m_first, timezone.get_current_timezone()) last_m_mid = this_m_first - timedelta(days=16) last_m_first = datetime(last_m_mid.year, last_m_mid.month, 1) create_test_users() cust = Customer(first_name="TestCust1", last_name="L") cust.save() cust2 = Customer(first_name="TestCust2", last_name="L") cust2.save() cust3 = Customer(first_name="TestCust3", last_name="L") cust3.save() store1 = Store(name="Sacramento") store2 = Store(name="Roseville") store1.save() store2.save() users = User.objects.all() user1 = users.get(username="******") user2 = users.get(username="******") user3 = users.get(username="******") user4 = users.get(username="******") o = Order() o.number = 'SO-01-0001' o.order_date = this_m_first o.customer = cust o.status = 'N' o.deposit_balance = 100.00 o.subtotal_after_discount = 3500.00 o.store = store1 o.save() commission = Commission(associate=user1, order=o) commission.save() item1 = OrderItem(status='S', description="Item1", order=o) item1.save() o = Order() o.number = 'SO-01-0003' o.order_date = last_m_mid o.customer = cust2 o.status = 'Q' o.deposit_balance = 500 o.subtotal_after_discount = 7000.00 o.store = store1 o.save() commission = Commission(associate=user3, order=o) commission.save() commission = Commission(associate=user4, order=o) commission.save() item1 = OrderItem(status='P', description="Item2", order=o) item1.save() item2 = OrderItem(status='S', description="Item3", order=o) item2.save() o = Order() o.number = 'SO-03-0001' o.order_date = last_m_first o.customer = cust o.status = 'C' o.deposit_balance = 5000 o.subtotal_after_discount = 5000.00 o.store = store2 o.save() commission = Commission(associate=user3, order=o) commission.save() commission = Commission(associate=user4, order=o) commission.save() item1 = OrderItem(status='P', description="Item4", order=o) item1.save() item2 = OrderItem(status='S', description="Item6", order=o) item2.save() item2 = OrderItem(status='O', description="Item7", order=o) item2.save()