def business_sale(request, business_url=None): if request.method == "POST": if not request.user.is_anonymous: business = Business.objects.filter(url=business_url).first() if not business: return Response(status=status.HTTP_400_BAD_REQUEST) business_owner = business.user user = User.objects.get(id=request.user.id) client_user_query = ClientUser.objects.filter(user=user) for client_user in client_user_query: if client_user.client.id_user == business_owner: client = client_user.client sale = Sale() sale.id_user = business_owner sale.id_client = client sale.date = request.data.get('date') sale.discount = request.data.get('discount') sale.subtotal = request.data.get('subtotal') sale.pay_type = request.data.get('pay_type') sale.total = request.data.get('total') sale.finished = request.data.get('finished') sale.save() products = request.data.get('products') for product_request in products: product = Product.objects.get( id=product_request.get('id_product')) SaleProduct.objects.create( id_sale=sale, product=product, quantity=product_request.get('quantity')) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_401_UNAUTHORIZED) else: return Response(status=status.HTTP_404_NOT_FOUND)
def clean(self): """ The clean method will effectively charge the card and create a new Sale instance. If it fails, it simply raises the error given from Stripe's library as a standard ValidationError for proper feedback. """ cleaned = super(SalePaymentForm, self).clean() if not self.errors: number = self.cleaned_data["number"] amount = self.cleaned_data["amount"] exp_month = self.cleaned_data["expiration"].month exp_year = self.cleaned_data["expiration"].year cvc = self.cleaned_data["cvc"] sale = Sale() # let's charge $10.00 for this particular item success, instance = sale.charge(amount * 100, number, exp_month, exp_year, "hello", cvc) instance.save() if not success: raise forms.ValidationError("Error: %s" % instance.message) else: sale.save() # we were successful! do whatever you will here... # perhaps you'd like to send an email... pass return cleaned
def post(self, request, *args, **kwargs): self.request_data = json.loads(self.request.body) store_id = self.request_data['store_id'] amount = self.request_data['total_amount'] products = self.request_data['products'] buyer = self.request.user store = None try: store = Store.objects.get(pk=store_id) except: return JsonResponse({'msg': 'Store does not exist.'}) total, cleaned_products = get_products_data( client_products=products, store_products=store.products) print(f"Total: {total}\nProducts: {cleaned_products}") sale = Sale(amount=total, products=cleaned_products, buyer=buyer, store=store) sale.save() return JsonResponse({'id': sale.pk.__str__()})
def process_item(self, item, spider): # / SALE >>>> # extra if check up. shouldn't trigger because we already only scraping since th last sale. if Sale.objects.filter(sale_id=item['sale_id'], product__sku=item['sku']).exists(): print('Sale already exists in database') return item else: sale = Sale() sale.sale_id = item['sale_id'] # nooks sale id sale.date = item['date'] sale.product = Product.objects.get( Q(sku=item['sku']) | Q(sku_oshawa=item['sku'])) sale.quantity = int(item['quantity']) # int bc. its string # slice bcause first char is $, float bc. its string sale.price_per_unit = float(item['price_per_unit'][1:]) sale.price = sale.price_per_unit * sale.quantity # TODO make real model for channels sale.channel = 'Nooks' # attribute nooks payout period to the sale nooks_payout_schedule = NooksPayoutSchedule.objects.get( start_date__lte=sale.date, end_date__gte=sale.date) sale.nooks_payout_schedule = nooks_payout_schedule sale.save() # / TRANSACTION >>>> # record change in inventory because of sale transaction = Transaction() transaction.date = item['date'] transaction.product = sale.product transaction.type = TransactionType.objects.get( id=1) # id 1 is Sale # minus because it's sale transaction.quantity = -int(item['quantity']) transaction.location = Location.objects.get(name=item['location']) # because each location has different sku need to check which sku to query # all because one sale id can be multiple items. # TODO: redesign if item['location'] == "Oshawa Centre": # for now only check oshawa transaction.sale = Sale.objects.get( sale_id=item['sale_id'], product__sku_oshawa=item['sku']) else: transaction.sale = Sale.objects.get(sale_id=item['sale_id'], product__sku=item['sku']) transaction.save() return item
def charge(request, amount): if request.method == 'POST': if amount == '0': return redirect('sales:checkout') u = User.objects.get(username=request.user) sale = Sale() #stripe charge success, instance = sale.charge(amount, request.POST['stripeToken'], u.email) if not success: print(instance) return HttpResponse("Error reading card.") else: try: billing = Billing.objects.get(user=u) except Billing.DoesNotExist: billing = Billing(user=u) billing.address = request.POST['args[billing_address_line1]'] billing.city = request.POST['args[billing_address_city]'] billing.state = request.POST['args[billing_address_state]'] billing.zipcode = request.POST['args[billing_address_zip]'] billing.country = request.POST['args[billing_address_country]'] billing.save() try: shipping = Shipping.objects.get(user=u) except Shipping.DoesNotExist: shipping = Shipping(user=u) shipping.address = request.POST['args[shipping_address_line1]'] shipping.city = request.POST['args[shipping_address_city]'] shipping.state = request.POST['args[shipping_address_state]'] shipping.zipcode = request.POST['args[shipping_address_zip]'] shipping.country = request.POST['args[shipping_address_country]'] shipping.save() sale.date = timezone.now() sale.amount = amount sale.user = u sale.save() request.session['sale_id'] = sale.id #Send Confirmation email. subject = "Master Faster Confirmation Email." message = "Thank you for shopping with Master Faster. \ Your payment successfully went through.\n\nConfirmation number: %s\n\n\ Shipping Address is:\n\n%s\n%s, %s\n%s %s\n\nBilling Address:\n\n%s\n%s, %s\n%s %s\n\n\ You will be receiving your receipt shortly.\n\n\ Please email us at %s to correct any order detail errors." % ( sale.charge_id, shipping.address, shipping.city, shipping.state, shipping.zipcode, shipping.country, billing.address, billing.city, billing.state, billing.zipcode, billing.country, settings.EMAIL_HOST_USER) from_email = settings.EMAIL_HOST_USER to_email = request.POST.get('emailAddress', '') send_email(subject, message, from_email, to_email) return HttpResponse('Successful Charge.') return HttpResponse("Invalid match.")
def submit_basket(self): # Selecting the customer customer_id = 1 if self.selected_customer is not '': customer_id = int(self.selected_customer) else: print('Please select a customer') customer = Customer.objects.get(pk=customer_id) # Selecting the employee employee = User.objects.get( pk=1) # TODO: Modify this after implementing the login # Creating the basket date_submitted = timezone.now() basket = Basket(date_submitted=date_submitted) basket.save() # Creating the basket lines lines_dict = self.products_in_basket for line in lines_dict: product = Product.objects.get(pk=int(line)) quantity = lines_dict[line] price_excl_tax = product.selling_price price_incl_tax = float(product.selling_price) + ( float(product.selling_price) * float(product.tax_rate)) / 100 # TODO: This line has to be fed from the Basket Table, # as user can modify prices at checkout basket_line = BasketLine(basket=basket, product=product, quantity=quantity, price_excl_tax=price_excl_tax, price_incl_tax=price_incl_tax) basket_line.save() # Selecting the payment payment_source_text = self.comboBox.currentText() payment_source = PaymentSource.objects.get(name=payment_source_text) payment_value_date = timezone.now() payment = Payment(source=payment_source, date_value=payment_value_date, amount=self.total_basket) payment.save() sale = Sale(basket=basket, employee=employee, payment=payment, customer=customer) # TODO: Need to add Inventory Entries after submitting a sale sale.save() msg = MessageDialog('The sale has been submitted') msg.exec_() msg.show() self.clear_all()
def create_sale(self): if self.order: items = self.order.items.all() for item in items: product_price = item.product.discounted_price if item.product.discounted_price else item.product.price promo_code = self.order.promo_code if self.order.promo_code else None sale = Sale(product=item.product, price=product_price, promo_code=promo_code) sale.save()
def setUp(self): time = timezone.now() staff = Staff(name="C", position="B") staff.save() product = LemonadeProduct(name="Lemonade", price=20) product.save() sale_1 = Sale(staff_id=staff, product_id=product, quantity=1) sale_1.save() sale_2 = Sale(staff_id=staff, product_id=product, quantity=2) one_week = timezone.now() + datetime.timedelta(days=7) sale_2.date_sale = one_week sale_2.save()
def create(self, validated_data): sale = Sale() sale.id_user = validated_data.get('id_user') sale.id_client = validated_data.get('id_client') sale.date = validated_data.get('date') sale.discount = validated_data.get('discount') sale.subtotal = validated_data.get('subtotal') sale.pay_type = validated_data.get('pay_type') sale.total = validated_data.get('total') sale.finished = validated_data.get('finished') sale.products = validated_data.get('products') sale.save() # Save every product in table SaleProduct for product in sale.products: sale_product = SaleProduct() sale_product.id_sale = sale sale_product.product = Product.objects.get( id=product['id_product']) sale_product.quantity = product['quantity'] sale_product.save() return sale
def clean(self): """ The clean method will effectively charge the card and create a new Sale instance. If it fails, it simply raises the error given from Stripe's library as a standard ValidationError for proper feedback. """ cleaned = super(SalePaymentForm, self).clean() if not self.errors: number = self.cleaned_data["number"] amount = self.cleaned_data["amount"] exp_month = self.cleaned_data["expiration"].month exp_year = self.cleaned_data["expiration"].year cvc = self.cleaned_data["cvc"] username = self.user user_data = User.objects.filter(username=self.user).values('email') user_email = user_data.values()[0]['email'] sale = Sale() # let's charge $10.00 for this particular item success, instance = sale.charge(amount * 100, number, exp_month, exp_year, username, user_email, cvc) instance.save() if not success: raise forms.ValidationError("Error: %s" % instance.message) else: print self.user trans = sale.save() # transaction_data = PayTransactions(user_name=self.user, email_id=user_email, amount=amount, # date_time=datetime.now()) # transaction_data.save() # try: # trans = sale.save() # customer = stripe.Customer.create(email = user_email, plan='MPL01',card=trans.stripe_id ) # trans.stripe_id = customer.id # trans.plan = 'MPL01' # trans.save() # except stripe.CardError , e: # forms.ValidationError("Error: %s" % instance.message) print "SSSSSSSSSSSSSSSSSSSSSSSSsssssssssssssssssssssssssssssssssss" return "Payment Successfull" # we were successful! do whatever you will here... # perhaps you'd like to send an email... # pass return cleaned
def post(self, request, *args, **kwargs): for product in request.session['cart_products']: product_obj = Product.objects.get(pk=product['product_id']) sale = Sale( product_id=product['product_id'], quantity=product['quantity'], unit_price=product['unit_price'], total=product['unit_price'] * product['quantity'], staff_id=self.request.user.pk, branch_id=self.request.user.branch.pk, ) sale.save() # Update product_stock product_obj.quantity = product_obj.quantity - product['quantity'] product_obj.save() # Update branch_stock tbl branch_stock, created = BranchProduct.objects.get_or_create( product_id=product_obj.pk, branch_id=request.user.branch.pk) branch_stock.quantity = branch_stock.quantity - product['quantity'] branch_stock.save() del request.session['cart_products'] messages.success(request, 'Sale completed successfully', extra_tags='alert alert-success') return redirect(to='/sales/')
import settings_copy as settings setup_environ(settings) from books.models import Book from members.models import Member from sales.models import Sale t = int(raw_input("number of sales you want to add:")) import random def get_rand(s): return s[random.randint(0, len(s) - 1)] books = Book.objects.all() members = Member.objects.all() for i in range(t): s = Sale() s.book = get_rand(books) s.member = get_rand(members) s.count = random.randint(1, 3) if s.book.count < s.count: continue s.new() s.save() print s
import csv import os import sys import django # Django configuration sys.path.append(os.path.join(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) os.environ['DJANGO_SETTINGS_MODULE'] = 'server.settings' django.setup() with open('sales.csv') as csvfile: from sales.models import Sale reader = csv.DictReader(csvfile) for row in reader: date = row['Sale Date'] sale_id = row['Sale ID'] sku = row['SKU'] product = row['Product Name'] quantity = row['Quantity'] price = row['Price'] channel = row['Channel'] sale = Sale(date=date, sale_id=sale_id, sku=sku, product=product, quantity=quantity, price=price, channel=channel) sale.save()