コード例 #1
0
ファイル: views.py プロジェクト: ajmalmohammedn/tutorial
def create(request):
    SaleItemFormset = formset_factory(SaleItemForm, extra=1)
    if request.method == 'POST':
        form = SaleForm(request.POST)
        sale_item_formset = SaleItemFormset(request.POST,
                                            prefix='sale_item_formset')
        if form.is_valid() and sale_item_formset.is_valid():

            # Creating Sale Item Objects for finding duplicate product entry
            items = {}
            for f in sale_item_formset:
                product = f.cleaned_data['product']
                qty = f.cleaned_data['qty']
                if str(product.pk) in items:
                    q = items[str(product.pk)]["qty"]
                    items[str(product.pk)]["qty"] = q + qty
                else:
                    dic = {
                        "qty": qty,
                    }
                    items[str(product.pk)] = dic

            # Checking the stock available for this product
            stock_ok = True
            error_message = ''
            for key, value in items.items():
                product = Product.objects.get(pk=key)
                stock = product.stock
                qty = value['qty']
                if qty > stock:
                    stock_ok = False
                    error_message += "{} has only {} in stock, You entered {} qty".format(
                        product.name, str(stock), str(qty))

            if stock_ok:
                discount = form.cleaned_data['discount']
                data = form.save(commit=False)
                data.creator = request.user
                data.updator = request.user
                data.auto_id = get_auto_id(Sale)
                data.save()

                subtotal = 0
                for key, value in items.items():
                    product = Product.objects.get(pk=key)
                    qty = value["qty"]
                    price = product.price
                    sub = (qty * price)
                    subtotal += sub

                    SaleItem(sale=data, product=product, qty=qty).save()

                    update_stock(product.pk, qty, 'decrease')

                total = subtotal - discount
                data.subtotal = subtotal
                data.total = total
                data.save()

                response_data = {
                    "status": "true",
                    "title": "Successfully Created",
                    "message": "Sale Successfully Created.",
                    "redirect": "true",
                    "redirect_url": reverse('sales:sale',
                                            kwargs={'pk': data.pk})
                }
            else:
                response_data = {
                    "status": "false",
                    "stable": "true",
                    "title": "Out of Stock",
                    "message": error_message
                }
        else:
            message = generate_form_errors(form, formset=False)
            message += generate_form_errors(sale_item_formset, formset=True)
            response_data = {
                "status": "false",
                "stable": "true",
                "title": "Form validation error",
                "message": message
            }

        return HttpResponse(json.dumps(response_data),
                            content_type='application/javascript')
    else:
        form = SaleForm()
        sale_item_formset = SaleItemFormset(prefix='sale_item_formset')
        context = {
            'title': 'Create Sale',
            'form': form,
            'sale_item_formset': sale_item_formset,
            'redirect': True,
            'url': reverse('sales:create'),
            "is_need_select_picker": True,
            "is_need_popup_box": True,
            "is_need_custom_scroll_bar": True,
            "is_need_wave_effect": True,
            "is_need_bootstrap_growl": True,
            "is_need_chosen_select": True,
            "is_need_grid_system": True,
            "is_need_datetime_picker": True,
            "is_need_animations": True,
            "is_dashboard": True
        }
        return render(request, 'sales/entry.html', context)
