def get(self, request, chat_id, format=None): customer = get_object_or_404(BeerBearCustomer, pk=request.user.pk) chatroom = get_object_or_404(Chat, pk=chat_id) if chatroom.is_active == False: return Response(status=status.HTTP_400_BAD_REQUEST) else: # getCouponlist ( Chat -> Coupon) coupon_list = Chat.getCouponlist(chatroom) for coupon in coupon_list: if coupon.customer == customer: my_coupon = coupon else: buddy_coupon = coupon if my_coupon == None: return Response(status=status.HTTP_404_NOT_FOUND) else: # checkActive ( Coupon self) check = Coupon.checkActive(my_coupon) if check: if buddy_coupon.count == 1: # activateCoupon ( Coupon self ) Coupon.activateCoupon(my_coupon) Coupon.activateCoupon(buddy_coupon) # deactiveChat ( Chat self ) Chat.deactiveChat(chatroom) return Response(status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST)
def setUpClass(cls): super(BaseModelTestCase, cls).setUpClass() coupon = Coupon(code='sale', valid_from=datetime.now(), discount=10, active=True, valid_to=datetime.now() + timedelta(days=10)) coupon.save() cls.order_sale = Order(first_name='Имя', last_name='Фамилия', email='*****@*****.**', address='Улица, дом 1', postal_code='123', city='Город', discount=10, coupon=coupon) cls.order_sale.save() cls.order = Order(first_name='Имя', last_name='Фамилия', email='*****@*****.**', address='Улица, дом 1', postal_code='123', city='Город') cls.order.save() category = Category(name='category_name', slug='category_slug') category.save() product_1 = Product(category=category, name='product_1', slug='slug_1', price=5, stock=1) product_2 = Product(category=category, name='product_2', slug='slug_2', price=5, stock=1) product_1.save() product_2.save() cls.order_item_1 = OrderItem( order=cls.order, product=product_1, price=product_1.price, ) cls.order_item_2 = OrderItem(order=cls.order, product=product_2, price=product_2.price, quantity=5) cls.order_item_1.save() cls.order_item_2.save() cls.order_sale_item = OrderItem(order=cls.order_sale, product=product_2, price=product_2.price, quantity=5) cls.order_sale_item.save()
def cart(request): cartProducts = request.session.get('products') orderItems = get_order_items(cartProducts) # if there is a promo code, update the cart with order items coupon = Coupon() orderItems, couponMessage = coupon.apply_coupon(orderItems, request) cart_total = get_order_items_cart_total(orderItems) context = {} context['orderItems'] = orderItems context['cart_total'] = cart_total context['couponMessage'] = couponMessage # context = {'order': order} context['categories'] = Category.objects.all()[:50] return render(request, 'cart.html', context)
def test_generate_code_segmented(self): num_segments = CODE_LENGTH // SEGMENT_LENGTH # full ones num_rest = CODE_LENGTH - num_segments * SEGMENT_LENGTH self.assertIsNotNone( re.match( "^([{chars}]{{{sl}}}{sep}){{{ns}}}[{chars}]{{{nr}}}$".format( chars=CODE_CHARS, sep=SEGMENT_SEPARATOR, sl=SEGMENT_LENGTH, ns=num_segments, nr=num_rest), Coupon.generate_code("", True)))
def test_generate_code_segmented(self): num_segments = CODE_LENGTH // SEGMENT_LENGTH # full ones num_rest = CODE_LENGTH - num_segments * SEGMENT_LENGTH self.assertIsNotNone( re.match( "^([{chars}]{{{sl}}}{sep}){{{ns}}}[{chars}]{{{nr}}}$".format( chars=CODE_CHARS, sep=SEGMENT_SEPARATOR, sl=SEGMENT_LENGTH, ns=num_segments, nr=num_rest), Coupon.generate_code("", True) ) )
def get(self, request, coupon_id, format=None): coupon = get_object_or_404(Coupon, pk=coupon_id) # generate_qrcode Coupon.generate_qrcode(coupon) serializer = CouponSerializer(coupon) return Response(data=serializer.data, status=status.HTTP_200_OK)
def test_generate_code(self): self.assertIsNotNone(re.match("^[%s]{%d}" % (CODE_CHARS, CODE_LENGTH,), Coupon.generate_code()))
def test_save(self): coupon = Coupon(type='monetary', value=100) coupon.save() self.assertTrue(coupon.pk)
def checkout(request): context = {} cartProducts = request.session.get('products') orderItems = get_order_items(cartProducts) coupon = Coupon() orderItems, couponMessage = coupon.apply_coupon(orderItems, request) cart_total = get_order_items_cart_total(orderItems) context['categories'] = Category.objects.all()[:50] context['orderItems'] = orderItems context['cart_total'] = cart_total context['couponMessage'] = couponMessage ### GET REQUEST ############# if request.method == 'GET': ## FORMS context['CustomerSignUpForm'] = CustomerSignUpForm() # context['ProductCollectionForm'] = ProductCollectionForm() context['PaymentStoreSelectForm'] = PaymentStoreSelectForm() context['ShippingAddressSelectForm'] = ShippingAddressSelectForm() context[ 'CustomerFaceAddressCreateForm'] = CustomerFaceAddressCreateForm() context['CheckoutPaymentMethodsForm'] = CheckoutPaymentMethodsForm() ### POST REQUEST ############# if request.method == 'POST': passCriteria = False # productCollectionForm = ProductCollectionForm(request.POST) shippingAddressSelectForm = ShippingAddressSelectForm(request.POST) customerSignUpForm = CustomerSignUpForm(request.POST) customerFaceAddressCreateForm = CustomerFaceAddressCreateForm( request.POST) checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm(request.POST) paymentStoreSelectForm = PaymentStoreSelectForm(request.POST) paymentStoreId = None product_collection_choice = request.POST.get( 'product_collection_choice') ## FOR LOGIN USERS if request.user.is_authenticated: user = request.user # inserting the selected address option into the form, as they are loaded dynamically on the frontend addressSelectedID = request.POST.get('addressSelected') shippingAddressSelectForm.fields['addressSelected'].choices = [ (addressSelectedID, addressSelectedID) ] # PRODUCT COLLECTION VIA SHIPPING: if product_collection_choice == 'shipping': # user selects an existing address if shippingAddressSelectForm.is_valid( ) and shippingAddressSelectForm.cleaned_data[ 'addressSelected'] != '-1': shippingAddress = Address.objects.get( pk=shippingAddressSelectForm. cleaned_data['addressSelected']) passCriteria = True # User selects a new address elif customerFaceAddressCreateForm.is_valid(): shippingAddress = customerFaceAddressCreateForm.save( commit=False) passCriteria = True # PRODUCT COLLECTION IN STORE: elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid( ): paymentStoreId = paymentStoreSelectForm.cleaned_data.get( 'paymentStore') passCriteria = True ## IF NOT LOGGEDIN: CHECK IF ADDRESS FORM OR COLLECTION STORE IS CORRECT elif customerSignUpForm.is_valid(): if product_collection_choice == 'shipping' and customerFaceAddressCreateForm.is_valid( ): shippingAddress = customerFaceAddressCreateForm.save( commit=False) passCriteria = True elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid( ): paymentStoreId = paymentStoreSelectForm.cleaned_data.get( 'paymentStore') passCriteria = True ## IF NOT LOGGEDIN: CHECK IF PAYMENT STORE IS SELECTED if passCriteria: if checkoutPaymentMethodsForm.is_valid(): # create new user if the user is not authenticated if not request.user.is_authenticated: user = customerSignUpForm.save(request) ## Reuse Indodana order if exists, else create new order, order_created = Order.objects.get_or_create( customer=user.customer, paymentOption='Indodana', status='Awaiting Indodana payment', defaults={ 'customer': user.customer, 'orderChannel': 'Website', 'coupon': coupon.coupon, }) # remove all order items from the order in case the customer has manipulated the cart if not order_created: order.orderitem_set.clear() # Saving the address or payment store if paymentStoreId: order.store = Store.objects.get(id=paymentStoreId) else: shippingAddress.save() order.shippingAddress = shippingAddress user.customer.address_set.add(shippingAddress) user.save() order.paymentOption = checkoutPaymentMethodsForm.cleaned_data.get( 'payment_method') if checkoutPaymentMethodsForm.cleaned_data.get( 'installment_period'): order.installmentPeriod = checkoutPaymentMethodsForm.cleaned_data.get( 'installment_period') if checkoutPaymentMethodsForm.cleaned_data.get( 'payment_store'): order.installmentPeriod = checkoutPaymentMethodsForm.cleaned_data.get( 'payment_store') # status setting: if order.paymentOption == 'Bank Transfer': order.status = 'Awaiting Bank Transfer' elif order.paymentOption == 'Payment in the store': order.status = 'Awaiting payment in store' elif order.paymentOption == 'Payment on delivery': order.status = 'Awaiting payment on delivery' elif order.paymentOption == 'Indodana': order.status = 'Awaiting Indodana payment' else: order.status = 'Unknown' order.save() for orderItem in orderItems: orderItem.save() order.orderitem_set.add(orderItem) ### REGULAR ORDER PROCESSING ### if not order.paymentOption == 'Indodana': for orderItem in orderItems: productHistory = ProductHistory() productHistory.adjust_stock_order( orderItem, 'Website Purchase') # updating the coupon code stats if coupon.coupon: coupon.coupon.amountUsed += 1 coupon.coupon.customersUsedCoupons.add(user) coupon.coupon.save() # delete the products from the cart if request.session.get('products'): del request.session['products'] # todo delete coupon code from session # login the customer if the customer is not logged in already if not request.user.is_authenticated: login( request, user, backend='django.contrib.auth.backends.ModelBackend' ) send_order_emails(order) return render(request, 'order-completed.html', context) ## INDODANA REQUEST SENDING ## else: indodana = Indodana(order) indodana.send_transaction_request() #! save transaction code!! print('RESP DATA', indodana.resp_data) # todo delete this line if indodana.is_valid(): return redirect(indodana.redirect_url) else: context[ 'indodata_error_message'] = indodana.error_message context['ShippingAddressSelectForm'] = shippingAddressSelectForm context['CustomerSignUpForm'] = customerSignUpForm context[ 'CustomerFaceAddressCreateForm'] = customerFaceAddressCreateForm context['CheckoutPaymentMethodsForm'] = checkoutPaymentMethodsForm return render(request, 'checkout.html', context)
def order_create_cart_view(request, pk): """view for staff to create orders for customers""" customer_user = User.objects.get(pk=pk) order, orderIsCreated = Order.objects.get_or_create( customer=customer_user.customer, status='Pending') orderItems = order.orderitem_set.all() coupon = Coupon() orderItems, couponMessage = coupon.apply_coupon( orderItems, request, customer_user=customer_user) cart_total = get_order_items_cart_total(orderItems) if request.method == 'GET': shippingAddressSelectForm = ShippingAddressSelectForm() checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm() staffOrderCreateForm = StaffOrderCreateForm() del checkoutPaymentMethodsForm.fields['payment_method'].choices[ -1] # deleting indodana as option in the list checkoutPaymentMethodsForm.fields[ 'installment_period'].widget = forms.HiddenInput( ) # disabling installment period, as it can be used only directly by the customer login paymentStoreSelectForm = PaymentStoreSelectForm() customerFaceAddressCreateForm = CustomerFaceAddressCreateForm() if request.method == 'POST': passCriteria = False # inserting the selected address option into the form, as they are loaded dynamically on the frontend shippingAddressSelectForm = ShippingAddressSelectForm(request.POST) customerFaceAddressCreateForm = CustomerFaceAddressCreateForm( request.POST) checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm(request.POST) paymentStoreSelectForm = PaymentStoreSelectForm(request.POST) paymentStoreId = None product_collection_choice = request.POST.get( 'product_collection_choice') staffOrderCreateForm = StaffOrderCreateForm(request.POST) ## PRODUCT COLLECTION VIA SHIPPING: if product_collection_choice == 'shipping': addressSelectedID = request.POST.get('addressSelected') shippingAddressSelectForm.fields['addressSelected'].choices = [ (addressSelectedID, addressSelectedID) ] # SECTION OF EXISTING ADDRESS if shippingAddressSelectForm.is_valid( ) and shippingAddressSelectForm.cleaned_data[ 'addressSelected'] != '-1': shippingAddress = Address.objects.get( pk=shippingAddressSelectForm. cleaned_data['addressSelected']) passCriteria = True # SELECTION TO ENDER A NEW ADDRESS elif customerFaceAddressCreateForm.is_valid(): shippingAddress = customerFaceAddressCreateForm.save( commit=False) passCriteria = True ## PRODUCT COLLECTION IN STORE: elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid( ): paymentStoreId = paymentStoreSelectForm.cleaned_data.get( 'paymentStore') passCriteria = True if passCriteria and \ checkoutPaymentMethodsForm.is_valid() and \ staffOrderCreateForm.is_valid(): # Saving the address or payment store if paymentStoreId: order.store = Store.objects.get(id=paymentStoreId) else: shippingAddress.save() customer_user.customer.address_set.add(shippingAddress) order.shippingAddress = shippingAddress # setting payment option order.paymentOption = checkoutPaymentMethodsForm.cleaned_data.get( 'payment_method') # status setting: if order.paymentOption == 'Bank Transfer': order.status = 'Awaiting Bank Transfer' elif order.paymentOption == 'Payment in the store': order.status = 'Awaiting payment in store' elif order.paymentOption == 'Payment on delivery': order.status = 'Awaiting payment on delivery' elif order.paymentOption == 'Indodana': order.status = 'Awaiting Indodana payment' else: order.status = 'Unknown' order.orderChannel = staffOrderCreateForm.cleaned_data.get( 'orderChannel') order.shippingCost = staffOrderCreateForm.cleaned_data.get( 'shippingCost') order.notes = staffOrderCreateForm.cleaned_data.get('notes') order.staff = request.user customer_user.save() # managing stock for orderItem in orderItems: orderItem.save() productHistory = ProductHistory() productHistory.adjust_stock_order(orderItem, 'Purchase via backoffice') # processing the coupon if coupon.coupon: coupon.coupon.amountUsed += 1 coupon.coupon.customersUsedCoupons.add(customer_user) coupon.coupon.save() order.coupon = coupon.coupon order.save() return redirect('order-details', pk=order.id) context = {} context['user'] = customer_user context['attributes'] = Attribute.objects.all() context['categories'] = Category.objects.all() context['ShippingAddressSelectForm'] = shippingAddressSelectForm context['CheckoutPaymentMethodsForm'] = checkoutPaymentMethodsForm context['PaymentStoreSelectForm'] = paymentStoreSelectForm context['StaffOrderCreateForm'] = staffOrderCreateForm context['CustomerFaceAddressCreateForm'] = customerFaceAddressCreateForm context['orderItems'] = orderItems context['couponMessage'] = couponMessage return render(request, 'order-create-cart.html', context)