Subversion Repositories SmartDukaan

Rev

Rev 35458 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(function () {
    //Price change handler
    $(document).on('change', "form#cd input.unitPrice, form#cd input.discount", function () {
        var $row = $(this).closest('tr'); // Get the closest <tr> parent of the changed input
        var unitPrice = parseFloat($row.find('input.unitPrice').val());

        if (isNaN(unitPrice)) {
            unitPrice = 0;
        }
        var discount = parseFloat($row.find('input.discount').val());
        var maxDiscount = parseFloat($row.find('input.discount').data('maxdiscount'));
        if (isNaN(discount)) {
            discount = 0;
        }
        if (isNaN(maxDiscount)) {
            maxDiscount = 0;
        }
        if (discount > maxDiscount) {
            alert("Discount can't be greater than max Discount");
            $row.find('input.discount').val(maxDiscount);
            $(this).focus();
            return;
        }
        if (unitPrice < 0 || (unitPrice > 0 && unitPrice - discount < 0)) {
            alert("Invalid unit/discount price");
            $(this).focus();
            return;
        }
        let lines = $("#order-items").find('tbody>tr:gt(0)').length;
        if (lines > 3) {
            calculateTotalAmount($row);
        } else {
            calculateTotalAmount();
        }
        $row.find('.mk_check_plans').trigger('click', ['manual']); // Trigger the button within the same row
    });

    $(document).on('click', ".upgrade-offer", function () {
        var itemId = $(this).data('itemid');
        doGetAjaxRequestHandler(`${context}/getItemWiseUpgradeOffer?itemId=` + itemId, function (response) {
            $('#upgradeOfferModal .modal-content').html(response);
        });
    });


    $(document).on('change', "form#cd input.insuranceamount", function () {
        calculateTotalAmount();
    });

    $(document).on('click', ".create-order", function () {
        checkout("main-content");
    });

    $(document).on('click', ".mk_check_plans", function (event, source) {
        console.log("checkPlansssssss99999");
        let lines = $("#order-items").find('tbody>tr:gt(0)').length;
        if (lines > 3) {
            //No need to check plans
            return;
        }
        $('div.itemdetails').find('input').val('');
        let price = mop;
        var mop = parseFloat($(this).data("mop"));
        var sellingPrice = $(this).val();
        var itemId = $(this).closest(".input-group").find("input.insuranceamount").attr("itemid");
        if (!isNaN(sellingPrice) && parseFloat(sellingPrice) >= mop) {
            price = parseFloat(sellingPrice);
        } else {
            price = mop;
        }
        var poiId = parseFloat($(this).closest("tr").find("input.poiId").val());
        var discount = parseFloat($(this).closest("tr").find("input.discount").val());
        if (!isNaN(discount)) {
            price = price - discount;
        }
        let that = this;
        doGetAjaxRequestHandler(`${context}/checkplans?price=${price}&itemId=${itemId}&poiId=${poiId}`, function (response) {
            var obj = JSON.parse(response);
            if (obj != null) {
                getInsurancePlansModal(obj, that, price, itemId);
                return;
            } else {
                if (typeof source === "undefined") {
                    alert("Product is not eligible for insurance");
                }
            }
        });
    });

});

class InsuranceElement extends React.Component {

    planChecked;

    constructor(props) {
        super(props);
        this.state = {
            quotedPlans: {}
        };
    }

