Sunday, 2 November 2014

Add new product (add to cart) in knockout js


<script>

    var CartLine = function () {
            var self = this;

            self.TottalItemQuantity = ko.observable(0);
            self.CategoryItems = ko.observableArray([]);
            self.SubCatergoryItems = ko.observableArray([]);
            self.InvoiceItems = ko.observableArray([]);
            self.selectedDisType = ko.observable();


            var DisTypes = function (ID, Name) {

                this.DisTypeValue = ID;
                this.DisTypeName = Name;
            };

            self.DisTypeItems = ko.observable([
                new DisTypes(1, "Original"),
                new DisTypes(2, "Discounted")]);

            self.DisTypeVisible = ko.observable(true);
            self.DisButnTypeVisible = ko.observable(false);
            $.ajax({
                dataType: "JSON",
                Type: "Get",
                url: baseUri + 'api/Items/2014',
                success: function (data) {

                    self.CategoryItems.removeAll();
                    $.each(data, function (i, obj) {
                        var c = new CategoryEntity(data[i]);
                        self.CategoryItems.push(c);

                    });

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                }
            });


            self.category = ko.observable();
            self.product = ko.observable();
            self.selectedItemId = ko.observable();
            self.price = ko.observable();
            self.Deatils = ko.observable();
            self.Bags = ko.observable();
            self.Discount = ko.observable();
            self.DisTypeVisible = ko.observable();
            self.DisButnTypeVisible = ko.observable();
            self.quantity = ko.observable();

            self.subtotal = ko.computed(function () {
                if (!jQuery.isEmptyObject(self.Discount())) {
                    var cost = self.product() ? self.price() * parseInt("0" + self.quantity(), 10) : 0;
                    var discValue = (cost * self.Discount()) / 100;
                    return parseInt(cost - discValue);
                }
                else {
                    return self.product() ? self.price() * parseInt("0" + self.quantity(), 10) : 0;
                }
            });



            self.selectedItemId.subscribe(function (newselectedItemId) {
                if (newselectedItemId) {

                    $.ajax({
                        dataType: "JSON",
                        Type: "Get",
                        url: baseUri + 'api/Items/?Id=-2&id2=2014&name=' + newselectedItemId,
                        success: function (data) {
                            self.TottalItemQuantity(0);
                            self.price(0);

                            if (jQuery.isEmptyObject(data)) {
                                alert("Stock Availabilty is 0 so  you can not generate invoice for this item.")
                            }
                            self.TottalItemQuantity(data[0].RemaingQuantity);
                            self.price(data[0].Price);

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                        }
                    });
                }
            });


            self.selectedDisType.subscribe(function (newselectedDiscountType) {
                if (newselectedDiscountType) {

                    var isID = 0;
                    self.selectedItemId() ? isID = 1 : isID = 0

                    if (isID == 1) {

                        if (newselectedDiscountType == 2) {
                            $.ajax({
                                dataType: "JSON",
                                Type: "Get",
                                url: baseUri + 'api/Items/?Id=3&id2=2014&name=' + self.selectedItemId(),
                                success: function (data) {


                                    self.price(data[0].ItemPrice);

                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                                }
                            });
                        }
                        else {
                            $.ajax({
                                dataType: "JSON",
                                Type: "Get",
                                url: baseUri + 'api/Items/?Id=-2&id2=2014&name=' + self.selectedItemId(),
                                success: function (data) {

                                    self.price(0);
                                    self.price(data[0].Price);

                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                                }
                            });
                        }
                    }
                }
            });



            self.product.subscribe(function (newSubselectedCategoryName) {
                $.ajax({
                    dataType: "JSON",
                    Type: "Get",
                    url: baseUri + 'api/Items/?Id=-1&id2=2014&name=' + newSubselectedCategoryName,
                    success: function (data) {
                        self.InvoiceItems.removeAll();
                        $.each(data, function (i, obj) {
                            var c = new ItemsEntity(data[i]);
                            self.InvoiceItems.push(c);
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                    }
                });
            });


            // Whenever the category changes, reset the product selection
            self.category.subscribe(function (newselectedCategoryName) {
                self.selectedDisType(1);
                self.product(undefined);

                if (newselectedCategoryName == "Finished Goods") {

                    self.DisTypeVisible(true);
                    self.DisButnTypeVisible(false);
                } else {

                    self.DisTypeVisible(false);
                    self.DisButnTypeVisible(true);
                }

                $.ajax({
                    dataType: "JSON",
                    Type: "Get",
                    url: baseUri + 'api/Items/?Id=-1&name=' + newselectedCategoryName,
                    success: function (data) {
                        self.SubCatergoryItems.removeAll();
                        $.each(data, function (i, obj) {
                            var c = new SubCategoryEntity(data[i]);
                            self.SubCatergoryItems.push(c);
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Failed to get Details . </br>" + errorThrown + ". </br>" + "\n" + JSON.parse(jqXHR.responseText).Message + ". </br>" + "\nPlease try again.", true);
                    }
                });

            });
        };



        var total;
        var finaltotal;
        var Cart = function () {
            // Stores an array of lines, and from these, can work out the grandTotal
            var self = this;
            self.content = ko.observable();
            self.invoiceID = ko.observable();
            self.availableCustomers = ko.observableArray([]);
            self.selectedCustomerName = ko.observable();
            self.TotalInvoiceAmount = ko.observable();

           
            self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
            self.grandTotal = ko.computed(function () {
                total = 0;
                $.each(self.lines(), function () { total += this.subtotal() })
                calFinalTotal();
                return total;
            });
            //06/09/2014


                        // Operations
            self.addLine = function () { self.lines.push(new CartLine()) };
            self.removeLine = function (line) { self.lines.remove(line) };
            self.save = function () {
                self.content.loading = ko.observable(true);
                if (self.grandTotal() != 0 && self.grandTotal() && $('#hfCompanyId').val() != "") {

                    //var InvoiceAmount = Math.round(self.grandTotal());

                    var InvoiceAmount = Math.round(finaltotalamount);

                    //alert("FinalInvoiceAmount" + finaltotalamount);
                    $.map(self.lines(), function (line) {

                        if (line.subtotal() != 0 && line.subtotal()) {
                            if (line.TottalItemQuantity() == 0) {
                                InvoiceAmount = InvoiceAmount - line.subtotal();
                            }
                        }

                    });


                    var CustomerID = $('#hfCompanyId').val();
                    var InvoiceDate;
                    if ($("#datepicker").val().length > 0) {
                        InvoiceDate = $("#datepicker").val();
                    } else {
                        InvoiceDate = "01/01/2000";
                    }

                    var pID = 0;

                    var ctype = "C";
                    if (InvoiceAmount != 0) {

                        $.ajax({
                            type: "POST",
                            url: baseUri + 'api/Invoice/?id=' + CustomerID + '&date=' + InvoiceDate + '&amount=' + InvoiceAmount + '&Type=' + ctype + '&PurchaseInvoiceId=' + pID + '&Id2=1',
                            success: function (data) {
                                self.invoiceID = data;
                                setInvoiceItems(data);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert("Failed to get Details ." + errorThrown + ". " + "" + JSON.parse(jqXHR.responseText).Message + "." + "Please try again.", true);
                            }
                        });
                    }
                    else {
                        alert("Please select Invoice Items Correctly");
                    }
                }
                else {
                    if ($('#hfCompanyId').val() == "") {
                        alert("Please select Company Name ");
                        $('#CompanyName').focus();
                    }
                    else {
                        alert("Please select Invoice Items Correctly");
                    }
                }

                setInvoiceItems = function (InvoiceID) {
                    if (InvoiceID > 0) {
                        $.map(self.lines(), function (line) {

                            if (line.subtotal() != 0 && line.subtotal()) {
                                if (line.TottalItemQuantity() != 0) {
                                    line.product() ? $.ajax({
                                        type: "POST",
                                        data: {
                                            InvoiceID: InvoiceID,
                                            InvoiceItem1: line.selectedItemId(),
                                            InvoiceDeatils: line.Deatils(),
                                            ItemQuantity: line.quantity(),
                                            ItemPrice: line.price(),
                                            TotalCost: line.subtotal(),
                                            Bags: line.Bags(),
                                            Discount: line.Discount()
                                        },
                                        url: baseUri + 'api/Invoice/-1',
                                        success: function (data) {

                                        },
                                        error: function (jqXHR, textStatus, errorThrown) {
                                            alert("Failed to get Details ." + errorThrown + ". " + "" + JSON.parse(jqXHR.responseText).Message + "." + "Please try again.", true);
                                        }
                                    }) : undefined
                                }
                            }

                        });
                        $("#totalInvoicee").text(InvoiceID);
                        $("#dialogInsertedSuccess").dialog({

                            buttons: {
                                "OK": function () {

                                    $(this).dialog("close");
                                    self.Clear();
                                }
                            }
                        }).prev(".ui-dialog-titlebar").css("background", "#e5412d");
                    }
                }
                self.content.loading = ko.observable(false);
            };

            self.Clear = function () {
                location.reload();
            }
        };

    </script>
<table class="footable table table-striped table-bordered table-white table-primary">
                    <thead>
                        <tr>
                            <th>Category Name</th>
                            <th>Sub Category Name</th>
                            <th>Item Name</th>
                            <th>Details</th>
                            <th>Stock</th>
                            <th>Bags</th>
                            <th>Quantity</th>
                            <th>Type</th>
                            <th>Price</th>
                            <th>Discount %</th>
                            <th>Amount</th>
                            <th></th>
                        </tr>
                    </thead>

                    <tbody data-bind='foreach: lines'>
                        <tr>
                            <td class="value">
                                <select data-bind='options: CategoryItems, optionsText: "name", optionsValue: "name", optionsCaption: "Select...", value: category' name="name" id="name1" class="input-medium"></select>
                            </td>
                            <td>
                                <select data-bind='options: SubCatergoryItems, optionsText: "name", optionsValue: "name", optionsCaption: "Select...", value: product' name="name" id="Select3" class="input-medium"></select>
                            </td>

                            <td>
                                <select data-bind='options: InvoiceItems, optionsText: "ItemName", optionsValue: "ItemID", value: selectedItemId' name="name" id="Select1" class="input-small"></select>
                            </td>

                            <td>
                                <textarea data-bind='visible: product, value: Deatils' class="input-small" name="message" id="InvoiceDeatils" rows="1"></textarea>
                            </td>

                            <td>
                                <input type="text" data-bind='visible: product, value: TottalItemQuantity' class="input-mini" id="totalQuantity" name="name" readonly="true">
                            </td>

                            <td>
                                <input data-bind='visible: product, value: Bags' class="input-mini" id="bags" name="name" />
                            </td>

                            <td>
                                <input data-bind='visible: product, value: quantity, valueUpdate: "afterkeydown"' class="input-mini" id="Quantity" name="name" />
                            </td>

                            <td>
                                <select data-bind='visible: DisTypeVisible, options: DisTypeItems, optionsText: "DisTypeName", optionsValue: "DisTypeValue", value: selectedDisType' name="name" id="DisType" class="input-small"></select>
                                <input data-bind="visible: DisButnTypeVisible, click: ViewSelectThing" type="button" class="btn btn-primary" value="View">
                            </td>

                            <td>
                                <input type="text" id="txtPrice" data-bind="visible: product, value: price" class="input-mini" />
                                <%--<span data-bind='text: formatCurrency(price)'> </span>--%>
                            </td>
                            <td>
                                <input type="text" id="txtDiscount" data-bind='visible: product, value: Discount, valueUpdate: "afterkeydown"' class="input-mini" />
                            </td>

                            <td class="value">
                                <%--<span data-bind='visible: product, text: formatCurrency(subtotal())'></span>--%>
                                <span data-bind="visible: product, text: subtotal()" class="input-small" id="TotalAmount"></span>
                            </td>
                            <td>
                                <a href='#' data-bind='click: $parent.removeLine'>Remove</a>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div style="float: right; margin-right: 100px" class="image" data-bind="visible: content.loading"></div>
                <div data-bind="text: content"></div>
                <p class='grandTotal'>
                    Total value: <span data-bind='text: formatCurrency(grandTotal())'></span>
                </p>
                <p class='grandTotal'>
                    Final Total value: <span id="txtGrandTotal"></span>
                </p>
                <button data-bind='click: addLine' class="btn btn-primary">Add product</button>

                <button data-bind='click: save' class="btn btn-primary">Submit order</button>

No comments:

Post a Comment