コード例 #2
0
ファイル: views.py プロジェクト: ajmalmohammedn/tutorial
def edit(request, pk):
    instance = get_object_or_404(Sale.objects.filter(pk=pk))
    if SaleItem.objects.filter(sale=instance).exists():
        extra = 0
    else:
        extra = 1

    SaleItemFormset = inlineformset_factory(
        Sale,
        SaleItem,
        can_delete=True,
        extra=extra,
        exclude=('sale', ),
        widgets={
            'product':
            autocomplete.ModelSelect2(
                url='products:product_autocomplete',
                attrs={
                    'data-placeholder': 'Product',
                    'data-minimum-input-length': 1
                },
            ),
            'qty':
            TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Quantity'
            }),
        })

    if request.method == 'POST':
        form = SaleForm(request.POST, instance=instance)
        sale_item_formset = SaleItemFormset(request.POST,
                                            prefix='sale_item_formset',
                                            instance=instance)
        if form.is_valid() and sale_item_formset.is_valid():

            # Creating Sale Item Objects for finding duplicate product entry
            items = {}
            for f in sale_item_formset:
                product = f.cleaned_data['product']
                qty = f.cleaned_data['qty']
                if str(product.pk) in items:
                    q = items[str(product.pk)]["qty"]
                    items[str(product.pk)]["qty"] = q + qty
                else:
                    dic = {
                        "qty": qty,
                    }
                    items[str(product.pk)] = dic

            # Checking the stock available for this product
            stock_ok = True
            error_message = ''
            for key, value in items.items():
                product = Product.objects.get(pk=key)
                prev_qty = 0
                if SaleItem.objects.filter(sale=instance,
                                           product=product).exists():
                    prev_qty = SaleItem.objects.get(sale=instance,
                                                    product=product).qty
                stock = product.stock + prev_qty
                qty = value['qty']
                if qty > stock:
                    stock_ok = False
                    error_message += "{} has only {} in stock, You entered {} qty".format(
                        product.name, str(stock), str(qty))

            if stock_ok:
                discount = form.cleaned_data['discount']
                data = form.save(commit=False)
                data.updator = request.user
                data.date_updated = datetime.datetime.now()
                data.save()

                #delete previous items and update stock
                previous_sale_items = SaleItem.objects.filter(sale=instance)
                for p in previous_sale_items:
                    prev_qty = p.qty
                    update_stock(p.product.pk, prev_qty, 'increase')
                previous_sale_items.delete()

                #save items
                subtotal = 0
                for key, value in items.items():
                    product = Product.objects.get(pk=key)
                    qty = value["qty"]
                    price = product.price
                    sub = (qty * price)
                    subtotal += sub

                    SaleItem(sale=data, product=product, qty=qty).save()

                    update_stock(product.pk, qty, 'decrease')

                total = subtotal - discount
                data.subtotal = subtotal
                data.total = total
                data.save()

                response_data = {
                    "status": "true",
                    "title": "Successfully Updated",
                    "message": "Sale Successfully Updated.",
                    "redirect": "true",
                    "redirect_url": reverse('sales:sale',
                                            kwargs={'pk': data.pk})
                }
            else:
                response_data = {
                    "status": "false",
                    "stable": "true",
                    "title": "Out of Stock",
                    "message": error_message
                }
        else:
            message = generate_form_errors(form, formset=False)
            message += generate_form_errors(sale_item_formset, formset=True)
            response_data = {
                "status": "false",
                "stable": "true",
                "title": "Form validation error",
                "message": message
            }

        return HttpResponse(json.dumps(response_data),
                            content_type='application/javascript')

    else:
        form = SaleForm(instance=instance)
        sale_item_formset = SaleItemFormset(prefix='sale_item_formset',
                                            instance=instance)
        context = {
            'title': 'Edit Sale',
            'form': form,
            'sale_item_formset': sale_item_formset,
            'redirect': True,
            'url': reverse('sales:edit', kwargs={'pk': instance.pk}),
            "is_need_select_picker": True,
            "is_need_popup_box": True,
            "is_need_custom_scroll_bar": True,
            "is_need_wave_effect": True,
            "is_need_bootstrap_growl": True,
            "is_need_chosen_select": True,
            "is_need_grid_system": True,
            "is_need_datetime_picker": True,
            "is_need_animations": True,
            "is_dashboard": True
        }
        return render(request, 'sales/entry.html', context)