    render() {
        console.log(this.props);
        return <table className="table table-sm">
            <thead>
            <tr>
                <th>Plan Name</th>
                <th>Duration</th>
                <th>DP</th>
                <th>Selling Price</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            {Object.keys(this.props.plans).map((planName, i) =>
                this.props.plans[planName].map((plan, j) => {
                    const quoted = this.state.quotedPlans[plan.productId];
                    const isQuoted = !!quoted;
                    const displayPremium = isQuoted ? quoted.premium : (plan.premium || 0);
                    const displayDP = isQuoted ? quoted.dp : (plan.dp || 0);

                    return (
                        <tr key={`${i}-${j}`}>
                            <td>
                                {plan.providerId == 6 ? (
                                    <div style={{textAlign: "center"}}>
                                        <img
                                            src="/resources/images/ProtectPlusLogo2.jpg"
                                            style={{height: "70px"}}
                                            alt="ProtectPlus"
                                        />
                                        <div style={{fontSize: "13px", marginTop: "4px", color: "#666"}}>
                                            4% margin
                                        </div>
                                    </div>
                                ) : (
                                    planName
                                )}

                            </td>

                            <td>{plan.duration}</td>
                            <td>{displayDP ? displayDP.toFixed(2) : "-"}</td>
                            <td>{displayPremium ? displayPremium.toFixed(2) : "-"}</td>

                            <td>
                                {isQuoted || (plan.dp > 0 && plan.premium > 0) ? (
                                    <button
                                        className="btn btn-primary"
                                        data-key={plan.productId}
                                        data-amount={isQuoted ? quoted.premium.toFixed(2) : plan.premium.toFixed(2)}
                                        data-correlationid={isQuoted ? quoted.correlationId : plan.correlationId}
                                        onClick={this.planChecked}
                                    >
                                        Add
                                    </button>
                                ) : (
                                    <button className="btn btn-warning"
                                            onClick={(e) => this.checkQuote(e, plan, planName)}>
                                        Check Quote
                                    </button>
                                )}
                            </td>
                        </tr>
                    );
                })
            )}
            </tbody>

        </table>;
    }

    /* planChecked = (e) => {
         //debugger;
         let $itemDetails = $('div.itemdetails');
         if ($itemDetails.find('.dgram').val() === '') {
             bootbox.alert('Mobile RAM is required');
             return;
         }
         if ($itemDetails.find('.dgmemory').val() === '') {
             bootbox.alert('Mobile Memory is required');
             return;
         }
         if ($itemDetails.find('#dgmfgdate').val() === '') {
             bootbox.alert('Mobile Mfg Date is required');
             return;
         }
         let $orderItemRow = $(this.props.elePlanCheckedOn).closest('td');
         $orderItemRow.find('.insuranceid').val($(e.target).data('key'));
         $orderItemRow.find('.correlationid').val($(e.target).data('correlationid'));
         $orderItemRow.find('.insuranceamount').val($(e.target).data('amount'));
         $orderItemRow.find('.ram').val($itemDetails.find('.dgram').val());
         $orderItemRow.find('.memory').val($itemDetails.find('.dgmemory').val());
         // $orderItemRow.find('.mfgdate').val(window.mfgDate);
         $orderItemRow.find('.mfgdate').val($itemDetails.find('.dgmfgdate').val());
         $('#mobilePlansModal').modal('hide');
         calculateTotalAmount();
     }*/

    planChecked = (e) => {
        let $itemDetails = $('div.itemdetails');

        if ($itemDetails.find('.dgram').val() === '') {
            bootbox.alert('Mobile RAM is required');
            return;
        }
        if ($itemDetails.find('.dgmemory').val() === '') {
            bootbox.alert('Mobile Memory is required');
            return;
        }
        if ($itemDetails.find('#dgmfgdate').val() === '') {
            bootbox.alert('Mobile Mfg Date is required');
            return;
        }

        let $orderItemRow = $(this.props.elePlanCheckedOn).closest('td');

        // read existing values
        let existingIds = $orderItemRow.find('.insuranceid').val() || "";
        let existingAmounts = $orderItemRow.find('.insuranceamount').data('all-amounts') || ""; // store individual amounts in data attribute
        let existingCorrelation = $orderItemRow.find('.correlationid').val() || "";

        // new selected values
        let newId = $(e.target).data('key');
        let newAmount = $(e.target).data('amount');
        let newCorrelation = $(e.target).data('correlationid');

        // append IDs
        let updatedIds = existingIds ? existingIds + "," + newId : newId;

        // append individual amounts (for tooltip)
        let updatedAmountsList = existingAmounts ? existingAmounts + "," + newAmount : newAmount;

        // calculate total
        let totalAmount = updatedAmountsList.split(',').reduce((sum, val) => sum + parseFloat(val || 0), 0);

        // correlation ID logic
        let updatedCorrelation = existingCorrelation;
        if (newCorrelation && newCorrelation.trim() !== "") {
            updatedCorrelation = newCorrelation;
        }

        // assign back
        $orderItemRow.find('.insuranceid').val(updatedIds);
        $orderItemRow.find('.insuranceamount').val(totalAmount.toFixed(2))  // sum total
            .data('all-amounts', updatedAmountsList)                          // save individual amounts
            .attr('title', updatedAmountsList);                               // tooltip for user
        $orderItemRow.find('.correlationid').val(updatedCorrelation);
        $orderItemRow.find('.ram').val($itemDetails.find('.dgram').val());
        $orderItemRow.find('.memory').val($itemDetails.find('.dgmemory').val());
        $orderItemRow.find('.mfgdate').val($itemDetails.find('.dgmfgdate').val());
        $(e.target).text("Added");
        $(e.target).prop("disabled", true);
        calculateTotalAmount();
    };



