def handle(self, *args, **kwargs): for event_id in kwargs['event_ids']: event = Event.objects.get(pk=event_id) print(f'Process event {event.name}') qtickets = QTicketsInfo.get_order_list(event.external_id) for item in qtickets: Order.add_or_update(item)
def insert_cart(request, product_id): context = {} nItems = 0 if 'order_id' in request.session: order = Order.objects.get(id=request.session['order_id']) orderItem = OrderItem() product = Product.objects.get(id=product_id) orderItem.order = order orderItem.product = product orderItem.value = product.value orderItem.save() # context['order'] = order # context['orderItems'] = OrderItem.objects.filter(order__id=order.id) request.session['howItems'] = \ int(request.session['howItems']) + 1 else: order = Order() order.user = User.objects.get(id=request.user.id) order.save() orderItem = OrderItem() product = Product.objects.get(id=product_id) orderItem.order = order orderItem.product = product orderItem.value = product.value orderItem.save() # context['order'] = order # context['orderItems'] = OrderItem.objects.filter(order__id=order.id) request.session['order_id'] = order.id request.session['howItems'] = 1 return HttpResponseRedirect(resolve_url("/"))
def payment_completed(request): payload = request.body signature_header = request.META['HTTP_STRIPE_SIGNATURE'] # To store the data that stripe is sending back to server event = None endpoint_secret = settings.STRIPE_ENDPOINT_SECRET try: event = stripe.Webhook.construct_event(payload, signature_header, endpoint_secret) except ValueError as e: return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # means the data is not from Stripe return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': plants = Plant.objects.all() hours = 8 # to convert the date session in local SGT hours_added = datetime.timedelta(hours=hours) session = event['data']['object'] session_created = datetime.datetime.fromtimestamp( event['created']) + hours_added all_plant_ids_jsonstr = session['metadata']['all_plant_ids'] all_plant_ids = json.loads(all_plant_ids_jsonstr) # to retrieve the order item and save them in the database for item in all_plant_ids: plant_model = get_object_or_404(Plant, pk=item['plant_id']) user_model = get_object_or_404(User, pk=item['user']) plant_model.qty = plant_model.qty - item['qty'] plant_model.save(update_fields=["qty"]) order = Order(title=plant_model.name, price=float(item['price']), datetime_ordered=session_created, plant=plant_model, order_by=user_model, qty=item['qty']) order.save() return HttpResponse(status=200)
def webhook(request): signature = hmac.new(settings.QTICKETS_SECRET.encode(), request.body, hashlib.sha1).hexdigest() if signature != request.headers.get('X-Signature'): return HttpResponseBadRequest() payload = json.loads(request.body) Order.add_or_update(payload) return HttpResponse()
def create_order(request): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED print (order.number) order.save() print (order.number) order.number = int(str(order.id) + datetime.today().strftime('%m%d%Y')) order.save() print (order.number) # create order item for each cart item if order.pk: cart_items = carts.get_cart_items(request) for ci in cart_items: oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.product.price oi.product = ci.product oi.save() carts.empty_cart(request) return order
def create_order(request, transaction_id): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.transaction_id = transaction_id order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated: order.user = request.user order.status = Order.SUBMITTED order.save() # if the order save succeeded if order.pk: cart_items = cart.get_cart_items(request) for ci in cart_items: # create order item for each cart item oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price # now using @property oi.product = ci.product oi.save() # all set, empty cart cart.empty_cart(request) # save profile info for future orders if request.user.is_authenticated: profile.set(request) # return the new order object return order
def test_Checkout_details(self): order = Order.objects.get(id=1) Order.update_total(order) Order.save(order) self.assertEqual(order.full_name, 'TestOrder') self.assertEqual(order.email, '*****@*****.**') self.assertEqual(order.town_or_city, 'Town') self.assertEqual(order.order_total, 10) # Delivery costs added self.assertEqual(order.delivery_cost, round(Decimal(5.99), 2)) self.assertEqual(order.grand_total, round(Decimal(15.99), 2))
def create_order(request, transaction_id): order = Order() checkout_form = CheckoutForm(request.POST, instance = order) order = checkout_form.save(commit = False) order.transaction_id = transaction_id order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() if order.pk: cart_items = cart.get_cart_items(request) for ci in cart_items: oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price oi.product = ci.product oi.save() cart.empty_cart(request) if request.user.is_authenticated(): from accounts import profile profile.set(request) return order
def create_order(request, transaction_id): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.transaction_id = transaction_id order.ip_address = reqest.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() # If order save succeeded if order.pk: cart_items = cart_utils.get_cart_items(request) for ci in cart_items: # Create order item for each cart item oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price oi.product = ci.product oi.save() # Now we can emty the cart cart_utils.empty_cart(request) # save profile info for future orders if request.user.is_authenticated(): from accounts import profile profile.set(request) # Return the new order object return order
def setUp(self): self.discount_1 = Discount(name="2-for-1") self.discount_1.save() self.discount_2 = Discount(name="3 or more") self.discount_2.save() self.product_1 = Product(code="TEST1", name="Test 1", price=10, discount=self.discount_1) self.product_1.save() self.product_2 = Product(code="TEST2", name="Test 2", price=10, discount=self.discount_2) self.product_2.save() self.order_1 = Order(quantity=5, product=self.product_1) self.order_2 = Order(quantity=5, product=self.product_2) self.total_1 = 30 self.total_2 = 45
def confirm_pre_order(request, order_number): """ view upgrading preorder and creating a corresponding order """ if not request.user.is_superuser: messages.error(request, 'Sorry, only store owners can see that.') return redirect(reverse('home')) pre_order = get_object_or_404(PreOrder, order_number=order_number) pp_transaction_id = request.POST['pp_transaction_id'] order = Order(user_profile=pre_order.user_profile, full_name=pre_order.full_name, email=pre_order.email, phone_number=pre_order.phone_number, country=pre_order.country, postcode=pre_order.postcode, town_or_city=pre_order.town_or_city, street_address1=pre_order.street_address1, street_address2=pre_order.street_address2, county=pre_order.county, delivery_cost=pre_order.delivery_cost, order_total=pre_order.order_total, grand_total=pre_order.grand_total, pp_transaction_id=pp_transaction_id) # save order order.save() # copy line items from preorder to order for li in pre_order.lineitems.all(): order_line_item = OrderLineItem( order=order, product=li.product, quantity=li.quantity, ) order_line_item.save() # update product reserved, sold product = li.product quantity = li.quantity product.sold = product.sold + quantity product.reserved = product.reserved - quantity product.save() # update preorder pre_order.upgraded_order = order pre_order.status = "UPG" pre_order.save() # success message messages.success(request, (f'Preorder {pre_order.order_number} upgraded.' f'New order {order.order_number} confirmed.')) return redirect(reverse('products_management'))
def test_order_shipped(self): """testing if order is marked as shipped correctly""" order = Order(full_name="test", email="test", phone_number="12", country="test", postcode="test", town_or_city="test", street_address1="test", street_address2="test", county="test", delivery_cost=10, order_total=10, grand_total=10, original_bag="test") order.save() user = User.objects.create_superuser('testuser', '*****@*****.**', '12345') user.save() self.client.login(username=user.username, password='******') delivery_info = { 'tracking_number': '12345', 'provider': 'test provider', 'expected_wait': 22, 'order': order, } response = self.client.post(f'/products/toggle_shipped/{order.id}', delivery_info) order = Order.objects.get(pk=order.id) self.assertTrue(order.shipped) # check if associated delivery was generated delivery_generated = False delivery = order.delivery.all()[0] if (delivery_info['tracking_number'] == delivery.tracking_number and delivery_info['provider'] == delivery.provider and delivery_info['expected_wait'] == delivery.expected_wait): delivery_generated = True self.assertTrue(delivery_generated) # request to unship the order response = self.client.post(f'/products/toggle_shipped/{order.id}') order = Order.objects.get(pk=order.id) self.assertFalse(order.shipped)
class OrderTests(TestCase): """ Testing order line item total calculation """ def test_subtotal_calculation(self): self.product = Product(name='test_name', price=11, description='test_description', ) self.product.save() self.order = Order( full_name="Test User", email="*****@*****.**", phone_number="12345", country="gb", postcode="e114dr", town_or_city="london", street_address1="40 test road", original_bag="", stripe_pid="", ) self.order.save() self.order_line_item = OrderLineItem( order=self.order, product=self.product, quantity=2, ) self.order_line_item.save() ''' Testing product and order is created ''' self.assertEqual(str(self.product.name), 'test_name') self.assertEqual(str(self.order.full_name), 'Test User') ''' Testing order line item ''' self.assertEqual(str(self.order_line_item.lineitem_total), '22') ''' Testing order total ''' self.assertEqual(str(self.order.order_total), '22')
def post(self, req): shipping_destination, fitting = req.POST['shipping'], req.POST['fitting'] if 'fitting' in req.POST else None order = Order() try: shipping_destination = ShippingDestination.objects.get(pk=shipping_destination) if not shipping_destination.active: messages.error(req, 'Something happen while creating your order, please try again.') return render_to_response(self.template_name, context_instance=RequestContext(req)) except ShippingDestination.DoesNotExist: messages.error(req, 'Something happen while creating your order, please try again.') return render_to_response(self.template_name, context_instance=RequestContext(req)) try: order.new_order(req.cart, shipping_destination, fitting, req.user) except Exception: messages.error(req, 'Something happen while creating your order, please try again.') return render_to_response(self.template_name, context_instance=RequestContext(req)) else: # TODO: clear the cart messages.success(req, 'Your order has been successfully created, please proceed with the payment.') return redirect('/checkout/pay/' + order.id)
def test_country_str_test(self): test_order = Order(full_name="test", phone_number="test", country="france", postcode="test", town_or_city="test", street_address1="test", street_address2="test", county="test", date="2020-01-01") self.assertEqual(str(test_order.country), "france")
def ordered(request): '''this saves your order to the data base''' if request.user.is_authenticated: payment_info = payment.objects.filter(user=request.user).first() pers_info = personal_info.objects.filter(user=request.user).first() create_order = Order(user=request.user, info=pers_info, confirmed=True, payment=payment_info) create_order.save() cart = Cart.objects.filter(user=request.user) for item in cart: product = products.objects.get(pk=item.products.id) order_product = Order_item(order_id=create_order.id, products_id=product.id, quantity=item.quantity) order_product.save() Cart.objects.filter(user_id=request.user.id).delete() context = {} return render(request, 'checkout/order_success.html', context)
def saveOrder(request, method): try: sessionCopy = {k: v for k, v in request.session.items()} currentUser = request.user.id order = Order(accountId_id=currentUser, shippingMethod=method) order.save() for item, val in sessionCopy.items(): if val == 'item': for product in Product.objects.all(): if int(product.id) == int(item): image = _removePhotos(request, product.id) sold = Sold(orderId_id=order.id, name=product.name, price=product.price, image=image) sold.save() del request.session[item] removeItem = Product.objects.get(pk=product.id) removeItem.delete() time.sleep(1) return redirect('homepage-index') except: return render(request, '404.html', manufacturerContext(request))
def create_order(request): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() # if the order save succeeded if order.pk: cart_items = cart.get_cart_items(request) for ci in cart_items: # create order item for each cart item oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.product = ci.product oi.save() # all set, empty cart cart.empty_cart(request) # save profile info for future orders if request.user.is_authenticated(): from accounts import profile profile.fill(request) # mail the managers mail_manager_subject = '{0} has been placed!'.format(order) mail_manager_message = '{0} has been placed by {1}.\n\nClick here: {2}'.format( order, order.user if order.user else 'anonymous', request.build_absolute_uri( reverse('admin:checkout_order_change', args=(order.pk, )))) mail_managers(mail_manager_subject, mail_manager_message) # mail the customer if order.email: # FIXME: someday make templates for these emails mail_customer_subject = 'Thank you for placing {0}!'.format(order.name) mail_customer_message = '{0} was placed by you. Click here for more details: {1}\n\nThank you for your order!\n\n{2}'.format( order.name, request.build_absolute_uri(order.get_absolute_url()), settings.SITE_NAME) send_mail(mail_customer_subject, mail_customer_message, settings.DEFAULT_FROM_EMAIL, [order.email]) # return the new order object return order
def create_order(request): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() order.number = int(str(order.id) + datetime.today().strftime('%m%d%Y')) order.save() # create order item for each cart item if order.pk: cart_items = carts.get_cart_items(request) for ci in cart_items: oi = OrderItem() oi.order = order oi.quantity = ci.quantity if ci.product.quantity >= ci.quantity: ci.product.quantity = ci.product.quantity - ci.quantity else: ci.product.quantity = 0 ci.product.save() oi.price = ci.product.price oi.product = ci.product oi.save() carts.empty_cart(request) # send_mail('Subject here', 'Here is the message.', '*****@*****.**', # ['*****@*****.**'], fail_silently=False) items = OrderItem.objects.filter(order = order) plaintext = get_template('email.txt') htmly = get_template('email.html') d = Context({ 'order': order, 'items': items}) subject, from_email, to = 'Ваш заказ', '*****@*****.**', [order.email] text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(html_content, "text/html") msg.send() print('sent!') return order
def test_total_contributions(self): user = User.objects.create_user(username='******', password='******') feature = Feature(title="Test Post", author=user, content="Test Content") feature.save() order = Order(full_name = "Patrick Doherty", phone_number = "02871774646", country = "Ireland", postcode = "BT829DE", town_or_city = "Strabane", street_address1 = "5 Lasts Lane", street_address2 = "Urney Road", county = "Tyrone", date = timezone.now()) order.save() contribution = OrderLineItem(order=order, feature=feature, user=user, contribution =50) contribution.save() page = self.client.get("/features/{0}/{1}/".format(feature.id, feature.slug)) self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, "features/feature_detail.html") self.assertEqual(page.context["total_contributions"], 50) self.assertContains(page, 'Test Content') self.assertEqual(str(order), "{0}-{1}-{2}".format(order.id, order.date, order.full_name)) self.assertEqual(str(contribution), "{0}-{1}-{2}".format(contribution.contribution, feature.title, user.username))
def post(self, req): shipping_destination, fitting = req.POST[ 'shipping'], req.POST['fitting'] if 'fitting' in req.POST else None order = Order() try: shipping_destination = ShippingDestination.objects.get( pk=shipping_destination) if not shipping_destination.active: messages.error( req, 'Something happen while creating your order, please try again.' ) return render_to_response(self.template_name, context_instance=RequestContext(req)) except ShippingDestination.DoesNotExist: messages.error( req, 'Something happen while creating your order, please try again.' ) return render_to_response(self.template_name, context_instance=RequestContext(req)) try: order.new_order(req.cart, shipping_destination, fitting, req.user) except Exception: messages.error( req, 'Something happen while creating your order, please try again.' ) return render_to_response(self.template_name, context_instance=RequestContext(req)) else: # TODO: clear the cart messages.success( req, 'Your order has been successfully created, please proceed with the payment.' ) return redirect('/checkout/pay/' + order.id)
def create_order(request, transaction_id): """ if the POST to the payment gateway successfully billed the customer, create a new order containing each CartItem instance, save the order with the transaction ID from the gateway, and empty the shopping cart """ order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.transaction_id = transaction_id order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() if order.pk: """ if the order save succeeded """ cart_items = carts.get_cart_items(request) for ci in cart_items: """ create order item for each cart item """ oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price # now using @property oi.product = ci.product oi.save() # all set, clear the cart carts.empty_cart(request) # save profile info for future orders if request.user.is_authenticated(): from accounts import profile profile.set(request) return order
def index(request): # search for order that had status active order = Order.objects.filter(user__id=request.user.id).\ filter(status_order='A').first() context = {} if order: order.value = Order.get_total(order.id) order.save() context['order'] = order context['orderItems'] = OrderItem.objects.filter(order__id=order.id) context['total'] = order.value else: messages.warning(request, 'Você não tem nenhum pedido ativo') return render(request, 'dashboard_client/index.html', context)
def test_show_correct_orders(self): """testing if orders shown are correctly associated to profile""" user = User.objects.create(username='******') user.set_password('12345') user.save() userprofile = user.userprofile logged_in = self.client.login(username='******', password='******') order = Order( user_profile=userprofile, full_name='test', email="test", phone_number="1", country="test", town_or_city="test", street_address1="test", delivery_cost=1, order_total=1, grand_total=1 ) order.save() order2 = Order(user_profile=userprofile, full_name='test', email="test", phone_number="1", country="test", town_or_city="test", street_address1="test", delivery_cost=1, order_total=1, grand_total=1 ) order2.save() user_orders = user.userprofile.orders.all() response = self.client.get('/profiles/') self.assertEqual(response.status_code, 200) context_orders = response.context['orders'] set_context_orders = set(context_orders) set_user_orders = set(user_orders) self.assertEqual(set_context_orders, set_user_orders)
def create_order(request, transaction_id): """ if the POST to the payment gateway successfully billed the customer, create a new order containing each CartItem instance, save the order with the transaction ID from the gateway, and empty the shopping cart """ order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.transaction_id = transaction_id order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() if order.pk: """ if the order save succeeded """ cart_items = cart.get_cart_items(request) for ci in cart_items: """ create order item for each cart item """ oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price # now using @property oi.product = ci.product oi.save() # all set, clear the cart cart.empty_cart(request) # save profile info for future orders if request.user.is_authenticated(): from ecomstore.accounts import profile profile.set(request) return order
def test_place_order(self): Order.username = User(username='******') order = Order(full_name='Tom Riddle', phone_number='07777888888', country='Wizardland', postcode='H0GWAR7', town_or_city='Wizardtown', street_address1='Hogwarts', street_address2='Castle', county='Wizardcounty', username='******') self.assertEqual(order.full_name, 'Tom Riddle') self.assertEqual(order.phone_number, '07777888888') self.assertEqual(order.country, 'Wizardland') self.assertEqual(order.postcode, 'H0GWAR7') self.assertEqual(order.town_or_city, 'Wizardtown') self.assertEqual(order.street_address1, 'Hogwarts') self.assertEqual(order.street_address2, 'Castle') self.assertEqual(order.county, 'Wizardcounty') self.assertEqual(order.username, 'TomRiddle')
def send_order(request, order_id): order = Order.objects.get(id=order_id) items = OrderItem.objects.filter(order=order_id) order.value = Order.get_total(order.id) order.sended = True order.status_order = 'I' # dont appears in dash board as not sended money = Utils.convertStringForNumber(request.GET['money']) if (money): order.money = money else: messages.warning(request, 'Por favor digite um calor válido para Dinheiro') return HttpResponseRedirect(reverse('dashboard_client:index')) order.save() del request.session['order_id'] del request.session['howItems'] return render(request, 'dashboard_client/sended.html')
def create_order(request): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.ip_address = request.META.get('REMOTE_ADDR') order.user = None if request.user.is_authenticated(): order.user = request.user order.status = Order.SUBMITTED order.save() # if the order save succeeded if order.pk: cart_items = cart.get_cart_items(request) for ci in cart_items: # create order item for each cart item oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.product = ci.product oi.save() # all set, empty cart cart.empty_cart(request) # save profile info for future orders if request.user.is_authenticated(): from accounts import profile profile.fill(request) # mail the managers mail_manager_subject = '{0} has been placed!'.format(order) mail_manager_message = '{0} has been placed by {1}.\n\nClick here: {2}'.format(order, order.user if order.user else 'anonymous', request.build_absolute_uri(reverse('admin:checkout_order_change', args=(order.pk,)))) mail_managers(mail_manager_subject, mail_manager_message) # mail the customer if order.email: # FIXME: someday make templates for these emails mail_customer_subject = 'Thank you for placing {0}!'.format(order.name) mail_customer_message = '{0} was placed by you. Click here for more details: {1}\n\nThank you for your order!\n\n{2}'.format(order.name, request.build_absolute_uri(order.get_absolute_url()), settings.SITE_NAME) send_mail(mail_customer_subject, mail_customer_message, settings.DEFAULT_FROM_EMAIL, [order.email]) # return the new order object return order
def get_or_set_order_session(request): order_id = request.session.get('order_id', None) if order_id is None: order = Order() order.save() request.session['order_id'] = order.id else: try: order = Order.objects.get(id=order_id, ordered=False) except Order.DoesNotExist: order = Order() order.save() request.session['order_id'] = order.id if request.user.is_authenticated and order.user is None: order.user = request.user order.save() return order
def checkout(request): if request.method == 'GET': # request.session['braintree_client_token'] = braintree.ClientToken.generate() stripe_customer = stripe.Customer.retrieve( request.user.user.stripe_customer_id) payment_info = stripe_customer.sources.retrieve( stripe_customer.default_source) cart = request.session.get('cart', {}) new_cart = cart.copy() item_list = [] sold_item_list = [] total_price = 0 total_shipping = 0 for id in cart: try: item = Item.objects.get(pk=id) if item.sold == True: sold_item_list.append(item) del new_cart[id] else: item_list.append(item) total_price = total_price + item.price total_shipping = total_shipping + item.shipping_price except: pass final_total = total_shipping + total_price if sold_item_list: request.session['cart'] = new_cart return render( request, 'checkout/checkout.html', { 'sold_item_list': sold_item_list, 'items': item_list, 'total': final_total, 'sub_total': total_price, 'total_shipping': total_shipping, 'payment_information': payment_info }) else: print request.POST cart = request.session.get('cart', {}) new_cart = cart.copy() item_list = [] sold_item_list = [] total_price = 0 total_shipping = 0 final_total = 0 print cart print new_cart for id in cart: try: item = Item.objects.get(pk=id) if item.sold == True: sold_item_list.append(item) base_sold_email_template = open( os.path.join(PROJECT_ROOT, 'emails/reminder_email.html')).read() message = sendgrid.Mail( to=item.seller.email, subject='CampusThrift Buyer Reminder', html=base_sold_email_template, text='Body', from_email='*****@*****.**') sg.send(message) del new_cart[id] else: item_list.append(item) total_price = total_price + item.price total_shipping = total_shipping + item.shipping_price except: pass final_total = total_shipping + total_price if sold_item_list: request.session['cart'] = new_cart return render( request, 'checkout/checkout.html', { 'sold_item_list': sold_item_list, 'items': item_list, 'total': final_total, 'sub_total': total_price, 'total_shipping': total_shipping }) else: new_order = Order() new_order.buyer = request.user sub_total = 0 shipping_total = 0 final_total = 0 # for item in item_list: new_order_item = OrderItem() new_order_item.order = new_order new_order_item.item = item new_order_item.seller = item.user new_order_item.shipping_method = request.POST[str(item.pk) + '_ship_method'] new_order_item.price = item.price if int(request.POST[str(item.pk) + '_ship_method']) == 1: new_order_item.shipping_price = 0.00 new_order_item.order_item_total_price = new_order_item.price else: new_order_item.shipping_price = item.shipping_price shipping_total = shipping_total + item.shipping_price new_order_item.order_item_total_price = new_order_item.price + new_order_item.shipping_price sub_total = sub_total + item.price new_order_item.save() new_order.shipping_address = request.POST['address'] new_order.city = request.POST['city'] new_order.state = request.POST['state'] new_order.zip = request.POST['zip'] new_order.final_total = sub_total + shipping_total new_order.shipping_total = shipping_total new_order.sub_total = sub_total new_order.save() request.session['order'] = new_order.primary_key return redirect('confirm')
def handle_payment_intent_succeeded(self, event): """ Handle the payment_intent.succeeded webhook from Stripe """ intent = event.data.object billing_details = intent.charges.data[0].billing_details shipping_details = intent.shipping """ create_webhook_order """ """ create a unique order number """ order_number = "wh" + uuid.uuid4().hex[:8] """ check for any unordered baskets """ cookie = billing_details.phone pid = intent.id existing = Order.objects.filter(stripe_pid=pid) if not existing: order_total = round(intent.charges.data[0].amount / 100, 2) full_name = shipping_details.name customer_name = billing_details.name customer_email = billing_details.email webhook_order = Order(order_number=order_number, cookie=cookie, order_total=order_total, grand_total=order_total, full_name=full_name, customer_name=customer_name, stripe_pid=pid) webhook_order.save() """ fetch the basket items to save into order_items """ baskets = Basket.objects.filter(cookie=cookie) for basket in baskets: cookie = basket.cookie item_number = basket.pk category = basket.category name = basket.name servings = basket.servings option = basket.option total_price = basket.total_price """ save the basket items into order_items """ order_basket = Order_items(cookie=cookie, order_number=order_number, item_number=item_number, category=category, name=name, servings=servings, option=option, total_price=total_price) order_basket.save() basket.delete() baskets = Basket.objects.filter(cookie=cookie) """ compose and send confirmation email """ order_date = webhook_order.date.strftime("%d/%m/%Y %H:%M:%S") parameters = { 'order_number': order_number, 'order_date': order_date, 'order_total': webhook_order.grand_total, } # Credit: https://stackoverflow.com/questions/2809547/creating-email-templates-with-django msg_html = render_to_string('checkout/confirmation_email.html', parameters) send_mail( 'Order Confirmation', msg_html, '*****@*****.**', [customer_email], html_message=msg_html, ) """ webhook order created """ return HttpResponse( content=f'Webhook received: {event["type"]}', status=200)
def noForwardedsInfo(request): """ This function update the information about orders no forwarded and return the object orderSended. Some functions need no use this object """ ordersSendeds = Order.objects.filter(sended=True) request.session['no_forwarded'] = Order.getNoForwardeds(ordersSendeds) return ordersSendeds
def handle(self, *args, **options): path = args[0] if path.startswith('http'): content = requests.get(path).json() else: content = json.load(open(path)) for item in content: id_ = int(item['id']) + 300 # 260 розничных заказов, плюс небольшой отступ try: order = Order.objects.get(id=id_) except Order.DoesNotExist: order = Order(id=id_) print 'Processing order %s' % item['id'] order.code = item['code'] order.net = float(item['amt']) order.comment = item.get('comment', '') order.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['cdt']))) order.status = STATUSES_MAPPING[item['status']] order.payment_type = PAYMENT_MAPPING.get(item.get('payment')) order.delivery_cost = int(item.get('dcost', 0)) try: order.delivery = Delivery.objects.get(id=DELIVERY_MAPPINGS.get(item.get('delivery'))) except Delivery.DoesNotExist: pass try: order.user = User.objects.get(id=int(item['user_id'])) except User.DoesNotExist: try: if not 'email' in item: raise User.DoesNotExist() order.user = User.objects.get(email=item['email']) except User.DoesNotExist: pass order.save() if order.user: try: company = Company.objects.get(user=order.user) except Company.DoesNotExist: company = Company(user=order.user) company.title = item.get('addr_name') or item.get('company_name', '') company.city = item.get('company_city', '') company.director = item.get('director', '') company.juridical_address = item.get('jaddress', '') company.post_address = item.get('address', '') company.industry = item.get('company_industry', '') company.phone = item.get('phone', '') company.inn = item.get('inn', '') company.ogrn = item.get('ogrn', '') company.save() else: print 'Order %d cant be linked to user' % order.id for pitem in item.get('lst', ()): product_id = int(pitem['item_id']) try: product = Product.objects.get(wholesale_legacy_id=product_id, is_visible=True) kwargs = { 'product': product, } except Product.DoesNotExist: print 'Unknown product with id %s' % pitem['item_id'] kwargs = { 'product_legacy_id': product_id, } except Product.MultipleObjectsReturned: print product_id raise try: order_item = OrderItem.objects.get(order=order, **kwargs) except OrderItem.DoesNotExist: order_item = OrderItem(order=order, **kwargs) order_item.product_legacy_id = product_id order_item.amount = int(pitem['qty']) order_item.per_item = float(pitem['price']) order_item.save()
def create_order(request,transaction_id): order=Order() checkout_form=CheckoutForm(request.POST,instance=order) order=checkout_form.save(commit=False) order.transaction_id= transaction_id order.ip_address = request.META.get('REMOTE_ADDR') order.user = None order.user = None if request.user.is_authenticated(): order.user=request.user order.status = Order.SUBMITTED order.save() order.status = Order.SUBMITTED order.save() # if the order save succeeded if order.pk: cart_items = cart.cart.get_cart_items(request) for ci in cart_items: # create order item for each cart item oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price # now using @property oi.product = ci.product oi.save() # all set, empty cart cart.cart.empty_cart(request) #associate orders placed with registered users if they are logged in during the checkout process. if request.user.is_authenticated(): from account import profile profile.set(request) # return the new order object return order
def save(self): self.checkout.storage['is_confirmed'] = True order = Order() order.user = self.request.user order.address = self._get_address() order.delivery_date = self._get_delivery_date() order.delivery_time = self._get_delivery_time() order.shop = self._get_shop() order.status = Order.STATUS_RECEIVED order.code = '!' form = PaymentForm(self.request.POST) form.is_valid() order.comment = form.cleaned_data.get('comment', self.checkout.storage.get('comment', '')) net = self.request.cart.get_total(request=self.request).net try: order.delivery = Delivery.objects.get(id=self.checkout.storage['delivery']) except Delivery.DoesNotExist: order.delivery = None order.delivery_cost = 0 else: order.delivery_cost = order.delivery.cost(net) print 'DELIVERY', order.delivery_id if order.delivery_id == Delivery.TYPE_SELF: order.payment_type = Order.PAYMENT_CASHPICK elif order.delivery_id == Delivery.TYPE_COURIER: order.payment_type = Order.PAYMENT_COURIER if net > 1000 and (order.address.city == u'Иркутск' or order.address.courier_city_id == 1): # Иркутск order.delivery_cost = 0 elif order.address.courier_city: order.delivery_cost = order.address.courier_city.price elif order.delivery_id == Delivery.TYPE_RUSSIANPOST: order.payment_type = Order.PAYMENT_ROBOKASSA elif order.delivery_id == Delivery.TYPE_EXPRESSPOST: pass order.products_price = self.request.cart.get_total(request=self.request).net order.net = self.request.cart.get_total(request=self.request).net + order.delivery_cost order.status = Order.STATUS_PAYMENT_WAITING order.save() for line in self.request.cart: item = OrderItem(order=order, product=line.product, amount=line.quantity, per_item=line.product.price_for_user(self.request.user) or 0) if line.data: item.sign = line.data.get('sign') item.save() coupon = self._get_coupon() if coupon: diff = self._apply_coupon(order, coupon) order.coupon = coupon order.net -= diff order.save() try: del self.request.session[Cart.COUPON_KEY] except KeyError: pass self.checkout.storage['order_id'] = order.id self.checkout.save()
def handle(self, *args, **options): path = args[0] if path.startswith('http'): content = requests.get(path).json() else: content = json.load(open(path)) for item in content: try: order = Order.objects.get(id=int(item['id'])) except Order.DoesNotExist: order = Order(id=int(item['id'])) order.code = item['code'] order.net = float(item['amt']) order.comment = item.get('comment', '') order.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['cdt']))) order.status = STATUSES_MAPPING[item['status']] order.payment_type = PAYMENT_MAPPING.get(item.get('payment')) order.delivery_cost = int(item.get('dcost', 0)) try: order.delivery = Delivery.objects.get(id=DELIVERY_MAPPINGS.get(item.get('delivery'))) except Delivery.DoesNotExist: pass try: order.user = User.objects.get(id=int(item['user_id'])) except User.DoesNotExist: try: if not 'email' in item: raise User.DoesNotExist() order.user = User.objects.get(email=item['email']) except User.DoesNotExist: pass order.save() for pitem in item.get('lst', ()): product = Product.objects.get(id=int(pitem['item_id'])) try: order_item = OrderItem.objects.get(order=order, product=product) except OrderItem.DoesNotExist: order_item = OrderItem(order=order, product=product) order_item.amount = int(pitem['qty']) order_item.per_item = float(pitem['price']) order_item.save()