コード例 #3
0
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)
コード例 #4
0
def edit(request, pk):
    instance = get_object_or_404(Sale.objects.filter(pk=pk, is_deleted=False))

    if SaleItem.objects.filter(sale=instance).exists():
        extra = 0
    else:
        extra = 1

    SaleItemFormset = inlineformset_factory(
        Sale,
        SaleItem,
        can_delete=True,
        extra=extra,
        exclude=[
            'creator',
            'updater',
            'auto_id',
            'is_deleted',
            'sale',
        ],
        widgets={
            'product':
            Select(attrs={
                'class': 'required form-control',
                'data-placeholder': 'Product'
            }, ),
            'qty':
            TextInput(attrs={
                'class': 'required number form-control',
                'placeholder': 'Quantity'
            }),
        })
    if request.method == "POST":
        form = SaleForm(request.POST, instance=instance)
        sale_item_formset = SaleItemFormset(request.POST,
                                            prefix='sale_item_formset',
                                            instance=instance)

        if form.is_valid() and sale_item_formset.is_valid():

            items = {}
            for f in sale_item_formset:
                if f not in sale_item_formset.deleted_forms:
                    product = f.cleaned_data['product']
                    qty = f.cleaned_data['qty']
                    if str(product.pk) in items:
                        q = items[str(product.pk)]["qty"]
                        items[str(product.pk)]["qty"] = q + qty

                    else:
                        dic = {"qty": qty}
                        items[str(product.pk)] = dic

            stock_ok = True
            error_message = ''
            for key, value in items.items():
                product = Product.objects.get(pk=key)
                prev_qty = 0
                if SaleItem.objects.filter(sale=instance,
                                           product=product).exists():
                    prev_qty = SaleItem.objects.get(sale=instance,
                                                    product=product).qty
                stock = product.stock + prev_qty

                product_qty = value['qty']
                if product_qty > stock:
                    stock_ok = False
                    error_message += "%s has only %s in stock, You entered %s qty" % (
                        product.name, str(stock), str(qty))

            stock_ok = True
            error_message = ''
            for key, value in items.items():
                product = Product.objects.get(pk=key)
                prev_qty = 0
                if SaleItem.objects.filter(sale=instance,
                                           product=product).exists():
                    prev_qty = SaleItem.objects.get(sale=instance,
                                                    product=product).qty
                stock = product.stock + prev_qty

                product_qty = value['qty']
                if product_qty > stock:
                    stock_ok = False
                    error_message += "%s has only %s in stock, " % (
                        product.name, str(stock))

            if stock_ok:

                #update sale
                discount = form.cleaned_data['discount']

                data = form.save(commit=False)
                data.updator = request.user
                data.date_updated = datetime.datetime.now()
                data.save()

                all_subtotal = 0

                #delete previous items and update stock
                previous_sale_items = SaleItem.objects.filter(sale=instance)
                for p in previous_sale_items:
                    prev_qty = p.qty
                    update_stock(p.product.pk, prev_qty, "increase")
                previous_sale_items.delete()

                #save items
                for key, value in items.items():
                    product = Product.objects.get(pk=key)
                    qty = value["qty"]
                    price = product.price
                    sub_total = (qty * price)
                    all_subtotal += sub_total
                    SaleItem(
                        sale=data,
                        product=product,
                        qty=qty,
                    ).save()

                    update_stock(product.pk, qty, "decrease")

                total = all_subtotal - discount

                data.sub_total = all_subtotal
                data.total = total
                data.save()

                response_data = {
                    "status": "true",
                    "title": "Successfully Updated",
                    "message": "Sale Successfully Updated.",
                    "redirect": "true",
                    "redirect_url": reverse('sales:sale',
                                            kwargs={'pk': data.pk})
                }
            else:
                response_data = {
                    "status": "false",
                    "stable": "true",
                    "title": "Out of Stock",
                    "message": error_message
                }
        else:
            message = generate_form_errors(form, formset=False)
            message += generate_form_errors(sale_item_formset, formset=True)
            response_data = {
                "status": "false",
                "stable": "true",
                "title": "Form validation error",
                "message": message
            }

        return HttpResponse(json.dumps(response_data),
                            content_type='application/javascript')
    else:
        form = SaleForm(instance=instance)
        sale_item_formset = SaleItemFormset(prefix='sale_item_formset',
                                            instance=instance)
        context = {
            "form": form,
            "title": "Edit Sale #: " + str(instance.auto_id),
            "instance": instance,
            "sale_item_formset": sale_item_formset,
            "redirect": True,
            "url": reverse('sales:edit', kwargs={"pk": instance.pk}),
            "is_need_select_picker": True,
            "is_need_popup_box": True,
            "is_need_custom_scroll_bar": True,
            "is_need_wave_effect": True,
            "is_need_bootstrap_growl": True,
            "is_need_chosen_select": True,
            "is_need_grid_system": True,
            "is_need_datetime_picker": True,
            "is_need_animations": True,
        }

        return render(request, 'sales/entry.html', context)
コード例 #5
0
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)