    checkQuote = (e, plan, planName) => {
        //debugger;
        let $itemDetails = $('div.itemdetails');
        if ($itemDetails.find('.dgram').val() === '') {
            bootbox.alert('Mobile RAM is required');
            return;
        }
        if ($itemDetails.find('.dgmemory').val() === '') {
            bootbox.alert('Mobile Memory is required');
            return;
        }
        if ($itemDetails.find('#dgmfgdate').val() === '') {
            bootbox.alert('Mobile Mfg Date is required');
            return;
        }
        let planCode = plan.productId;
        let manuFacturedDate = $itemDetails.find('.dgmfgdate').val();
        this.calculateQuote(planCode, this.props.itemId, this.props.devicePrice, manuFacturedDate, planName);

    }

    calculateQuote = (planCode, itemId, devicePrice, manuFacturedDate, planName) => {
        doGetAjaxRequestHandler(
            `${context}/getPlanQuote?planCode=${planCode}&itemId=${itemId}&sumInsured=${devicePrice}&manufacturedDate=${manuFacturedDate}&planName=${planName}`,
            (responseText) => {
                const response = JSON.parse(responseText);
                console.log("quote call back", response);

                if (response.afinityQuoteModel.policyStatus === "APPROVE" || response.afinityQuoteModel.message === "Success") {
                    const updatedPlan = {
                        premium: response.afinityQuoteModel.totalPremium,
                        dp: response.planDp,
                        correlationId: response.afinityQuoteModel.correlationId
                    };

                    this.setState((prevState) => ({
                        quotedPlans: {
                            ...prevState.quotedPlans,
                            [planCode]: updatedPlan
                        }
                    }));
                } else {
                    bootbox.alert("Quote failed: " + (response.afinityQuoteModel.message || "Unknown error"));
                }
            }
        );
    }
}

let reactRoot = null;

function getInsurancePlansModal(insurancePlans, elePlanCheckedOn, devicePrice, itemId) {
    const domContainer = document.querySelector('.insurancedetails');
    reactRoot = ReactDOM.createRoot(domContainer);
    reactRoot.render(<InsuranceElement plans={insurancePlans} elePlanCheckedOn={elePlanCheckedOn}
                                       devicePrice={devicePrice} itemId={itemId}/>)
    $('#mobilePlansModal').modal({show: true});

}


