def create_user(request): if request.method == 'POST': form = UserForm(request.POST) profile = ProfileForm(request.POST) if form.is_valid() and profile.is_valid(): shops = profile.cleaned_data['shops'] #save form user_data = form.save(commit=False) user_data.save() #save profile form profile_data = profile.save(commit=False) profile_data.creator = request.user profile_data.updater = request.user profile_data.user = user_data profile_data.current_shop = shops[0] profile_data.save() profile.save_m2m() request.session['message'] = 'User Created Successfully' return HttpResponseRedirect( reverse('users:view_user', kwargs={'pk': profile_data.pk})) else: errors = generate_form_errors(form, formset=False) errors += generate_form_errors(profile, formset=False) context = { 'form': form, 'profile': profile, 'title': 'Create User', 'message': 'Form Validation Error', "errors": errors, 'url': reverse('users:create_user'), "users_active": "active" } return render(request, 'users/entry_user.html', context) else: form = UserForm() profile = ProfileForm() context = { "form": form, "profile": profile, "title": "Create User", 'url': reverse('users:create_user'), "users_active": "active" } return render(request, 'users/entry_user.html', context)
def edit_user(request, pk): instance = get_object_or_404( Profile.objects.filter(pk=pk, is_deleted=False)) if request.method == 'POST': form = EditUserForm(request.POST, instance=instance.user) profile = ProfileForm(request.POST, instance=instance) if form.is_valid() and profile.is_valid(): #save auth user user_data = form.save(commit=False) user_data.save() #save profile profile_data = profile.save(commit=False) profile_data.updater = request.user profile_data.date_updated = datetime.datetime.now() profile_data.save() profile.save_m2m() request.session['message'] = 'User Successfully Edited' return HttpResponseRedirect( reverse('users:view_user', kwargs={'pk': instance.pk})) else: errors = generate_form_errors(form, formset=False) errors += generate_form_errors(profile, formset=False) context = { 'message': 'Form Validation Error', 'title': 'Edit Form', 'form': form, 'profile': profile, "errors": errors, "users_active": "active", 'url': reverse('users:edit_user', kwargs={'pk': instance.pk}), } return render(request, 'users/entry_user.html', context) else: form = EditUserForm(instance=instance.user) profile = ProfileForm(instance=instance) context = { 'title': 'Edit User' + instance.user.username, 'form': form, 'profile': profile, 'instance': instance, 'url': reverse('users:edit_user', kwargs={'pk': instance.pk}), "users_active": "active" } return render(request, 'users/entry_user.html', context)
def create_customer(request): if request.method == "POST": form = CustomerForm(request.POST, request=request) if form.is_valid(): #get current shop shop = get_current_shop(request) #create customer_id customer_id = 1 customer_obj = Customer.objects.filter( shop=shop).order_by("-date_added")[:1] if customer_obj: for customer in customer_obj: customer_id = customer.customer_id + 1 #create farmer data = form.save(commit=False) data.creator = request.user data.updater = request.user data.customer_id = customer_id data.shop = shop data.save() request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('customers:view_customer', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) context = { "form": form, "title": "Error", "errors": errors, "customers_active": "active" } return render(request, 'customers/entry_customer.html', context) else: form = CustomerForm() context = { "form": form, "title": "Create Customer", "url": reverse('customers:create_customer'), "redirect": True, "customers_active": "active" } return render(request, 'customers/entry_customer.html', context)
def create_shop(request): if request.method == "POST": form = ShopForm(request.POST) if form.is_valid(): #generate auto id shop_id = 1 shop_obj = Shop.objects.all().order_by("-date_added")[:1] if shop_obj: for shop in shop_obj: shop_id = shop.shop_id + 1 #create shop data = form.save(commit=False) data.creator = request.user data.updater = request.user data.shop_id = shop_id data.save() profiles = Profile.objects.filter(user_type='admin') for profile in profiles: profile.shops.add(data.pk) request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('shops:view_shop', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) context = { "form": form, "title": "Create Shop", "errors": errors, "shops_active": "active" } return render(request, 'shops/entry_shop.html', context) else: form = ShopForm() context = { "form": form, "title": "Create Shop", "url": reverse('shops:create_shop'), "shops_active": "active" } return render(request, 'shops/entry_shop.html', context)
def create_vendor(request): if request.method == "POST": form = VendorForm(request.POST,request=request) current_shop = get_current_shop(request) if form.is_valid(): #generate auto id vendor_id = 1 vendor_obj= Vendor.objects.filter(shop=current_shop).order_by("-date_added")[:1] if vendor_obj: for vendor in vendor_obj: vendor_id = vendor.vendor_id+1 #create vendor data = form.save(commit=False) data.creator = request.user data.updater = request.user data.vendor_id = vendor_id data.shop = current_shop data.save() request.session['message'] = 'Form Submitted Successfully' return HttpResponseRedirect(reverse('vendors:view_vendor',kwargs = {'pk' : data.pk})) else: errors =generate_form_errors(form,formset=False) context = { "form" : form, "title" : "Create Vendor", "errors" : errors, "vendors_active":"active" } return render(request,'vendors/entry_vendor.html',context) else: form = VendorForm() context = { "form" : form, "title" : "Create Vendor", "url" : reverse('vendors:create_vendor'), "vendors_active":"active" } return render(request,'vendors/entry_vendor.html',context)
def create_cheque(request): if request.method == "POST": form = ChequeForm(request.POST) if form.is_valid(): #get current shop shop = get_current_shop(request) #create cheque data = form.save(commit=False) data.creator = request.user data.updater = request.user data.shop = shop data.save() request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect(reverse('cheques:view_cheque', kwargs = {'pk' : data.pk})) else: errors =generate_form_errors(form,formset=False) context = { "form" : form, "title" : "Error", "errors":errors, "cheques_active":"active" } return render(request, 'cheques/entry_cheque.html', context) else: form = ChequeForm() context = { "form" : form, "title" : "Create Cheque", "url" : reverse('cheques:create_cheque'), "redirect" : True, "cheques_active":"active" } return render(request, 'cheques/entry_cheque.html', context)
def create_customer_popup(request): if request.method == "POST": #get current shop shop = get_current_shop(request) form = CustomerForm(request.POST, request=request) if form.is_valid(): #create customer_id customer_id = 1 customer_obj = Customer.objects.filter( shop=shop).order_by("-date_added")[:1] if customer_obj: for customer in customer_obj: customer_id = customer.customer_id + 1 #create farmer data = form.save(commit=False) data.creator = request.user data.updater = request.user data.customer_id = customer_id data.shop = shop data.save() response_data = { 'status': 'true', 'message': "Customer %s Created Successfully" % (data.name), } response = HttpResponse(json.dumps(response_data), content_type='application/javascript') return response else: errors = generate_form_errors(form, formset=False) response_data = { 'status': 'false', 'message': errors, } response = HttpResponse(json.dumps(response_data), content_type='application/javascript') return response
def edit_customer(request, pk): instance = get_object_or_404( Customer.objects.filter(pk=pk, is_deleted=False)) if request.method == "POST": response_data = {} form = CustomerForm(request.POST, instance=instance, request=request, edit=True) if form.is_valid(): #update customer data = form.save(commit=False) data.updater = request.user data.date_updated = datetime.datetime.now() data.save() request.session['message'] = 'Form Edited successfully' return HttpResponseRedirect( reverse('customers:view_customer', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) context = { "form": form, "title": "Update Customer", "customers_active": "active" } return render(request, 'customers/entry_customer.html', context) else: form = CustomerForm(instance=instance) context = { "form": form, "title": "Edit customer : " + instance.name, "instance": instance, "customers_active": "active" } return render(request, 'customers/entry_customer.html', context)
def create_vendor_popup(request): if request.method == "POST": form = VendorForm(request.POST,request=request) current_shop = get_current_shop(request) if form.is_valid(): #generate auto id vendor_id = 1 vendor_obj= Vendor.objects.filter(shop=current_shop).order_by("-date_added")[:1] if vendor_obj: for vendor in vendor_obj: vendor_id = vendor.vendor_id+1 #create vendor data = form.save(commit=False) data.creator = request.user data.updater = request.user data.vendor_id = vendor_id data.shop = current_shop data.save() response_data = { 'status':'true', 'message': "Vendor %s Created Successfully" %(data.name), } response = HttpResponse(json.dumps(response_data), content_type='application/javascript') return response else: errors =generate_form_errors(form,formset=False) response_data = { 'status':'false', 'message': errors, } response = HttpResponse(json.dumps(response_data), content_type='application/javascript') return response
def change_password(request, pk): profile = get_object_or_404(Profile.objects.filter(pk=pk)) user = get_object_or_404( User.objects.filter(pk=profile.user.pk, is_active=True)) if request.method == "POST": change_password_form = SetPasswordForm(user=user, data=request.POST) if change_password_form.is_valid(): change_password_form.save() context = { "change_password_form": change_password_form, "title": "Change Password: "******"message": "Password Changed Succesfully", "instance": profile, } return render(request, 'includes/change_password.html', context) else: errors = generate_form_errors(change_password_form, formset=False) context = { "change_password_form": change_password_form, "title": "Change Password: "******"errors": errors, "instance": profile, } return render(request, 'includes/change_password.html', context) else: change_password_form = SetPasswordForm(user=user) context = { "change_password_form": change_password_form, "title": "Change Password: "******"instance": profile, } return render(request, 'includes/change_password.html', context)
def edit_shop(request, pk): instance = get_object_or_404(Shop.objects.filter(pk=pk, is_deleted=False)) if request.method == "POST": form = ShopForm(request.POST, instance=instance) if form.is_valid(): #edit shop data = form.save(commit=False) data.updater = request.user data.date_updated = datetime.datetime.now() data.save() request.session['message'] = 'Form Edited successfully' return HttpResponseRedirect( reverse('shops:view_shop', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) context = { "form": form, "title": "Edit Shop", "errors": errors, "shops_active": "active" } return render(request, 'shops/entry_shop.html', context) else: form = ShopForm(instance=instance) context = { "form": form, "title": "Edit Shop : " + instance.name, "url": reverse('shops:edit_shop', kwargs={'pk': instance.pk}), "shops_active": "active" } return render(request, 'shops/entry_shop.html', context)
def create_purchase(request): PurchaseProductFormset = formset_factory(PurchaseProductForm, min_num=1, validate_min=True, extra=0) current_shop = get_current_shop(request) vendor_form = VendorForm() if request.method == "POST": form = PurchaseForm(request.POST) purchase_product_formset = PurchaseProductFormset( request.POST, prefix='purchase_product_formset') for field in purchase_product_formset: field.fields['product'].queryset = Product.objects.filter( shop=current_shop, is_deleted=False) if form.is_valid() and purchase_product_formset.is_valid(): purchase_id = 'P1' purchase_obj = Purchase.objects.filter( shop=current_shop).order_by("-date_added")[:1] if purchase_obj: for purchase in purchase_obj: purchase_id = 'P' + str( int(re.findall(r'\d+', purchase.purchase_id)[0]) + 1) balance = form.cleaned_data['balance'] vendor = form.cleaned_data['vendor'] #create purchase data = form.save(commit=False) data.creator = request.user data.updater = request.user data.purchase_id = purchase_id data.shop = current_shop data.date_added = datetime.datetime.now() data.save() #save PurchaseProduct for form in purchase_product_formset: product = form.cleaned_data['product'] unit_cost = form.cleaned_data['unit_cost'] input_gst = form.cleaned_data['input_gst'] quantity = form.cleaned_data['quantity'] offer = form.cleaned_data['offer'] tax_amount = form.cleaned_data['tax_amount'] amount = form.cleaned_data['amount'] total_amount = form.cleaned_data['total_amount'] PurchaseProduct(product=product, purchase=data, unit_cost=unit_cost, input_gst=input_gst, quantity=quantity, offer=offer, tax_amount=tax_amount, amount=amount, total_amount=total_amount).save() if Product.objects.filter(pk=product.pk, shop=current_shop).exists(): current_stock = Product.objects.get( pk=product.pk, shop=current_shop).stock Product.objects.filter(pk=product.pk, shop=current_shop).update( stock=quantity + current_stock) #update balance of vendor if vendor: current_balance = Vendor.objects.get(pk=vendor.pk, shop=current_shop, is_deleted=False).balance Vendor.objects.filter( pk=vendor.pk, shop=current_shop, is_deleted=False).update(balance=current_balance + balance) request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('purchases:view_purchase', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) errors += generate_form_errors(purchase_product_formset, formset=True) context = { "form": form, "vendor_form": vendor_form, "title": "Create Purchase", "purchase_product_formset": purchase_product_formset, "errors": errors, "purchases_active": "active" } return render(request, 'purchases/entry_purchase.html', context) else: form = PurchaseForm() purchase_product_formset = PurchaseProductFormset( prefix='purchase_product_formset') for field in purchase_product_formset: field.fields['product'].queryset = Product.objects.filter( shop=current_shop, is_deleted=False) context = { "form": form, "vendor_form": vendor_form, "purchase_product_formset": purchase_product_formset, "title": "Create Purchase", "url": reverse('purchases:create_purchase'), "purchases_active": "active" } return render(request, 'purchases/entry_purchase.html', context)
def edit_purchase(request, pk): current_shop = get_current_shop(request) purchase_instance = get_object_or_404( Purchase.objects.filter(pk=pk, is_deleted=False, shop=current_shop)) vendor_form = VendorForm() PurchaseProductFormset = inlineformset_factory( Purchase, PurchaseProduct, can_delete=True, extra=0, min_num=1, validate_min=True, exclude=('shop', 'purchase'), widgets={ 'product': autocomplete.ModelSelect2(url='products:product-autocomplete', attrs={ 'data-placeholder': 'Select Product', 'data-minimum-input-length': 1 }), 'quantity': TextInput(attrs={ 'placeholder': 'Enter quantity', 'class': 'required form-control' }), 'unit_cost': TextInput( attrs={ 'placeholder': 'Enter unit cost(inc. tax)', 'label': 'Unit cost', 'class': 'required form-control' }), 'input_gst': TextInput(attrs={ 'placeholder': 'Input Tax', 'class': 'required form-control' }), 'offer': TextInput(attrs={ 'placeholder': 'Enter offer', 'class': 'required form-control' }), 'amount': TextInput(attrs={ 'placeholder': 'Enter amount', 'class': 'required form-control' }), 'tax_amount': TextInput(attrs={ 'placeholder': 'Tax amount', 'class': 'required form-control' }), 'total_amount': TextInput( attrs={ 'placeholder': 'Enter total amount', 'class': 'required form-control' }), }, error_messages={ 'product': { 'required': _("product field is required."), }, 'unit_cost': { 'required': _("Unit Cost field is required."), }, 'quantity': { 'required': _("Quantity field is required."), }, }) if request.method == "POST": response_data = {} form = PurchaseForm(request.POST, instance=purchase_instance) purchase_product_formset = PurchaseProductFormset( request.POST, prefix='purchase_product_formset', instance=purchase_instance) error = '' # checking quantity and stock of deleted product to ensure quantity is less than stock if purchase_product_formset.deleted_forms: for deleted_form in purchase_product_formset.deleted_forms: if deleted_form.instance.product.stock <= deleted_form.instance.quantity: error = "Invalid operation, Product can not removed because of incorrect quantity" #tacking vendor and vendor balance in variables vendor_balance = purchase_instance.balance vendor = purchase_instance.vendor if form.is_valid() and purchase_product_formset.is_valid(): #remove previous Purchase Product purchase_product = PurchaseProduct.objects.filter( purchase=purchase_instance.pk, is_deleted=False) for purchase_product_form in purchase_product_formset: new_product = purchase_product_form.cleaned_data['product'] new_quantity = purchase_product_form.cleaned_data['quantity'] new_unit_cost = purchase_product_form.cleaned_data['unit_cost'] new_input_gst = purchase_product_form.cleaned_data['input_gst'] new_offer = purchase_product_form.cleaned_data['offer'] new_amount = purchase_product_form.cleaned_data['amount'] pre_quantity = 0 pre_product = None if PurchaseProduct.objects.filter( pk=purchase_product_form.instance.pk).exists(): purchaseform = PurchaseProduct.objects.get( pk=purchase_product_form.instance.pk) pre_quantity = purchaseform.quantity pre_purchase_product = PurchaseProduct.objects.get( pk=purchase_product_form.instance.pk) pre_product = pre_purchase_product.product current_stock = new_product.stock new_stock = 0 if pre_product == new_product: new_stock = current_stock - pre_quantity + new_quantity else: if pre_product: pre_product_stock_defference = pre_product.stock - pre_purchase_product.quantity if pre_product_stock_defference < 0: error += "You can not change product because you already sold some unit %s belong to this purchase" % pre_product.name if new_quantity < 0: error += "Can't change the quantity as you entered. Please re enter the quantity of %s" % ( new_product) if new_stock < 0: error += "You can not change product because you already sold some unit %s belong to this purchase" % pre_product.name if not error: #take edited vendor and balance edited_balance = form.cleaned_data['balance'] edited_vendor = form.cleaned_data['vendor'] #removing deleted form from formset group and reducing count of product in stock count if purchase_product_formset.deleted_forms: for deleted_form in purchase_product_formset.deleted_forms: if deleted_form.instance.product.stock >= deleted_form.instance.quantity: new_stock = deleted_form.instance.product.stock - deleted_form.instance.quantity Product.objects.filter( pk=deleted_form.instance.product.pk, is_deleted=False).update(stock=new_stock) #update item data = form.save(commit=False) data.updater = request.user data.date_updated = datetime.datetime.now() data.save() #update PurchaseProduct for form in purchase_product_formset: product = form.cleaned_data['product'] unit_cost = form.cleaned_data['unit_cost'] input_gst = form.cleaned_data['input_gst'] quantity = form.cleaned_data['quantity'] offer = form.cleaned_data['offer'] amount = form.cleaned_data['amount'] #update product stock pre_quantity = 0 pre_product = None if PurchaseProduct.objects.filter( pk=form.instance.pk).exists(): purchaseform_instance = PurchaseProduct.objects.get( pk=form.instance.pk) pre_quantity = purchaseform_instance.quantity pre_purchase_product = purchaseform_instance pre_product = pre_purchase_product.product """update product stock if previous product is current product or previous product""" if pre_product == product: new_stock = pre_product.stock - pre_quantity + quantity Product.objects.filter( pk=product.pk, shop=current_shop).update(stock=new_stock) elif pre_product: #reducing entire quantity from product prev_product_stock = pre_product.stock - pre_quantity #updating previous product stock Product.objects.filter( pk=pre_product.pk, shop=current_shop).update(stock=prev_product_stock) #adding newly entered quantity to product stock new_stock = product.stock + quantity #updating new stock Product.objects.filter( pk=product.pk, shop=current_shop).update(stock=new_stock) """if there is no previous product then modifing product stock""" else: #adding new quantity to stock new_stock = product.stock + quantity #updating new quantity Product.objects.filter( pk=product.pk, shop=current_shop).update(stock=new_stock) #update purchase product fomset forms purchase_product_formset.save() #update vendor balance if vendor == edited_vendor: if vendor: current_balance = Vendor.objects.get( pk=vendor.pk, shop=current_shop).balance Vendor.objects.filter( pk=vendor.pk, shop=current_shop).update(balance=current_balance - vendor_balance + edited_balance) else: #update new vendor balance if edited_vendor: current_balance = Vendor.objects.get( pk=edited_vendor.pk, shop=current_shop).balance Vendor.objects.filter( pk=edited_vendor.pk, shop=current_shop).update(balance=current_balance + edited_balance) #remove previous vendor balance if vendor: pre_balance = Vendor.objects.get( pk=vendor.pk, shop=current_shop).balance Vendor.objects.filter( pk=vendor.pk, shop=current_shop).update(balance=pre_balance - vendor_balance) else: context = { "form": form, "vendor_form": vendor_form, "errors": error, "purchase_product_formset": purchase_product_formset, "title": "Edit Purchase : " + purchase_instance.purchase_id, "purchase_active": "active" } return render(request, 'purchases/entry_purchase.html', context) request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('purchases:view_purchase', kwargs={'pk': data.pk})) else: errors = generate_form_errors(form, formset=False) errors += generate_form_errors(purchase_product_formset, formset=True) context = { "form": form, "vendor_form": vendor_form, "errors": errors, "purchase_product_formset": purchase_product_formset, "title": "Edit Purchase : " + purchase_instance.purchase_id, "purchase_active": "active" } return render(request, 'purchases/entry_purchase.html', context) else: form = PurchaseForm(instance=purchase_instance) purchase_product_formset = PurchaseProductFormset( prefix='purchase_product_formset', instance=purchase_instance) for field in purchase_product_formset: field.fields['product'].queryset = Product.objects.filter( shop=current_shop, is_deleted=False) context = { "form": form, "vendor_form": vendor_form, "purchase_product_formset": purchase_product_formset, "title": "Edit Purchase : " + purchase_instance.purchase_id, "url": reverse('purchases:edit_purchase', kwargs={'pk': purchase_instance.pk}), "purchases_active": "active" } return render(request, 'purchases/entry_purchase.html', context)
def create_sale(request): SaleProductFormset = formset_factory(SaleProductForm, min_num=1, validate_min=True, extra=0) current_shop = get_current_shop(request) customer_form = CustomerForm() if request.method == "POST": form = SaleForm(request.POST) sale_product_formset = SaleProductFormset( request.POST, prefix='sale_product_formset') for field in sale_product_formset: field.fields['product'].queryset = Product.objects.filter( shop=current_shop, is_deleted=False) if form.is_valid() and sale_product_formset.is_valid(): sale_id = 'OFF/1' sale_obj = Sale.objects.filter( shop=current_shop).order_by("-date_added")[:1] if sale_obj: for sale in sale_obj: sale_id = 'OFF/' + str( int(re.findall(r'\d+', sale.sale_id)[0]) + 1) error_messages = '' #check product availability for f in sale_product_formset: product = f.cleaned_data['product'] quantity = f.cleaned_data['quantity'] available_stock = 0 #check product availability if Product.objects.filter(shop=current_shop, pk=product.pk).exists(): available_stock = Product.objects.get(shop=current_shop, pk=product.pk).stock if available_stock < quantity: error_messages += "%s is out of stock. Only %s unit(s) exists in %s . </br >" % ( product, available_stock, current_shop) if not error_messages: customer = form.cleaned_data['customer'] #create sale data = form.save(commit=False) data.creator = request.user data.updater = request.user data.sale_id = sale_id data.shop = current_shop data.date_added = datetime.datetime.now() data.save() #save SaleProduct for form in sale_product_formset: product = form.cleaned_data['product'] unit_price = form.cleaned_data['unit_price'] quantity = form.cleaned_data['quantity'] offer = form.cleaned_data['offer'] output_gst = form.cleaned_data['output_gst'] tax_amount = form.cleaned_data['tax_amount'] amount = form.cleaned_data['amount'] total_amount = form.cleaned_data['total_amount'] SaleProduct(product=product, sale=data, unit_price=unit_price, quantity=quantity, output_gst=output_gst, offer=offer, tax_amount=tax_amount, amount=amount, total_amount=total_amount).save() current_stock = Product.objects.get( pk=product.pk, shop=current_shop).stock updated_stock = current_stock - quantity Product.objects.filter( pk=product.pk, shop=current_shop).update(stock=updated_stock) if updated_stock == 0: create_notification(product, current_shop) request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('sales:view_sale', kwargs={'pk': data.pk})) else: context = { "form": form, "customer_form": customer_form, "title": "Create Sale", "sale_product_formset": sale_product_formset, "errors": error_messages, "sales_active": "active" } return render(request, 'sales/entry_sale.html', context) else: errors = generate_form_errors(form, formset=False) errors += generate_form_errors(sale_product_formset, formset=True) context = { "form": form, "customer_form": customer_form, "title": "Create Sale", "sale_product_formset": sale_product_formset, "errors": errors, "sales_active": "active" } return render(request, 'sales/entry_sale.html', context) else: form = SaleForm() sale_product_formset = SaleProductFormset( prefix='sale_product_formset') context = { "form": form, "customer_form": customer_form, "title": "Create Sale", "sale_product_formset": sale_product_formset, "url": reverse('sales:create_sale'), "sales_active": "active" } return render(request, 'sales/entry_sale.html', context)
def edit_sale(request, pk): current_shop = get_current_shop(request) instance = get_object_or_404(Sale.objects.filter(pk=pk, is_deleted=False)) customer_form = CustomerForm() SaleProductFormset = inlineformset_factory( Sale, SaleProduct, can_delete=True, extra=0, min_num=1, validate_min=True, exclude=('shop', 'sale'), widgets={ 'product': autocomplete.ModelSelect2(url='products:product-autocomplete', attrs={ 'data-placeholder': '*Select Product', 'data-minimum-input-length': 1 }), 'quantity': TextInput(attrs={ 'placeholder': '*Enter quantity', 'class': 'required form-control' }), 'unit_price': TextInput( attrs={ 'placeholder': 'Enter unit price(inc. tax)', 'label': '*Unit price', 'class': 'required form-control' }), 'output_gst': TextInput(attrs={ 'placeholder': 'Output GST', 'class': 'required form-control' }), 'offer': TextInput(attrs={ 'placeholder': 'Enter Discount', 'class': 'required form-control' }), 'amount': TextInput(attrs={ 'placeholder': 'Enter amount', 'class': 'required form-control' }), 'tax_amount': TextInput(attrs={ 'placeholder': 'Tax amount', 'class': 'required form-control' }), 'total_amount': TextInput( attrs={ 'placeholder': 'Enter total amount', 'class': 'required form-control' }), }, error_messages={ 'product': { 'required': _("Product field is required."), }, 'unit_price': { 'required': _("Unit Price field is required."), }, 'quantity': { 'required': _("Quantity field is required."), }, }) if request.method == "POST": form = SaleForm(request.POST, instance=instance) sale_product_formset = SaleProductFormset( request.POST, prefix='sale_product_formset', instance=instance) error_messages = '' if form.is_valid() and sale_product_formset.is_valid(): #check product availability for f in sale_product_formset: product = f.cleaned_data['product'] quantity = f.cleaned_data['quantity'] # previous sale quantity taken if SaleProduct.objects.filter(pk=f.instance.pk).exists(): saleform = SaleProduct.objects.get(pk=f.instance.pk) pre_product = saleform.product pre_quantity = saleform.quantity if pre_product == product: available_stock = Product.objects.get( shop=current_shop, pk=product.pk).stock new_stock = available_stock + pre_quantity if new_stock < quantity: error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % ( product, available_stock) else: available_stock = Product.objects.get( shop=current_shop, pk=product.pk).stock if available_stock < quantity: error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % ( product, available_stock) else: available_stock = 0 #check product availability if product: available_stock = Product.objects.get( shop=current_shop, pk=product.pk).stock if available_stock < quantity: error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % ( product, available_stock) if not error_messages: #update item data = form.save(commit=False) data.updater = request.user data.date_updated = datetime.datetime.now() data.save() if sale_product_formset.deleted_forms: for deleted_form in sale_product_formset.deleted_forms: new_stock = deleted_form.instance.product.stock + deleted_form.instance.quantity Product.objects.filter( pk=deleted_form.instance.product.pk, is_deleted=False).update(stock=new_stock) #save SaleProduct for form in sale_product_formset: product = form.cleaned_data['product'] unit_price = form.cleaned_data['unit_price'] quantity = form.cleaned_data['quantity'] offer = form.cleaned_data['offer'] output_gst = form.cleaned_data['output_gst'] tax_amount = form.cleaned_data['tax_amount'] amount = form.cleaned_data['amount'] # previous sale quantity taken if SaleProduct.objects.filter( pk=form.instance.pk).exists(): saleform = SaleProduct.objects.get(pk=form.instance.pk) pre_product = saleform.product pre_quantity = saleform.quantity if pre_product == product: current_stock = Product.objects.get( pk=product.pk, shop=current_shop).stock Product.objects.filter(pk=product.pk, shop=current_shop).update( stock=current_stock + pre_quantity - quantity) else: current_stock = pre_product.stock Product.objects.filter( pk=pre_product.pk, shop=current_shop).update(stock=current_stock + pre_quantity) current_product_stock = product.stock product.stock = current_product_stock - quantity product.save() else: current_stock = Product.objects.get( pk=product.pk, shop=current_shop).stock Product.objects.filter( pk=product.pk, shop=current_shop).update(stock=current_stock - quantity) #update sale product fomset forms sale_product_formset.save() request.session['message'] = 'Form Submitted successfully' return HttpResponseRedirect( reverse('sales:view_sale', kwargs={'pk': data.pk})) else: context = { "form": form, "customer_form": customer_form, "title": "Edit Sale : " + instance.sale_id, "sale_product_formset": sale_product_formset, "errors": error_messages, "sales_active": "active" } return render(request, 'sales/entry_sale.html', context) else: error_messages = generate_form_errors(form, formset=False) error_messages += generate_form_errors(sale_product_formset, formset=True) context = { "form": form, "customer_form": customer_form, "title": "Edit Sale : " + instance.sale_id, "sale_product_formset": sale_product_formset, "errors": error_messages, "sales_active": "active" } return render(request, 'sales/entry_sale.html', context) else: form = SaleForm(instance=instance) sale_product_formset = SaleProductFormset( prefix='sale_product_formset', instance=instance) for field in sale_product_formset: field.fields['product'].queryset = Product.objects.filter( shop=current_shop, is_deleted=False) context = { "form": form, "customer_form": customer_form, "sale_product_formset": sale_product_formset, "title": "Edit Sale : " + instance.sale_id, "url": reverse('sales:edit_sale', kwargs={'pk': instance.pk}), "sales_active": "active" } return render(request, 'sales/entry_sale.html', context)