Checkout actions using suitelet

Jira Code: OSI-54

The script is used to accomplish the different actions in the checkout page of the site. Which create an estimate, create sales order, set shipping address details, fetch shipping address at different context. This also finds the shipping cost for each shipping methods of CANADA and USA by creating an estimate for each case. If the payment actions like credit card, paypal are initiated from the site, then the script will trigger and a sales order will be created and the payment response will set in the sales order.

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**
 * Script Description
 * This script is to handle checkout feature for normal customers who are unqualified for
 * paid order ; 
 * 
 * Created on 22-feb-2019 by J&J
 */
/*******************************************************************************
 * * OneSource IML | Aquverse *
 * **************************************************************************
 * 
 * 
 * Author:  Jobin & Jismi IT Services LLP
 * 
 * REVISION HISTORY
 * 
 * 
 ******************************************************************************/

/**
 *  SCRIPT ID : customscriptosi_52_jj_sl_aquverse_checko
 *  
 *  DEPLOYMENT ID : customdeploy_osi_52_jj_sl_aquv_check_out 
 *  
 */


var CONTEXT;
define(['N/record', 'N/search', 'N/file', 'N/runtime', 'N/http', 'N/https', 'N/url', 'N/email', 'N/log'],
    function(record, search, file, runtime, http, https, url, email, log) {
        //To check whether a value exists in parameter
        function checkForParameter(parameter, parameterName) {
            if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && parameter != " " && parameter != false) {
                return true;
            } else {
                if (parameterName)
                    log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                return false;
            }
        }

        //To assign a default value if the it is empty
        function assignDefaultValue(value, defaultValue) {
            if (checkForParameter(value))
                return value;
            else 
                return defaultValue;
        }

        /*To round a float number */
        function roundFloat(value, decimals) {
            return Number(Math.round(parseFloat(value) + 'e' + parseInt(decimals)) + 'e-' + parseInt(decimals));
        }
        /*To fix a float number to specified decimal parts */
        function fixFloat(value, decimals) {
            return roundFloat(parseFloat(value), parseInt(decimals)).toFixed(parseInt(decimals));
        }

        //To encode/decode a string into BASE64
        function encodeAndDecodeString(inputString, isEncode) {
            try {
                var Base64 = {
                    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
                    encode: function(e) {
                        var t = "";
                        var n, r, i, s, o, u, a;
                        var f = 0;
                        e = Base64._utf8_encode(e);
                        while (f < e.length) {
                            n = e.charCodeAt(f++);
                            r = e.charCodeAt(f++);
                            i = e.charCodeAt(f++);
                            s = n >> 2;
                            o = (n & 3) << 4 | r >> 4;
                            u = (r & 15) << 2 | i >> 6;
                            a = i & 63;
                            if (isNaN(r)) {
                                u = a = 64
                            } else if (isNaN(i)) {
                                a = 64
                            }
                            t = t + this._keyStr.charAt(s) +
                                this._keyStr.charAt(o) +
                                this._keyStr.charAt(u) +
                                this._keyStr.charAt(a)
                        }
                        return t
                    },
                    decode: function(e) {
                        var t = "";
                        var n, r, i;
                        var s, o, u, a;
                        var f = 0;
                        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
                        while (f < e.length) {
                            s = this._keyStr.indexOf(e.charAt(f++));
                            o = this._keyStr.indexOf(e.charAt(f++));
                            u = this._keyStr.indexOf(e.charAt(f++));
                            a = this._keyStr.indexOf(e.charAt(f++));
                            n = s << 2 | o >> 4;
                            r = (o & 15) << 4 | u >> 2;
                            i = (u & 3) << 6 | a;
                            t = t + String.fromCharCode(n);
                            if (u != 64) {
                                t = t + String.fromCharCode(r)
                            }
                            if (a != 64) {
                                t = t + String.fromCharCode(i)
                            }
                        }
                        t = Base64._utf8_decode(t);
                        return t
                    },
                    _utf8_encode: function(e) {
                        e = e.replace(/rn/g, "n");
                        var t = "";
                        for (var n = 0; n < e.length; n++) {
                            var r = e.charCodeAt(n);
                            if (r < 128) {
                                t += String.fromCharCode(r)
                            } else if (r > 127 && r < 2048) {
                                t += String.fromCharCode(r >> 6 | 192);
                                t += String.fromCharCode(r & 63 | 128)
                            } else {
                                t += String.fromCharCode(r >> 12 | 224);
                                t += String.fromCharCode(r >> 6 & 63 | 128);
                                t += String.fromCharCode(r & 63 | 128)
                            }
                        }
                        return t
                    },
                    _utf8_decode: function(e) {
                        var t = "";
                        var n = 0;
                        var r = c1 = c2 = 0;
                        while (n < e.length) {
                            r = e.charCodeAt(n);
                            if (r < 128) {
                                t += String.fromCharCode(r);
                                n++
                            } else if (r > 191 && r < 224) {
                                c2 = e.charCodeAt(n + 1);
                                t += String.fromCharCode((r & 31) << 6 | c2 &
                                    63);
                                n += 2
                            } else {
                                c2 = e.charCodeAt(n + 1);
                                c3 = e.charCodeAt(n + 2);
                                t += String.fromCharCode((r & 15) << 12 |
                                    (c2 & 63) << 6 | c3 & 63);
                                n += 3
                            }
                        }
                        return t
                    }
                }
                inputString = inputString.toString();
                if (isEncode)
                    return Base64.encode(inputString);
                else
                    return Base64.decode(inputString);
            } catch (err) {
                log.debug("Error ", "Error at function encodeAndDecodeString()");
                return false;
            }
        }
        //custom encryption module
        var encryptionModule = {
            encrypt: function(key, value) {
                var result = "";
                for (i = 0; i < value.length; ++i) {
                    result += String.fromCharCode(key[i % key.length] ^ value.charCodeAt(i));
                }
                return result;
            },
            decrypt: function(key, value) {
                var result = "";
                for (i = 0; i < value.length; ++i) {
                    result += String.fromCharCode(key[i % key.length] ^ value.charCodeAt(i));
                }
                return result;
            },
            encode: function(k, s) {
                var enc = "";
                var str = "";
                // make sure that input is string
                str = s.toString();
                for (var i = 0; i < s.length; i++) {
                    // create block
                    var a = s.charCodeAt(i);
                    // bitwise XOR
                    var b = a ^ k;
                    enc = enc + String.fromCharCode(b);
                }
                return enc;
            },
            finalResult: function(key, value, times, type, index) {
                times = encryptionModule.assignDefaultValue(times, 1);
                index = encryptionModule.assignDefaultValue(index, 1);
                key = key.toString();
                var radKey = parseInt((parseFloat(key) * times * encryptionModule.giveNumberCode(index.toString())) / 1000000000);
                radKey = encryptionModule.giveNumberCode(radKey.toString());
                if (times > index)
                    return encryptionModule.finalResult(radKey, value, times, type, index + 1);
                if (type == 'encrypt' || type == 1)
                    for (var i = 0; i < times; i++)
                        if (i % 2 == 0)
                            value = encryptionModule.encode(key, value);
                        else
                            value = encryptionModule.encrypt(encryptionModule.giveNumberCode(key), value);
                else if (type == 'decrypt' || type == 2)
                    for (var i = 0; i < times; i++)
                        if (i % 2 == 0)
                            value = encryptionModule.encode(key, value);
                        else
                            value = encryptionModule.decrypt(encryptionModule.giveNumberCode(key), value);
                else
                    for (var i = 0; i < times; i++)
                        value = encryptionModule.encode(key, value);

                return value;
            },
            processData: function(key, value, type) {
                key = key.toString();
                value = value.toString();
                if (type == 'encrypt' || type == 1) {
                    value = encryptionModule.encrypt(key, value);
                    value = encryptionModule.encrypt(encryptionModule.giveNumberCode(key).toString(), value);
                } else if (type == 'decrypt' || type == 2) {
                    value = encryptionModule.decrypt(encryptionModule.giveNumberCode(key).toString(), value);
                    value = encryptionModule.decrypt(key, value);
                } else
                    value = encryptionModule.encode(key, value);
                return value;
            },
            giveNumberCode: function(someString) {
                var letters = ["d", "e", "g", ";", "w", "o", "q", "5", "p", ".", "*", "a", "2", "/", "z", "3", "l", "+", "m", "%", "4", "'", "b", "c", "7", "s", "8", "r", "u", "-", "v", "y", "t", "0", "@", "1", "f", ":", "6", "h", "i", ",", "n", " ", "x", "j", "k", "9"];

                var numberCode = "";
                for (var i = 0; i < someString.length; i++) {
                    var letter = someString[i].toLowerCase();
                    var number = letters.indexOf(letter) + 1;
                    if (number < 10) {
                        number = "0" + number;
                    }
                    numberCode += number;
                }
                numberCode = ((numberCode * 3.14159265359) / 2.22144146908) * 2.64575131106;
                if (numberCode.toString().split(".")[1]) {
                    if (numberCode.toString().split(".")[1].length > 5) {
                        numberCode = numberCode.toString().split(".")[1];
                    }
                }
                numberCode = parseInt(numberCode) % 1000000;
                return numberCode;
            },
            checkForParameter: function(parameter) {
                if (parameter != "" && parameter != null && parameter != undefined && parameter != "undefined" && parameter != " " && parameter != false) {
                    return true;
                } else {
                    if (paremeterName)
                        console.log('Empty Value found', 'Empty Value for parameter ' + paremeterName);
                    return false;
                }
            },
            assignDefaultValue: function(value, defaultValue) {
                if (encryptionModule.checkForParameter(value))
                    return value;
                else
                    return defaultValue;
            },
            encodedEncryption: function(key, value) {
                return encodeAndDecodeString(encryptionModule.encrypt(key, value), true);
            },
            decodedDecryption: function(key, value) {
                return encryptionModule.decrypt(key, encodeAndDecodeString(value, false));
            }
        };



        //main or root object for this entire suitelet scritpt
        var main = {
            routeRequest: function(context) {
                log.debug('context.request.method', context.request.method);
                if (checkForParameter(context.request.parameters.status)) {
                    var status = context.request.parameters.status;
                    log.debug('status', status);
                    if (checkForParameter(context.request.parameters.callback)) {
                        if (status == 'fetchinfo')
                            return main.fetchAddressDetails(context);
                        else if (status == 'updateaddr')
                            return main.handleUpdateAddress(context);
                        else if (status == 'issameaddr')
                            return main.handleSetBillingAsShipping(context);
                        else if (status == 'createestimate')
                            return main.handlecreateEstimate(context);
                        else if (status == 'placeorder')
                            return main.handleCreateSalesOrder(context);
                        else
                            return main.sendResponse('FAILURE', escape('INVALID STATUS'), false, escape('main.routeRequest()'), context);
                    } else if (status == 'clearpaidcart') {
                        return main.handleClearPaidShoppingCart(context);
                    } else
                        return false;
                } else
                    return false;
            },
            handlecreateEstimate: function(context) {
                log.debug('STARTS FUNCTION ', 'main.handlecreateEstimate()');
                var customerID = unescape(context.request.parameters.empid);
                var country = unescape(context.request.parameters.country);



                if (main.verifyStock(customerID, context)) {
                    customerID = (customerID.toString()).trim();
                    var shippingMethods = {};

                    if (country == 'United States') { //United States
                        shippingMethods = {

                            '0': { id: 3252, text: 'Fedex Ground', shippingcost: null },
                            '1': { id: 2, text: 'Fedex 1 Day', shippingcost: null },
                            '2': { id: 100, text: 'Fedex 2 Day', shippingcost: null },
                            '3': { id: 204, text: 'USPS First-Class Parcel', shippingcost: null }
                        };

                    } else if (country == 'Canada') { //Canada

                        shippingMethods = {
                            '0': { id: 4415, text: 'Fedex International Ground', shippingcost: null },
                            '1': { id: 4404, text: 'USPS Priority Mail', shippingcost: null }
                        };

                    }


                    /*if (country == 'United States') { //United States
                        shippingMethods = {

                            '0': { id: 3252, text: 'Fedex Ground', shippingcost: null },
                            '1': { id: 2, text: 'Fedex 1 Day', shippingcost: null },
                            '2': { id: 100, text: 'Fedex 2 Day', shippingcost: null },
                            '3': { id: 204, text: 'USPS First-Class Parcel', shippingcost: null }
                        };

                    } else if (country == 'Canada') { //Canada

                        shippingMethods = {
                            '0': { id: 4415, text: 'Fedex International Ground', shippingcost: null },
                            '1': { id: 4404, text: 'USPS Priority Mail', shippingcost: null },
                            '2': { id: 3252, text: 'Fedex Ground', shippingcost: null }
                        };

                    }*/

                    var customerObj = main.runCustomerSearch(customerID);
                    if (customerObj.length > 0) {
                        var paidShoppingCartObj = main.searchPaidShoppingCartItems(customerID);
                        log.debug('paidShoppingCartObj', paidShoppingCartObj);
                        if (paidShoppingCartObj.length > 0) {

                            responseArray = main.createEstimate(customerID, customerObj[0], paidShoppingCartObj, true, shippingMethods);

                            if (checkForParameter(responseArray)) {
                                var callBackFunction = context.request.parameters.callback;
                                var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                                context.response.write(responseStrJson);
                                return true;
                            }
                            return false;
                        } else
                            return main.sendResponse('FAILURE', escape('EMPTY PAID CART'), false, escape('main.handlecreateEstimate()'), context);
                    } else
                        return main.sendResponse('FAILURE', escape('INVALID CUSTOMER ID'), false, escape('main.handlecreateEstimate()'), context);
                } else {

                    return main.sendResponse('FAILURE', escape('OUT OF STOCK'), false, escape('main.handlecreateEstimate()'), context);
                }
            },
            runCustomerSearch: function(INTERNAL_ID) {
                if (!checkForParameter(INTERNAL_ID))
                    return [];
                var customerSearchObj = new Array();
                customerSearchObj = search.create({
                    type: search.Type.CUSTOMER,
                    title: 'Search for Customer Details',
                    filters: [
                        ["status", "anyof", "13"], // 13 - Customer-Customer Closed (Won)
                        "AND", ["internalid", "anyof", INTERNAL_ID]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.DESC,
                            label: "Internal ID"
                        }),
                        search.createColumn({ name: "altname", label: "Name" }),
                        search.createColumn({ name: "email", label: "Email" }),
                        search.createColumn({ name: "phone", label: "Phone" }),
                        search.createColumn({ name: "shipaddress", label: "Shipping Address" }),
                        search.createColumn({ name: "billaddress", label: "Billing Address" }),
                        search.createColumn({ name: "shipphone", label: "Shipping Phone" }),
                        search.createColumn({ name: "billphone", label: "Billing Phone" }),
                        search.createColumn({ name: "firstname", label: "First Name" }),
                        search.createColumn({ name: "lastname", label: "Last Name" })
                    ]
                }).run().getRange({
                    start: 0,
                    end: 1
                });
                return customerSearchObj;
            },
            searchPaidShoppingCartItems: function(customerID) {
                //search for all Shopping Cart Items
                if (!checkForParameter(customerID))
                    return [];
                var responseArray = new Array();
                var itemDetails = new Object();
                var shoppingCartSearchObj = search.create({
                    type: "customrecord_osi52_jj_aquverse_user_cart",
                    filters: [
                        ["custrecord_osi52_jj_sc_customer_id.internalid", "anyof", customerID]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_item_quantity", label: "Item Quantity" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_itemid", label: "Item ID" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_item_name", label: "Item Display Name" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_item_image_url", label: "Item Image URL" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_item_base_price", label: "Item Base Price" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_customer_id", label: "Customer ID" })
                    ]
                }).run().each(function(result) {
                    itemDetails.scid = (result.getValue({
                        name: "internalid"
                    }));

                    itemDetails.internalid = (result.getValue({
                        name: "custrecord_osi52_jj_sc_itemid"
                    }));

                    itemDetails.itemType = ('InvtItem');
                    itemDetails.stockAvailabilityParams = itemDetails.internalid;
                    itemDetails.itemname = (result.getText({
                        name: "custrecord_osi52_jj_sc_itemid"
                    }));


                    itemDetails.empid = (result.getValue({
                        name: "custrecord_osi52_jj_sc_customer_id"
                    }));

                    itemDetails.itemquantity = (result.getValue({
                        name: "custrecord_osi52_jj_sc_item_quantity"
                    }));

                    itemDetails.itembaseprice = (result.getValue({
                        name: "custrecord_osi52_jj_sc_item_base_price"
                    }));

                    responseArray.push(itemDetails);
                    itemDetails = undefined;
                    itemDetails = {};
                    return true;

                });

                return responseArray;
            },
            sortObjArray: function(objArray, key) {
                var keyArray = new Array();
                var customEncodeThis = function(value) {
                    return (value.toString()).toUpperCase().replace(/-/g, "00").replace(/ /g, "").replace(/:/g, "00");
                }

                for (var i = 0, len = objArray.length; i < len; i++)
                    keyArray.push(objArray[i][key]);

                keyArray.sort(function(a, b) {
                    a = customEncodeThis(a);
                    b = customEncodeThis(b);
                    if (a < b)
                        return -1;
                    if (a > b)
                        return 1;
                    return 0;
                });

                var resultArray = new Array();
                var index = 0;
                var keyArrayLen = keyArray.length;
                while (index < keyArrayLen) {
                    for (var i = 0, len = objArray.length; i < len; i++)
                        if (keyArray[index] == objArray[i][key])
                            resultArray.push(objArray[i]);
                    index++;
                }
                return resultArray;
            },
            getCartTotalQuantity: function(objArray, keyName) {
                var key = ((keyName) ? (keyName) : ('itemquantity'));
                var cartQuantity = 0;
                for (var k = 0, len = objArray.length; k < len; k++) {
                    cartQuantity += Number(objArray[k][key]);
                }
                return cartQuantity;
            }, // function(customerID, shoppingCartObj, isSaveRecord)
            verifyStock: function(customerID, context) {


                var responseArray = new Array();
                var responseObj = new Object();

                var itemID;

                //Objects to group line items 
                var lineItem = new Object();
                var lineItemID = new Object();
                var lineQuantity = new Object();
                var lineItemStockAvailability = new Object();
                var lineItemStockAvailabilityParam = new Object();

                var finalStockFlag = true;
                searchFilter = [
                    ["custrecord_osi52_jj_sc_customer_id.internalid", "anyof", customerID]
                ];

                var shoppingCartSearchObj = search.create({
                    type: "customrecord_osi52_jj_aquverse_user_cart",
                    filters: searchFilter,
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_item_quantity", label: "Item Quantity" }),
                        search.createColumn({ name: "custrecord_osi52_jj_sc_itemid", label: "Item ID" })
                    ]
                }).run().each(function(result) {

                    itemID = result.getValue({
                        name: "custrecord_osi52_jj_sc_itemid"
                    });
                    if (typeof(lineItem[itemID]) == 'undefined' || lineItem[itemID] != true) {
                        //if itemID doesn't exist -> first entry
                        lineItem[itemID] = true;
                        lineItemID[itemID] = itemID;
                        lineQuantity[itemID] = 0;
                        lineQuantity[itemID] += parseInt(result.getValue({
                            name: "custrecord_osi52_jj_sc_item_quantity"
                        }));
                        //to get stock availability
                        lineItemStockAvailabilityParam[itemID] = itemID;
                    } else {
                        //if itemID exist -> Duplicate
                        lineQuantity[itemID] += parseInt(result.getValue({
                            name: "custrecord_osi52_jj_sc_item_quantity"
                        }));
                    }
                });

                lineItemStockAvailability = main.verifyStockStatusAsBatch(lineItemStockAvailabilityParam, context);
                if (Object.keys(lineItemID).length > 0) {
                    for (var i = 0; i < Object.keys(lineItemID).length; i++) {
                        if (checkForParameter(lineItemStockAvailability[Object.keys(lineItemID)[i]], 'lineItemStockAvailability', context)) {

                            //if lineItemStockAvailability is present

                            if (parseInt(lineItemStockAvailability[Object.keys(lineItemID)[i]]) < parseInt(lineQuantity[Object.keys(lineItemID)[i]])) {

                                finalStockFlag = false;
                                break;

                            }
                        } else {
                            //if lineItemStockAvailability is not present. ie, No stock is present
                            finalStockFlag = false;
                            break;
                        }
                    }
                } else {
                    finalStockFlag = false;
                }
                if (finalStockFlag) {
                    return true;
                } else {
                    return false;
                }

            },
            verifyStockStatusAsBatch: function(itemDetails, context) {
                /* to verify stock availability of multiple items as a batch */
                function mapStockStatusWithItemElements(stockAvailability, itemDetails) {
                    try {
                        for (var key in itemDetails) {
                            if (stockAvailability[key]) {
                                itemDetails[key] = stockAvailability[key];
                                itemDetails[key] = (checkForParameter(itemDetails[key], 'itemDetails[key] ', context) ? (itemDetails[key]) : '0');
                            } else {
                                itemDetails[key] = '0';
                            }
                        }
                        return itemDetails;
                    } catch (er) {
                        log.debug('error', 'error at function verifyStockStatusAsBatch() ->  function mapStockStatusWithItemElements()');
                        return false;
                    }
                }


                var stockAvailability = new Object();
                var itemArray = new Array();
                var itemRecord;

                for (var key in itemDetails) {
                    //for Normal Items -> Inventory Items
                    itemArray.push(parseInt(itemDetails[key]));
                }


                itemArray.push(4395, 4467, 7044, 4403);
                var kitItem = { //inv item: kit item
                    '4395': '4468',
                    '4467': '4469',
                    '7044': '7068',
                    '4403': '5925'
                };

                if (checkForParameter(itemArray, 'itemArray', context)) {
                    itemRecord = search.create({
                        type: "inventoryitem",
                        filters: [
                            ["type", "anyof", "InvtPart"],
                            "AND", ["inventorylocation", "anyof", "1"], //1-Denver
                            "AND", ["internalid", "anyof", itemArray],
                        ],
                        columns: [
                            "internalid",
                            "itemid",
                            "locationquantityavailable",
                            "baseprice"
                        ]
                    }).run().each(function(result) {
                        stockAvailability[result.getValue({ name: 'internalid' })] = result.getValue({ name: 'locationquantityavailable' });
                        if (kitItem[result.getValue({ name: 'internalid' })])
                            stockAvailability[kitItem[result.getValue({ name: 'internalid' })]] = result.getValue({ name: 'locationquantityavailable' });
                        return true;
                    });
                }
                itemDetails = mapStockStatusWithItemElements(stockAvailability, itemDetails);
                return itemDetails;

            },
            createEstimate: function(customerID, customerObj, shoppingCartObj, isSaveRecord, shippingMethods) {

                var responseObj = new Object();
                var responseArray = new Array();
                var recordExist = false;
                var estimateRecordID;


                for (var k in shippingMethods) {

                    if (!recordExist) {
                        var estimateObjRecord = record.transform({
                            fromType: record.Type.CUSTOMER,
                            fromId: customerID,
                            toType: record.Type.ESTIMATE,
                            isDynamic: true,
                        });
                        estimateObjRecord.setValue({
                            fieldId: 'customform',
                            value: 224 // value":"224","text":"OS Sales Estimate
                        });

                        estimateObjRecord.setValue({
                            fieldId: 'shipcarrier',
                            value: 'nonups',
                            ignoreFieldChange: false
                        });

                        estimateObjRecord.setValue({
                            fieldId: 'shipmethod',
                            value: shippingMethods[k].id, //shippingMethod,
                            ignoreFieldChange: false
                        });


                        responseObj.billaddress = escape(estimateObjRecord.getValue({
                            fieldId: 'billaddress'
                        }));
                        responseObj.shipaddress = escape(estimateObjRecord.getValue({
                            fieldId: 'shipaddress'
                        }));
                        responseObj.shipphone = escape(customerObj.getValue({
                            name: 'shipphone'
                        }));
                        responseObj.billphone = escape(customerObj.getValue({
                            name: 'billphone'
                        }));
                        responseObj.phone = escape(customerObj.getValue({
                            name: 'phone'
                        }));
                        responseObj.shipcarrierValue = escape(estimateObjRecord.getValue({
                            fieldId: 'shipcarrier'
                        }));
                        responseObj.shipcarrierText = escape(estimateObjRecord.getText({
                            fieldId: 'shipcarrier'
                        }));
                        responseObj.shipmethodValue = escape(estimateObjRecord.getValue({
                            fieldId: 'shipmethod'
                        }));
                        responseObj.shipmethodText = escape(estimateObjRecord.getText({
                            fieldId: 'shipmethod'
                        }));


                        //if estimate record is to be saved
                        // if (isSaveRecord) {
                        //to sort shoppingCartObj based on itemid/itemname

                        shoppingCartObj = main.sortObjArray(shoppingCartObj, 'itemname');

                        //to add line items
                        for (var i = 0, len = shoppingCartObj.length; i < len; i++) {
                            estimateObjRecord.selectNewLine({
                                sublistId: 'item'
                            });


                            estimateObjRecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'item',
                                value: shoppingCartObj[i].internalid,
                                ignoreFieldChange: false
                            });

                            estimateObjRecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'quantity',
                                value: shoppingCartObj[i].itemquantity,
                                ignoreFieldChange: false
                            });
                            estimateObjRecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'istaxable',
                                value: true,
                                ignoreFieldChange: false
                            });
                            estimateObjRecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'isclosed',
                                value: true,
                                ignoreFieldChange: false
                            });
                            estimateObjRecord.commitLine({
                                sublistId: 'item'
                            });

                        }

                        try {
                            //Saving Estimate Record
                            estimateRecordID = estimateObjRecord.save({
                                enableSourcing: true,
                                ignoreMandatoryFields: false
                            });
                            log.debug('temp estimateRecordID', estimateRecordID);

                        } catch (e) {
                            log.debug({
                                title: e.name,
                                details: e.message
                            });
                        }


                    }


                    if (estimateRecordID && !recordExist) {
                        recordExist = true;

                        //Load created Sales Order so that we can fetch data
                        estimateObjRecord = record.load({
                            type: record.Type.ESTIMATE,
                            id: estimateRecordID,
                            isDynamic: true
                        });

                        shippingMethods[k].shippingcost = escape(estimateObjRecord.getValue({
                            fieldId: 'shippingcost'
                        }));

                        // responseObj.tempestimateid = escape(estimateRecordID);
                        shippingMethods[k].subtotal = escape(estimateObjRecord.getValue({
                            fieldId: 'subtotal'
                        }));
                        shippingMethods[k].discounttotal = escape(estimateObjRecord.getValue({
                            fieldId: 'discounttotal'
                        }));
                        shippingMethods[k].item_total = escape(estimateObjRecord.getValue({
                            fieldId: 'item_total'
                        }));
                        shippingMethods[k].taxtotal = escape(estimateObjRecord.getValue({
                            fieldId: 'taxtotal'
                        }));
                        shippingMethods[k].shippingcost = escape(estimateObjRecord.getValue({
                            fieldId: 'shippingcost'
                        }));
                        shippingMethods[k].altshippingcost = escape(estimateObjRecord.getValue({
                            fieldId: 'altshippingcost'
                        }));
                        shippingMethods[k].handlingcost = escape(estimateObjRecord.getValue({
                            fieldId: 'handlingcost'
                        }));
                        shippingMethods[k].althandlingcost = escape(estimateObjRecord.getValue({
                            fieldId: 'althandlingcost'
                        }));
                        shippingMethods[k].origtotal = escape(estimateObjRecord.getValue({
                            fieldId: 'origtotal'
                        }));
                        shippingMethods[k].origtotal2 = escape(estimateObjRecord.getValue({
                            fieldId: 'origtotal2'
                        }));
                        shippingMethods[k].total = escape(estimateObjRecord.getValue({
                            fieldId: 'total'
                        }));
                        shippingMethods[k].itemcount = escape(estimateObjRecord.getValue({
                            fieldId: 'custbody_items_order'
                        }));


                    } else if (recordExist) {


                        estimateObjRecord = record.load({
                            type: record.Type.ESTIMATE,
                            id: estimateRecordID,
                            isDynamic: true
                        });
                        estimateObjRecord.setValue({
                            fieldId: 'shipmethod',
                            value: shippingMethods[k].id, //shippingMethod,
                            ignoreFieldChange: false
                        });

                        try {
                            //Saving Estimate Record
                            var estimateRecordID1 = estimateObjRecord.save({
                                enableSourcing: true,
                                ignoreMandatoryFields: false
                            });


                        } catch (e) {
                            log.debug({
                                title: e.name,
                                details: e.message
                            });
                        }
                        if (estimateRecordID1) {
                            //Load created Sales Order so that we can fetch data
                            estimateObjRecord = record.load({
                                type: record.Type.ESTIMATE,
                                id: estimateRecordID1,
                                isDynamic: true
                            });

                            shippingMethods[k].shippingcost = escape(estimateObjRecord.getValue({
                                fieldId: 'shippingcost'
                            }));
                            // responseObj.tempestimateid = escape(estimateRecordID);
                            shippingMethods[k].subtotal = escape(estimateObjRecord.getValue({
                                fieldId: 'subtotal'
                            }));
                            shippingMethods[k].discounttotal = escape(estimateObjRecord.getValue({
                                fieldId: 'discounttotal'
                            }));
                            shippingMethods[k].item_total = escape(estimateObjRecord.getValue({
                                fieldId: 'item_total'
                            }));
                            shippingMethods[k].taxtotal = escape(estimateObjRecord.getValue({
                                fieldId: 'taxtotal'
                            }));
                            shippingMethods[k].shippingcost = escape(estimateObjRecord.getValue({
                                fieldId: 'shippingcost'
                            }));
                            shippingMethods[k].altshippingcost = escape(estimateObjRecord.getValue({
                                fieldId: 'altshippingcost'
                            }));
                            shippingMethods[k].handlingcost = escape(estimateObjRecord.getValue({
                                fieldId: 'handlingcost'
                            }));
                            shippingMethods[k].althandlingcost = escape(estimateObjRecord.getValue({
                                fieldId: 'althandlingcost'
                            }));
                            shippingMethods[k].origtotal = escape(estimateObjRecord.getValue({
                                fieldId: 'origtotal'
                            }));
                            shippingMethods[k].origtotal2 = escape(estimateObjRecord.getValue({
                                fieldId: 'origtotal2'
                            }));
                            shippingMethods[k].total = escape(estimateObjRecord.getValue({
                                fieldId: 'total'
                            }));
                            shippingMethods[k].itemcount = escape(estimateObjRecord.getValue({
                                fieldId: 'custbody_items_order'
                            }));
                        }


                    }


                    // }

                    /* responseObj.responseString = escape('SUCCESS');
                     responseObj.responseHandle = escape('ORDERSUMMARY');
                     responseArray.push(responseObj);
                     //To delete Estimate/Quote
                     main.deleteEstimateRecord(estimateRecordID);
                     return responseArray;*/
                }

                if (estimateRecordID) {
                    main.deleteEstimateRecord(estimateRecordID);
                }
                if (estimateRecordID1) {
                    main.deleteEstimateRecord(estimateRecordID1);
                }

                shippingMethods.responseString = escape('SUCCESS');
                //responseArray.push(responseObj);

                return shippingMethods;
            },
            deleteEstimateRecord: function(RECORD_ID) {
                var estimateRecord = record.delete({
                    type: record.Type.ESTIMATE,
                    id: RECORD_ID
                });
                //return true;
            },
            fetchAddressDetails: function(context) {
                log.debug('STARTS FUNCTION ', 'main.fetchAddressDetails()');

                var customerID = unescape(context.request.parameters.empid);
                customerID = (customerID.toString()).trim();
                log.debug('customerID', customerID);
                var customerObj = main.runCustomerSearch(customerID);

                if (customerObj.length > 0) {

                    var result = customerObj[0];
                    var responseArray = new Array();
                    var responseObj = new Object();

                    responseObj.phone = escape(result.getValue({
                        name: 'phone'
                    }));
                    responseObj.shipphone = escape(result.getValue({
                        name: 'shipphone'
                    }));
                    responseObj.billphone = escape(result.getValue({
                        name: 'billphone'
                    }));
                    responseObj.shipaddress = escape(result.getValue({
                        name: 'shipaddress'
                    }));
                    responseObj.billaddress = escape(result.getValue({
                        name: 'billaddress'
                    }));
                    responseObj.responseString = escape('SUCCESS');


                    responseArray.push(responseObj)
                    /* responseObj = undefined;
                     responseObj = {};*/
                    //responseObj.responseString = escape('SUCCESS');
                    //responseArray.push(responseObj)


                    var callBackFunction = context.request.parameters.callback;
                    var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                    context.response.write(responseStrJson);
                    return true;

                } else
                    return main.sendResponse('FAILURE', escape('INVALID CUSTOMER ID'), false, escape('main.fetchAddressDetails()'), context);
            },
            updateAddress: function(context, addrObj) {
                if (!checkForParameter(context) && !checkForParameter(addrObj))
                    return false;
                var customerID, customerName, customerCompanyName, customerAddr1, customerAddr2, customerCountry, customerCity, customerState, customerZipCode, customerPhone;
                if (checkForParameter(context)) {
                    customerID = unescape(context.request.parameters.empid);
                    customerID = (customerID.toString()).trim();
                    customerName = unescape(context.request.parameters.empname);
                    customerCompanyName = unescape(context.request.parameters.compname);
                    if (customerCompanyName == 'empty')
                        customerCompanyName = '';
                    customerAddr1 = unescape(context.request.parameters.addr1);
                    customerAddr2 = unescape(context.request.parameters.addr2);
                    if (customerAddr2 == 'empty')
                        customerAddr2 = '';
                    customerCountry = unescape(context.request.parameters.country);
                    customerCity = unescape(context.request.parameters.city);
                    customerState = unescape(context.request.parameters.state);
                    customerZipCode = unescape(context.request.parameters.zip);
                    customerPhone = unescape(context.request.parameters.phone);

                    /*
                        customerAddressType permissible values are
                        sa <- Shipping Address (Default)
                        ba <- Billing Address
                    */
                    customerAddressType = unescape(context.request.parameters.addrtype);
                    customerAddressType = assignDefaultValue(customerAddressType, 'sa');
                } else {
                    customerID = unescape(addrObj.empid);
                    customerID = (customerID.toString()).trim();
                    customerName = unescape(addrObj.empname);
                    customerCompanyName = unescape(addrObj.compname);
                    if (customerCompanyName == 'empty')
                        customerCompanyName = '';
                    customerAddr1 = unescape(addrObj.addr1);
                    customerAddr2 = unescape(addrObj.addr2);
                    if (customerAddr2 == 'empty')
                        customerAddr2 = '';
                    customerCountry = unescape(addrObj.country);
                    customerCity = unescape(addrObj.city);
                    customerState = unescape(addrObj.state);
                    customerZipCode = unescape(addrObj.zip);
                    customerPhone = unescape(addrObj.phone);
                    /*
                        customerAddressType permissible values are
                        sa <- Shipping Address (Default)
                        ba <- Billing Address
                    */
                    customerAddressType = unescape(addrObj.addrtype);
                }


                var modifyExistingAddress = function(customerAddressType, customerRecord) {
                    var addressLines = customerRecord.getLineCount({
                        sublistId: 'addressbook'
                    });
                    if (addressLines > 0) {
                        var defaultStatus;
                        for (i = 0; i < addressLines; i++) {
                            if (customerAddressType == 'sa')
                                defaultStatus = customerRecord.getSublistValue({
                                    sublistId: 'addressbook',
                                    fieldId: 'defaultshipping',
                                    line: i
                                });
                            else if (customerAddressType == 'ba')
                                defaultStatus = customerRecord.getSublistValue({
                                    sublistId: 'addressbook',
                                    fieldId: 'defaultbilling',
                                    line: i
                                });
                            if (defaultStatus == true)
                                return {
                                    status: true,
                                    line: i
                                }
                        }
                        return {
                            status: false,
                        }
                    }
                    return {
                        status: false,
                    }
                }

                var customerRecord = record.load({
                    type: record.Type.CUSTOMER,
                    id: customerID,
                    isDynamic: true,
                });
                if (customerAddressType == 'sa')
                    customerRecord.setValue({
                        fieldId: 'phone',
                        value: customerPhone
                    });



                var isAddressExisting = modifyExistingAddress(customerAddressType, customerRecord);

                if (checkForParameter(isAddressExisting.status))
                    var selectLine = customerRecord.selectLine({
                        sublistId: 'addressbook',
                        line: isAddressExisting.line
                    });
                else
                    var selectLine = customerRecord.selectNewLine({
                        sublistId: 'addressbook'
                    });


                if (customerAddressType == 'sa') {
                    customerRecord.setCurrentSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'defaultshipping',
                        value: true
                    });
                    customerRecord.setCurrentSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'defaultbilling',
                        value: false
                    });
                } else if (customerAddressType == 'ba') {
                    customerRecord.setCurrentSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'defaultbilling',
                        value: true
                    });
                    customerRecord.setCurrentSublistValue({
                        sublistId: 'addressbook',
                        fieldId: 'defaultshipping',
                        value: false
                    });
                }



                var myaddressSubrecord = customerRecord.getCurrentSublistSubrecord({
                    sublistId: 'addressbook',
                    fieldId: 'addressbookaddress'
                });

                myaddressSubrecord.setValue({
                    fieldId: 'country',
                    value: customerCountry
                });
                myaddressSubrecord.setValue({
                    fieldId: 'city',
                    value: customerCity
                });
                myaddressSubrecord.setValue({
                    fieldId: 'state',
                    value: customerState
                });
                myaddressSubrecord.setValue({
                    fieldId: 'zip',
                    value: customerZipCode
                });
                myaddressSubrecord.setValue({
                    fieldId: 'addrphone',
                    value: customerPhone
                });
                myaddressSubrecord.setValue({
                    fieldId: 'attention',
                    value: customerName
                });
                myaddressSubrecord.setValue({
                    fieldId: 'addressee',
                    value: customerCompanyName
                });
                myaddressSubrecord.setValue({
                    fieldId: 'addr1',
                    value: customerAddr1
                });
                myaddressSubrecord.setValue({
                    fieldId: 'addr2',
                    value: customerAddr2
                });
                customerRecord.commitLine({
                    sublistId: 'addressbook'
                });
                var recordID = customerRecord.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                });


                return ((checkForParameter(recordID)) ? (true) : (false));
            },
            handleUpdateAddress: function(context) {
                log.debug('STARTS FUNCTION ', 'main.handleUpdateAddress()');
                var customerID = unescape(context.request.parameters.empid);
                customerID = (customerID.toString()).trim();
                log.debug('customerID', customerID);
                var customerObj = main.runCustomerSearch(customerID);
                if (customerObj.length > 0) {
                    var isAdressUpdate = main.updateAddress(context);
                    if (isAdressUpdate) {
                        customerObj = main.runCustomerSearch(customerID);
                        var result = customerObj[0];
                        var responseArray = new Array();
                        var responseObj = new Object();
                        responseObj.phone = escape(result.getValue({
                            name: 'phone'
                        }));
                        responseObj.shipphone = escape(result.getValue({
                            name: 'shipphone'
                        }));
                        responseObj.billphone = escape(result.getValue({
                            name: 'billphone'
                        }));
                        responseObj.shipaddress = escape(result.getValue({
                            name: 'shipaddress'
                        }));
                        responseObj.billaddress = escape(result.getValue({
                            name: 'billaddress'
                        }));
                        responseArray.push(responseObj);
                        responseObj = undefined;
                        responseObj = new Object();
                        responseObj.responseString = escape('SUCCESS');
                        responseArray.push(responseObj);

                        var callBackFunction = context.request.parameters.callback;
                        var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                        context.response.write(responseStrJson);
                        return true;
                    } else
                        return main.sendResponse('FAILURE', escape('FAILED TO UPDATED ADDRESS'), false, escape('main.handleUpdateAddress()'), context);
                } else
                    return main.sendResponse('FAILURE', escape('INVALID CUSTOMER ID'), false, escape('main.handleUpdateAddress()'), context);
            },
            setBillingAsShippingAddress: function(customerID) {
                var addrObj = new Object();
                var customerSearchObj = search.create({
                    type: "customer",
                    filters: [
                        ["status", "anyof", "13"],
                        "AND", ["internalid", "anyof", customerID]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        }),
                        search.createColumn({ name: "shipaddress", label: "Shipping Address" }),
                        search.createColumn({ name: "shipaddress1", label: "Shipping Address 1" }),
                        search.createColumn({ name: "shipaddress2", label: "Shipping Address 2" }),
                        search.createColumn({ name: "shipaddress3", label: "Shipping Address 3" }),
                        search.createColumn({ name: "shipaddressee", label: "Shipping Addressee" }),
                        search.createColumn({ name: "shipattention", label: "Shipping Attention" }),
                        search.createColumn({ name: "shippingcarrier", label: "Shipping Carrier" }),
                        search.createColumn({ name: "shipcity", label: "Shipping City" }),
                        search.createColumn({ name: "shipcountry", label: "Shipping Country" }),
                        search.createColumn({ name: "shipcountrycode", label: "Shipping Country Code" }),
                        search.createColumn({ name: "shippingitem", label: "Shipping Item" }),
                        search.createColumn({ name: "shipphone", label: "Shipping Phone" }),
                        search.createColumn({ name: "shipstate", label: "Shipping State/Province" }),
                        search.createColumn({ name: "shipzip", label: "Shipping Zip" }),
                    ]
                }).run().each(function(result) {
                    addrObj.empid = escape(customerID)
                    addrObj.empname = escape(assignDefaultValue(result.getValue({
                        name: 'shipattention'
                    }), ''));
                    addrObj.compname = escape(assignDefaultValue(result.getValue({
                        name: 'shipaddressee'
                    }), 'empty'));
                    addrObj.addr1 = escape(assignDefaultValue(result.getValue({
                        name: 'shipaddress1'
                    }), ''));
                    addrObj.addr2 = escape(assignDefaultValue(result.getValue({
                        name: 'shipaddress2'
                    }), 'empty'));
                    addrObj.country = escape(assignDefaultValue(result.getValue({
                        name: 'shipcountry'
                    }), ''));
                    addrObj.city = escape(assignDefaultValue(result.getValue({
                        name: 'shipcity'
                    }), ''));
                    addrObj.state = escape(assignDefaultValue(result.getValue({
                        name: 'shipstate'
                    }), ''));
                    addrObj.zip = escape(assignDefaultValue(result.getValue({
                        name: 'shipzip'
                    }), ''));
                    addrObj.phone = escape(assignDefaultValue(result.getValue({
                        name: 'shipphone'
                    }), ''));
                    addrObj.addrtype = escape('ba');
                    return false;
                });

                return main.updateAddress(undefined, addrObj);
            },
            handleSetBillingAsShipping: function(context) {
                log.debug('STARTS FUNCTION ', 'main.handleSetBillingAsShipping()');
                var customerID = unescape(context.request.parameters.empid);
                customerID = (customerID.toString()).trim();

                var customerObj = main.runCustomerSearch(customerID);
                if (customerObj.length > 0) {
                    var isAdressUpdate = main.setBillingAsShippingAddress(customerID);
                    if (isAdressUpdate) {
                        customerObj = main.runCustomerSearch(customerID);
                        var result = customerObj[0];
                        var responseArray = new Array();
                        var responseObj = new Object();
                        responseObj.phone = escape(result.getValue({
                            name: 'phone'
                        }));
                        responseObj.shipphone = escape(result.getValue({
                            name: 'shipphone'
                        }));
                        responseObj.billphone = escape(result.getValue({
                            name: 'billphone'
                        }));
                        responseObj.shipaddress = escape(result.getValue({
                            name: 'shipaddress'
                        }));
                        responseObj.billaddress = escape(result.getValue({
                            name: 'billaddress'
                        }));
                        responseArray.push(responseObj);
                        responseObj = undefined;
                        responseObj = new Object();
                        responseObj.responseString = escape('SUCCESS');
                        responseArray.push(responseObj);

                        var callBackFunction = context.request.parameters.callback;
                        var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                        context.response.write(responseStrJson);
                        return true;
                    } else
                        return main.sendResponse('FAILURE', escape('FAILED TO UPDATED ADDRESS'), false, escape('main.handleSetBillingAsShipping()'), context);
                } else
                    return main.sendResponse('FAILURE', escape('INVALID CUSTOMER ID'), false, escape('main.handleSetBillingAsShipping()'), context);
            },
            approveCCPayment: function(salesRecordID, context) {
                var timeStamp = decodeURIComponent(context.request.parameters.timestamp);

                var paymentCCtype = decodeURIComponent(context.request.parameters.ctype);
                paymentCCtype = encryptionModule.decodedDecryption(timeStamp, paymentCCtype);

                var paymentCCNumber = decodeURIComponent(context.request.parameters.cnum);
                paymentCCNumber = encryptionModule.decodedDecryption(timeStamp, paymentCCNumber);

                var paymentName = decodeURIComponent(context.request.parameters.cname);
                paymentName = encryptionModule.decodedDecryption(timeStamp, paymentName);

                var paymentExpiryMonth = decodeURIComponent(context.request.parameters.cmonth);
                paymentExpiryMonth = encryptionModule.decodedDecryption(timeStamp, paymentExpiryMonth);

                var paymentExpiryYear = decodeURIComponent(context.request.parameters.cyear);
                paymentExpiryYear = encryptionModule.decodedDecryption(timeStamp, paymentExpiryYear);

                var paymentCCVNumber = decodeURIComponent(context.request.parameters.cccv);
                paymentCCVNumber = encryptionModule.decodedDecryption(timeStamp, paymentCCVNumber);



                var paymentflag = false;
                var salesOrderRecord = record.load({
                    type: record.Type.SALES_ORDER,
                    id: salesRecordID,
                    isDynamic: true
                });
                var tranID = salesOrderRecord.getValue({
                    fieldId: 'tranid'
                });

                salesOrderRecord.setValue({
                    fieldId: 'paymentmethod',
                    value: paymentCCtype,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'creditcardprocessor',
                    value: 4, //4-os_uniforms
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'ccnumber',
                    value: paymentCCNumber,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'ccname',
                    value: paymentName,
                    ignoreFieldChange: false
                });
                var paymentExpiryDate = paymentExpiryMonth + '/' + paymentExpiryYear;
                salesOrderRecord.setValue({
                    fieldId: 'ccexpiredate',
                    value: paymentExpiryDate,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'ccsecuritycode',
                    value: paymentCCVNumber,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'getauth',
                    value: true,
                    ignoreFieldChange: false
                });
                salesRecordID = salesOrderRecord.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: false
                });


                var salesObjRecordSearch = search.create({
                    type: "transaction",
                    filters: [
                        ["internalidnumber", "equalto", salesRecordID],
                        "AND", ["mainline", "is", "T"]
                    ],
                    columns: [
                        search.createColumn({
                            name: "paymentstatus",
                            join: "paymentEvent"
                        }),
                        "paymenteventresult",
                        "paymentmethod",
                        "paymenthold"
                    ]
                }).run().getRange({
                    start: 0,
                    end: 1
                });

                if (salesObjRecordSearch.length > 0) {
                    var paymentEventResult = salesObjRecordSearch[0].getValue({
                        name: 'paymenteventresult'
                    });
                    if (paymentEventResult == "ACCEPT" || paymentEventResult == "Accept" || ((paymentEventResult.toLowerCase()) == 'accept')) {
                        paymentflag = true;
                    } else {
                        paymentflag = false;
                    }
                } else {
                    paymentflag = false;
                }
                if (paymentflag) {
                    return {
                        status: true,
                        soid: salesRecordID,
                        sotranid: tranID
                    };
                } else {
                    return {
                        status: false
                    };
                }
            },
            createSalesOrder: function(customerID, customerObj, shoppingCartObj, shippingMethod, context) {
                var responseObj = new Object();
                var responseArray = new Array();
                var salesOrderRecord = record.transform({
                    fromType: record.Type.CUSTOMER,
                    fromId: customerID,
                    toType: record.Type.SALES_ORDER,
                    isDynamic: true,
                });
                salesOrderRecord.setValue({
                    fieldId: 'customform',
                    value: 239 // value":"239","text":"OS Sales Order – PrePay"
                });
                salesOrderRecord.setValue({
                    fieldId: 'orderstatus',
                    value: 'B', //Pending Fulfillment
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'class',
                    value: 18, //Products : Water
                    ignoreFieldChange: false
                });
                /*
                    ups - UPS
                    nonups - FedEx/USPS/More
                 */
                salesOrderRecord.setValue({
                    fieldId: 'shipcarrier',
                    value: 'nonups',
                    ignoreFieldChange: false
                });
                var totalQuantity = main.getCartTotalQuantity(shoppingCartObj);


                salesOrderRecord.setValue({
                    fieldId: 'shipmethod',
                    value: shippingMethod.toString().trim(),
                    ignoreFieldChange: false
                });

                //to sort shoppingCartObj based on itemid/itemname
                shoppingCartObj = main.sortObjArray(shoppingCartObj, 'itemname');
                //to add line items
                for (var i = 0, len = shoppingCartObj.length; i < len; i++) {
                    salesOrderRecord.selectNewLine({
                        sublistId: 'item'
                    });

                    salesOrderRecord.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        value: shoppingCartObj[i].internalid,
                        ignoreFieldChange: false
                    });

                    salesOrderRecord.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        value: shoppingCartObj[i].itemquantity,
                        ignoreFieldChange: false
                    });
                    salesOrderRecord.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'istaxable',
                        value: true,
                        ignoreFieldChange: false
                    });
                    salesOrderRecord.commitLine({
                        sublistId: 'item'
                    });
                }

                var salesRecordID = salesOrderRecord.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: false
                });

                //For payment process
                var paymentType = decodeURIComponent(context.request.parameters.ptype);
                var confirmPayment = new Object();
                if (paymentType == 'cc')
                    confirmPayment = main.approveCCPayment(salesRecordID, context); //credit card
                else if (paymentType == 'pp')
                    confirmPayment = main.approvePaypalPayment(salesRecordID, context); //paypal
                else
                    confirmPayment.status = false;


                if (confirmPayment.status) {
                    //Delete items from Paid Cart after Sales Order is placed
                    var isDeleteFreeCart = main.sendClearPaidShoppingCartRequest(customerID);

                    responseObj.tranid = escape(confirmPayment.sotranid);
                    responseObj.soid = escape(confirmPayment.soid);
                    //responseObj.responseString = escape('SUCCESS');
                    responseObj.responseMessage = escape('ORDER PLACED');
                    responseObj.responseString = escape('SUCCESS');
                    responseArray.push(responseObj);

                    //To send Order Confirmation Email
                    main.sendOrderConfirmationEmail(unescape(responseArray[0].soid), customerID);
                    return responseArray;
                } else {
                    //To delete payment failed Sales Order     
                    main.deleteSalesOrderRecord(salesRecordID);

                    responseObj.responseString = escape('FAILURE');
                    responseArray.push(responseObj);
                    return responseArray;
                }
            },
            approvePaypalPayment: function(salesRecordID, context) {

                //var paymentID = 
                var paypalOrderId = unescape(context.request.parameters.paypalOrderId); //ORDER ID
                var authorizationID = unescape(context.request.parameters.authorizationID); //auth  ID


                var salesOrderRecord = record.load({
                    type: record.Type.SALES_ORDER,
                    id: salesRecordID,
                    isDynamic: true
                });

                var tranID = salesOrderRecord.getValue({
                    fieldId: 'tranid'
                });

                salesOrderRecord.setValue({
                    fieldId: 'paymentmethod',
                    value: 10,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'paypalorderid',
                    value: paypalOrderId,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'paypaltranid',
                    value: authorizationID,
                    ignoreFieldChange: false
                });
                salesOrderRecord.setValue({
                    fieldId: 'paypalauthid',
                    value: authorizationID,
                    ignoreFieldChange: false
                });

                salesOrderRecord.setValue({
                    fieldId: 'custbody_jj_paypal_site_category',
                    value: 1,
                    ignoreFieldChange: true
                });

                salesRecordID = salesOrderRecord.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: false
                });

                return {
                    status: true,
                    soid: salesRecordID,
                    sotranid: tranID
                };

            },
            deleteSalesOrderRecord: function(RECORD_ID) {
                var estimateRecord = record.delete({
                    type: record.Type.SALES_ORDER,
                    id: RECORD_ID
                });
                //return true;
            },
            handleCreateSalesOrder: function(context) {
                log.debug('STARTS FUNCTION ', 'main.handleCreateSalesOrder()');
                var customerID = unescape(context.request.parameters.empid);
                customerID = (customerID.toString()).trim();
                //log.debug('customerID', customerID);
                var customerObj = main.runCustomerSearch(customerID);
                if (main.verifyStock(customerID, context)) {
                    customerID = (customerID.toString()).trim();

                    var customerObj = main.runCustomerSearch(customerID);
                    if (customerObj.length > 0) {
                        var paidShoppingCartObj = main.searchPaidShoppingCartItems(customerID);

                        if (paidShoppingCartObj.length > 0) {
                            var responseArray = new Array();
                            var shippingMethod = unescape(context.request.parameters.shippingMethod);
                            responseArray = main.createSalesOrder(customerID, customerObj[0], paidShoppingCartObj, shippingMethod, context);
                            if (checkForParameter(responseArray)) {
                                var callBackFunction = context.request.parameters.callback;
                                var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                                context.response.write(responseStrJson);
                                return true;
                            }
                            return false;
                        } else
                            return main.sendResponse('FAILURE', escape('EMPTY CART'), false, escape('main.handleCreateSalesOrder()'), context);
                    } else
                        return main.sendResponse('FAILURE', escape('INVALID CUSTOMER ID'), false, escape('main.handleCreateSalesOrder()'), context);
                } else
                    return main.sendResponse('FAILURE', escape('OUT OF STOCK'), false, escape('main.handleCreateSalesOrder()'), context);
            },

            sendClearPaidShoppingCartRequest: function(customerID) {
                var requestURL = url.resolveScript({
                    scriptId: 'customscriptosi_52_jj_sl_aquverse_checko',
                    deploymentId: 'customdeploy_osi_52_jj_sl_aquv_check_out',
                    returnExternalUrl: true
                });
                https.get({
                    url: requestURL + '&status=clearpaidcart' + '&empid=' + escape(customerID)
                });
                return true;
            },
            handleClearPaidShoppingCart: function(context) {
                log.debug('STARTS FUNCTION ', 'main.handleClearPaidShoppingCart()');
                var customerID = unescape(context.request.parameters.empid);
                customerID = (customerID.toString()).trim();
                log.debug('customerID', customerID);
                var shoppingCartObj = main.searchPaidShoppingCartItems(customerID);
                log.debug('shoppingCartObj', shoppingCartObj);
                if (shoppingCartObj.length > 0) {
                    for (var i = 0, len = shoppingCartObj.length; i < len; i++)
                        record.delete({
                            type: 'customrecord_osi52_jj_aquverse_user_cart',
                            id: shoppingCartObj[i].scid
                        });
                }
                return true;
            },
            getItemDisplayName: function() {
                var displayNameMap = new Object();
                var itemInternalID;
                var inventoryitemSearchObj = search.create({
                    type: "inventoryitem",
                    filters: [
                        ["type", "anyof", "InvtPart"],
                        "AND", ["isonline", "is", "T"],
                        "AND", ["category", "anyof", "148319", "148320"],
                        "AND", ["isinactive", "is", "F"]
                    ],
                    columns: [
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({ name: "itemid", label: "Name" }),
                        search.createColumn({ name: "externalid", label: "External ID" }),
                        search.createColumn({ name: "displayname", label: "Display Name" }),
                        search.createColumn({ name: "salesdescription", label: "Description" }),
                        search.createColumn({ name: "type", label: "Type" }),
                        search.createColumn({ name: "storedisplayname", label: "Store Display Name" }),
                        search.createColumn({ name: "parent", label: "Parent" })
                    ]
                }).run().each(function(result) {
                    itemInternalID = result.getValue({
                        name: "internalid"
                    });
                    if (checkForParameter(displayNameMap[itemInternalID]))
                        return true;

                    displayNameMap[itemInternalID] = result.getValue({
                        name: "storedisplayname"
                    })
                    return true;
                });
                return displayNameMap;
            },
            fetchSOItems: function(SALES_ORDER_ID) {
                var responseArray = new Array();
                var displayNameMap = main.getItemDisplayName();
                var salesorderItemSearchObj = search.create({
                    type: "salesorder",
                    filters: [
                        ["type", "anyof", "SalesOrd"],
                        "AND", ["internalidnumber", "equalto", SALES_ORDER_ID],
                        "AND", ["item.internalidnumber", "isnotempty", ""],
                        "AND", ["item.type", "anyof", "InvtPart", "Kit"]
                    ],
                    columns: [
                        "internalid", //SALES ORDER INTERNAL ID
                        "item", //ITEM
                        "quantity", //QUANTITY
                        "rate", //ITEM RATE
                        "amount", //AMOUNT -> ( QUANTITY * ITEM RATE )
                        search.createColumn({
                            name: "internalid",
                            join: "item"
                        }), //ITEM : INTERNAL ID
                        search.createColumn({
                            name: "displayname",
                            join: "item"
                        }), //ITEM : DISPLAY NAME
                        search.createColumn({
                            name: "storedisplayname",
                            join: "item",
                            label: "Store Display Name"
                        }), //ITEM : STORE DISPLAY NAME
                        search.createColumn({
                            name: "parent",
                            join: "item",
                            label: "Parent"
                        }), //ITEM : PARENT
                        search.createColumn({
                            name: "shippingcost",
                            label: "Shipping Cost"
                        }), //Shipping Cost
                        search.createColumn({
                            name: "shippingamount",
                            label: "Amount (Shipping)"
                        }), //Amount (Shipping)
                        search.createColumn({
                            name: "total",
                            label: "Amount (Transaction Total)"
                        }), //Amount (Transaction Total)
                        search.createColumn({
                            name: "line",
                            sort: search.Sort.ASC
                        }), //LINE ID 
                    ]
                }).run().each(function(result) {
                    responseArray.push({
                        NAME: assignDefaultValue(displayNameMap[result.getValue({
                            name: "parent",
                            join: "item",
                        })], result.getText({
                            name: "item"
                        })),
                        QTY: result.getValue({
                            name: "quantity"
                        }), //QUANTITY
                        RATE_ITEM: fixFloat(result.getValue({
                            name: "rate"
                        }), 2), //RATE
                        AMOUNT_ITEM: fixFloat(result.getValue({
                            name: "amount"
                        }), 2), //AMOUNT
                    });
                    return true;
                });
                return responseArray;
            },
            getItemContents: function(SALES_ORDER_ID) {
                var getOrderItemsObj = main.fetchSOItems(SALES_ORDER_ID);


                var tableContents = '';
                var line1 = '<tr style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;"> <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;background-color:#dddddd;">$REPLACE_ITEM_NAME</td> <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;background-color:#dddddd;">$REPLACE_ITEM_QUANTITY</td> <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;background-color:#dddddd;">$REPLACE_ITEM_COST</td></tr>';
                var line2 = '<tr style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;"> <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;">$REPLACE_ITEM_NAME</td>  <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;">$REPLACE_ITEM_QUANTITY</td> <td style="margin-top:0;margin-bottom:0;margin-right:0;margin-left:0;font-family:\'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif;border-width:1px;border-style:solid;border-color:#cecece;text-align:left;padding-top:8px;padding-bottom:8px;padding-right:8px;padding-left:8px;">$REPLACE_ITEM_COST</td></tr>';

                var NAME, QTY, COST;
                for (var i = 0, len = getOrderItemsObj.length; i < len; i++) {
                    NAME = getOrderItemsObj[i].NAME;
                    QTY = getOrderItemsObj[i].QTY;
                    COST = '$' + getOrderItemsObj[i].AMOUNT_ITEM;
                    if (i % 2 == 0) {
                        tableContents += line1.replace('$REPLACE_ITEM_NAME', NAME).replace('$REPLACE_ITEM_QUANTITY', QTY).replace('$REPLACE_ITEM_COST', COST);
                    } else {
                        tableContents += line2.replace('$REPLACE_ITEM_NAME', NAME).replace('$REPLACE_ITEM_QUANTITY', QTY).replace('$REPLACE_ITEM_COST', COST);
                    }
                }
                return tableContents;
            },
            createOrderConfirmationContents: function(SALES_ORDER_ID, customerObj) {
                var salesRecordObj = record.load({
                    type: record.Type.SALES_ORDER,
                    id: SALES_ORDER_ID,
                });
                var getOrderDetailsObj = {
                    $REPLACE_CUSTOMER_NAME: assignDefaultValue(customerObj.getValue({
                        name: 'firstname'
                    }), '') + ' ' + assignDefaultValue(customerObj.getValue({
                        name: 'lastname'
                    }), ''),
                    $REPLACE_SO_TRANID: '#' + salesRecordObj.getValue({
                        fieldId: 'tranid'
                    }),
                    $REPLACE_ITEM_TABLE: main.getItemContents(SALES_ORDER_ID),
                    $REPLACE_SUBTOTAL: '$' + fixFloat(assignDefaultValue(salesRecordObj.getValue({
                        fieldId: 'subtotal'
                    }), 0), 2),
                    $REPLACE_SHIPPING_COST: '$' + fixFloat(assignDefaultValue(salesRecordObj.getValue({
                        fieldId: 'altshippingcost'
                    }), 0), 2),
                    $REPLACE_TOTAL_TAX: '$' + fixFloat(assignDefaultValue(salesRecordObj.getValue({
                        fieldId: 'taxtotal'
                    }), 0), 2),
                    $REPLACE_DISCOUNT: '-$0.00',
                    $REPLACE_TOTAL_COST: '$' + fixFloat(assignDefaultValue(salesRecordObj.getValue({
                        fieldId: 'total'
                    }), 0), 2),
                    $REPLACE_PAYMENT_METHOD: assignDefaultValue(salesRecordObj.getText({
                        fieldId: 'paymentmethod'
                    }), ''),
                    $REPLACE_SHIPPING_ADDRESS: salesRecordObj.getValue({
                        fieldId: 'shipaddress'
                    }).replace(/\r\n/g, '<br />').replace(/\n/g, '<br />').replace(/\r/g, '<br />').replace(/<BR>/g, '<br />'),
                    $REPLACE_BILLING_ADDRESS: salesRecordObj.getValue({
                        fieldId: 'billaddress'
                    }).replace(/\r\n/g, '<br />').replace(/\n/g, '<br />').replace(/\r/g, '<br />').replace(/<BR>/g, '<br />')
                };

                //Load Email template for EMAIL BODY
                var fileObj = file.load({
                    id: 1059037 //ORDER_INLINE_CSS_TEMPLATE.html
                });
                var getOrderEmailTemplate = fileObj.getContents();

                for (key in getOrderDetailsObj) {
                    getOrderEmailTemplate = getOrderEmailTemplate.replace(key, getOrderDetailsObj[key]);
                }
                return {
                    EMAILSUBJECT: 'Aquverse Order Confirmation',
                    EMAILBODY: getOrderEmailTemplate
                }
            },
            sendOrderConfirmationEmail: function(SALES_ORDER_ID, CUSTOMER_INTERNAL_ID) {
                log.debug('STARTS FUNCTION ', 'main.sendOrderConfirmationEmail()');
                var customerObj = main.runCustomerSearch(CUSTOMER_INTERNAL_ID);
                var emailContents = main.createOrderConfirmationContents(SALES_ORDER_ID, customerObj[0]);
                var senderId = 337292; //NoReply@osiml.com
                var recipientId = CUSTOMER_INTERNAL_ID;
                email.send({
                    author: senderId,
                    recipients: recipientId,
                    //cc: ['manu@jobinandjismi.com', 'rijo@jobinandjismi.com', 'Mark.Skorpil@osiml.com'],
                    subject: emailContents.EMAILSUBJECT,
                    body: emailContents.EMAILBODY,
                    relatedRecords: {
                        entityId: recipientId,
                    }
                });
                //return true;
            },
            onRequest: function(context) {
                /**
                 * Definition of the Suitelet script trigger point.
                 *
                 * @param {Object} context
                 * @param {ServerRequest} context.request - Encapsulation of the incoming request
                 * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
                 * @Since 2015.2
                 */
                CONTEXT = context;
                var isProccessed = main.routeRequest(context);
                log.debug("Is request Proccessed ", isProccessed);
            },
            sendResponse: function(responseString, responseMessage, isPositive, responseLocation, context, moreDetailsObj) {
                if (!checkForParameter(context))
                    context = CONTEXT;
                var responseObj = {};
                var responseArray = [];
                var callBackFunction = context.request.parameters.callback;
                if (isPositive) {
                    responseObj.responseString = responseString;
                    responseObj.responseMessage = responseMessage;
                    if (checkForParameter(moreDetailsObj))
                        responseObj.moreDetailsObj = moreDetailsObj
                } else {
                    responseObj.responseString = responseString;
                    responseObj.responseMessage = responseMessage;
                    responseObj.responseLocation = responseLocation;
                    if (checkForParameter(moreDetailsObj))
                        responseObj.moreDetailsObj = moreDetailsObj
                }
                responseArray.push(responseObj);
                var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                context.response.write(responseStrJson);

                if (isPositive)
                    return true;
                else
                    return false;
            },
            remainingUsage: function() {
                //var scriptObj = runtime.getCurrentScript();
                var remainingTime = runtime.getCurrentScript().getRemainingUsage();
                return remainingTime;
            }
        };


        for (var key in main) {
            if (typeof main[key] === 'function') {
                main[key] = trycatch(main[key], key);
            }
        }

        function trycatch(myfunction, key) {
            function logDetails(error) {
                log.debug("Error in function " + key, JSON.stringify(error));
                log.debug('Error on function ' + key, JSON.stringify(getError(error)));
                log.error("Error in function " + key, JSON.stringify(error));
                log.error('Error on function ' + key, JSON.stringify(getError(error)));
                return true;
            }
            return function() {
                try {
                    return myfunction.apply(this, arguments);
                } catch (error) {
                    var islogDetails = logDetails(error);
                    var responseObj = {};
                    var responseArray = [];
                    responseObj.responseString = 'FAILURE';
                    responseObj.responseMessage = escape(JSON.stringify(getError(error)));
                    responseObj.responseLocation = 'Error in main.' + key + '()';
                    responseArray.push(responseObj);
                    var context = CONTEXT;
                    if (checkForParameter(context.request.parameters.callback)) {
                        var callBackFunction = context.request.parameters.callback;
                        var responseStrJson = callBackFunction + '(\'' + JSON.stringify(responseArray) + '\');';
                        context.response.write(responseStrJson);
                    } else {
                        var responseStrJson = JSON.stringify(responseArray);
                        context.response.write(responseStrJson);
                    }
                    return false;
                }
            }
        };

        return main;

    });


/*******************************************************************************
 * return error
 * 
 * @param e
 * @returns
 * 
 */
function getError(e) {
    var stErrMsg = '';
    if (e.getDetails != undefined) {
        stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
            e.getStackTrace();
    } else {
        stErrMsg = '_' + e.toString();
    }
    return stErrMsg;
}

Leave a comment

Your email address will not be published. Required fields are marked *