function calculateTotalAmount(inputEle) {
    if (typeof inputEle !== "undefined") {
        let itemId = $(inputEle).attr("itemid");
        let unitPrice = inputEle.value;
        $("#order-items").find(`input.unitPrice[itemid=${itemId}]`).each(function () {
            this.value = unitPrice;
        })

    }
    var netPayableAmount = 0;
    var totaInsuranceAmount = 0;
    $("#order-items").find('tbody>tr:gt(0)').each(function (index, el) {
        var rowTotal = 0;
        let $tr = $(el);
        var insuranceAmount = $tr.find('input.insuranceamount').val();
        if (isNaN(insuranceAmount)) {
            insuranceAmount = 0;
        } else {
            insuranceAmount = parseFloat(insuranceAmount);
        }

        var quantity = parseFloat($(el).find('.unitPrice').attr('quantity'));

        var unitPrice = parseFloat($(el).find('.unitPrice').val());
        if (isNaN(unitPrice)) {
            unitPrice = 0;
        }

        var discount = $(el).find('.discount').val();
        if (isNaN(discount)) {
            discount = 0;
        }

        rowTotal = (unitPrice - discount + insuranceAmount) * quantity;
        $tr.find('.totalPrice').val(rowTotal);
        netPayableAmount += rowTotal;
        totaInsuranceAmount += insuranceAmount;
    });
    if (totaInsuranceAmount > 0) {
        $(".mk_insurance_row").show();
    } else {
        $(".mk_insurance_row").hide();
    }
    $('#cd').find('input.netPayableAmount').val(netPayableAmount);
}

$(document).on('change', '.offerSelect', function () {
    calculateAndUpdatePaymentOptions();
});

function calculateAndUpdatePaymentOptions() {
    let totalSchemePayout = 0;
    let totalPartnerPayout = 0;

    // Loop through all selected options in each row
    $('.offerSelect').each(function () {
        let selectedOption = $(this).find('option:selected');

        let schemePayout = parseFloat(selectedOption.data('scheme-payout')) || 0;
        let partnerPayout = parseFloat(selectedOption.data('partner-payout')) || 0;

        // Accumulate the payouts
        totalSchemePayout += schemePayout;
        totalPartnerPayout += partnerPayout;
    });

    // Now update the payment options with the accumulated values
    updatePaymentOptions(totalSchemePayout, totalPartnerPayout);
}

function updatePaymentOptions(schemePayout, partnerPayout) {
    $("#payment-option-id-amount-container").find('.paymentOptionAmount').each(function () {
        let paymentOptionName = $(this).closest('.row').find('h5').text().trim();

        if (paymentOptionName.includes('SAMSUNG UPGRADE')) {
            $(this).val(schemePayout);  // Set the total scheme payout
        }

        // if (paymentOptionName.includes('CASH DISCOUNT')) {
        //     $(this).val(partnerPayout);  // Set the total partner payout
        // }
    });
}

$(document).on('click', '.reset-irn-generated-panel', function () {
    getResetIrnGeneratedPanel();
});

$(document).on('click', '#search-invoice-for-irn-reset', function () {
    var invoiceNumber = $("#search-invoice-number").val();
    if (!invoiceNumber) {
        alert("Please enter Invoice Number");
        return;
    }
    doGetAjaxRequestHandler(`${context}/getTransactionForIrnReset?invoiceNumber=${invoiceNumber}`, function (response) {
        $('#transaction-for-reset-irn-container').html(response);
    });
});

$(document).on('click', '#reset-irn-button', function () {
    if (confirm("Are you sure to Reset IRN")) {
        let invoices = [];
        $('#eligible-irn-order tbody tr').each(function () {
            const invoiceNumber = $(this).find('td:nth-child(3)').text();
            invoices.push(invoiceNumber);
        });
        const invoiceNumbers = invoices.join(', ');
        console.log('invoiceNumbersString - ', invoiceNumbers)
        let url = `${context}/resetOrdersIrn?invoiceNumbers=${invoiceNumbers}`
        doPutAjaxRequestHandler(url, function (response) {
            if (response) {
                alert(`IRN reset successfully for Invoice No - ${invoiceNumbers}`);
                getResetIrnGeneratedPanel();
            }
        });
    }
});

function getResetIrnGeneratedPanel() {
    doGetAjaxRequestHandler(`${context}/resetIrnGeneratedPanel`, function (response) {
        $('#main-content').html(response);
    });
}