A NetSuite customization for order items.

A custom screen which calculates the stock replenishment and the quantity to order. When the user selects the item and clicks the submit button the purchase order will be created for corresponding items with the quantity mentioned.

There are two screens for the customization, on the first screen the user can filter out the items according to the vendor and date created. In the second screen, the items will be listed and these items are can be ordered to create PO.

HTL-1 SL Order Items Filter Page

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * HTL
 * **************************************************************************
 * 
 * Date: 11-06-2018
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/email', 'N/file', 'N/currency', 'N/https', 'N/record', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/ui/serverWidget'],
    /**
     * @param {email} email
     * @param {file} file
     * @param {http} http
     * @param {https} https
     * @param {record} record
     * @param {runtime} runtime
     * @param {search} search
     * @param {serverWidget} serverWidget
     */
    function(email, file, currency, https, record, runtime, search, serverWidget) {

        var main = {
            /*On Request */
            onRequest: function(context) {
                if (context.request.method === 'GET') {
                    var form = serverWidget.createForm({
                        title: 'Filter Order Items  Page'
                    });
                    var fieldgroupdatefilter = form.addFieldGroup({
                        id: 'fieldgroupdatefilter',
                        label: 'Supplier Date Filters'
                    });
                    var datefiltertype = form.addField({
                        id: 'datefiltertype',
                        type: serverWidget.FieldType.SELECT,
                        label: 'Date',
                        container: 'fieldgroupdatefilter'
                    });
                    datefiltertype.updateBreakType({
                        breakType: serverWidget.FieldBreakType.STARTROW
                    });
                    main.addtype(datefiltertype);
                    /*              datefiltertype.updateDisplaySize({
                                      height: 60,
                                      width: 64.8
                                  });*/
                    var todate = form.addField({
                        id: 'todate',
                        type: serverWidget.FieldType.DATE,
                        label: 'ON',
                        container: 'fieldgroupdatefilter'
                    });
                    todate.updateBreakType({
                        breakType: serverWidget.FieldBreakType.STARTROW
                    });
                    todate.updateDisplaySize({
                        height: 60,
                        width: 64.8
                    });
                    var fromdate = form.addField({
                        id: 'fromdate',
                        type: serverWidget.FieldType.DATE,
                        label: 'From ',
                        container: 'fieldgroupdatefilter'
                    });
                    fromdate.updateBreakType({
                        breakType: serverWidget.FieldBreakType.STARTROW
                    });
                    fromdate.updateDisplaySize({
                        height: 60,
                        width: 64.8
                    });

                    var other = form.addFieldGroup({
                        id: 'fieldotherfiolter',
                        label: 'Other Filters'
                    });
                    var location = form.addField({
                        id: 'location',
                        type: serverWidget.FieldType.SELECT,
                        label: 'Location',
                        source: 'location',
                        container: 'fieldotherfiolter'
                    });
                    var supplier = form.addField({
                        id: 'supplier',
                        type: serverWidget.FieldType.SELECT,
                        label: 'supplier',
                        source: 'vendor',
                        container: 'fieldotherfiolter'
                    });

                    var minquantity = form.addField({
                        id: 'minquantity',
                        type: serverWidget.FieldType.TEXT,
                        label: 'MINIMUM QUANTITY',
                        container: 'fieldotherfiolter'
                    });

                    form.clientScriptFileId = '260315';
                    form.addSubmitButton({
                        label: 'Show With Filters'
                    });
                    context.response.writePage(form);
                } else {
                    var employeedata = context.request.body;
                    log.debug("employeedata", employeedata)
                    main.dopostaction(employeedata);
                }
            },
            /*Add type filter for date*/
            addtype: function(field) {
                var dateobj = [{ "value": "", "text": "" }, { "value": "ON", "text": "on" }, { "value": "BEFORE", "text": "before" }, { "value": "AFTER", "text": "after" }, { "value": "ONORBEFORE", "text": "on or before" }, { "value": "ONORAFTER", "text": "on or after" }, { "value": "WITHIN", "text": "within" }, { "value": "NOTON", "text": "not on" }, { "value": "NOTBEFORE", "text": "not before" }, { "value": "NOTAFTER", "text": "not after" }, { "value": "NOTONORBEFORE", "text": "not on or before" }, { "value": "NOTONORAFTER", "text": "not on or after" }, { "value": "NOTWITHIN", "text": "not within" }];
                for (var key in dateobj) {
                    field.addSelectOption({
                        value: dateobj[key]["value"],
                        text: dateobj[key]["text"]
                    });
                }
                return field;
            },
            /*Post action script */
            dopostaction: function(employeedata) {
                employeedata = JSON.parse(employeedata);
                var datefiltertype = employeedata.datefiltertype;
                var todate = employeedata.todate;
                var fromdate = employeedata.fromdate;

                log.debug("todate", todate);
                log.debug("fromdate", fromdate);
                log.debug("datefiltertype", datefiltertype);

                var datefilter = main.createdatefilter(datefiltertype, todate, fromdate);
                log.debug("datefilter", datefilter);
                var itemdetails = main.finditems("locationfilter", "minquantityfilter", "supplierfilter", datefilter);
                log.debug("itemdetails", itemdetails);
                main.createfile(itemdetails, "datefiltertypetodate")
            },
            /*Filter for suoplier delivery date*/
            createdatefilter: function(typefilter, tofilter, fromdate) {
                if (typefilter != null || typefilter != undefined) {
                    if (typefilter == "NOTWITHIN" || typefilter == "WITHIN") {
                        var filterarray = ["transaction.custbody5", typefilter, tofilter, fromdate]
                    } else {
                        var filterarray = ["transaction.custbody5", typefilter, tofilter]
                    }
                    return filterarray
                }
                return false
            },
            /*For Saving the JSON File In File Cabinet */
            createfile: function(netsuitedata, name) {
                if (netsuitedata == null || netsuitedata == "" || netsuitedata == undefined)
                    netsuitedata = { "rambo": "always" }
                var fileObj = file.create({
                    name: name + '.txt',
                    fileType: file.Type.JSON,
                    contents: JSON.stringify(netsuitedata),
                    encoding: file.Encoding.UTF8,
                    folder: 226002,
                    isOnline: true
                });
                var fileid = fileObj.save();
                log.debug("fileid", fileid);
            },
            /*Search to create Ignore Quantiy date */
            finditems: function(locationfilter, minquantityfilter, supplierfilter, datefilter) {
                var filtertype = [
                    ["cost", "greaterthan", "0.00"],
                    "AND", ["locationpreferredstocklevel", "greaterthanorequalto", "0"],
                    "AND", ["inventorylocation", "noneof", "@NONE@"],
                    "AND", ["othervendor", "noneof", "@NONE@"],
                    "AND", ["transaction.type", "anyof", "PurchOrd"]
                ]
                filtertype.push("AND", datefilter);
                var itemSearchObj = search.create({
                    type: "item",
                    filters: filtertype,
                    columns: [
                        search.createColumn({
                            name: "itemid",
                            summary: "GROUP",
                            label: "Name"
                        }),
                        search.createColumn({
                            name: "inventorylocation",
                            summary: "GROUP",
                            label: "Inventory Location"
                        }),
                        search.createColumn({
                            name: "internalid",
                            summary: "GROUP",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "quantity",
                            join: "transaction",
                            summary: "SUM",
                            sort: search.Sort.ASC,
                            label: "Quantity"
                        })
                    ]
                });
                var searchResultCount = itemSearchObj.runPaged().count;
                log.debug("itemSearchObj result count", searchResultCount);
                var dataarray = {};
                itemSearchObj.run().each(function(result) {

                    var internalid = result.getValue({
                        name: "internalid",
                        summary: "GROUP",
                        label: "Internal ID"
                    });
                    var location = result.getValue({
                        name: "inventorylocation",
                        summary: "GROUP",
                        label: "Inventory Location"
                    });
                    var itemname = result.getValue({
                        name: "itemid",
                        summary: "GROUP",
                        label: "Name"
                    });
                    var quantity = result.getValue({
                        name: "quantity",
                        join: "transaction",
                        summary: "SUM",
                        label: "Quantity"
                    });
                    //   log.debug("location",location);
                    dataarray[internalid + location + itemname] = quantity;
                    return true;
                });
                return dataarray;
            },
            /*To Find  Exchange Rate */
            findexchangerate: function(currencyin) {
                var rate = currency.exchangeRate({
                    source: currencyin,
                    target: 'NZD',
                    date: new Date()
                });
                return rate
            },
            /*In Future If there is any sublist action */
            setsublist: function(itemdetails, sublist) {

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

        function trycatch(myfunction, key) {
            return function() {
                try {
                    return myfunction.apply(this, arguments);
                } catch (e) {
                    log.debug("e in  " + key, e);
                }
            }
        };
        return main;

    });

HTL-1 SL Order Items Page Customization

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * HTL
 * **************************************************************************
 * 
 * Date: 11-06-2018
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/email', 'N/file', 'N/currency', 'N/https', 'N/record', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/ui/serverWidget'],
    /**
     * @param {email} email
     * @param {file} file
     * @param {http} http
     * @param {https} https
     * @param {record} record
     * @param {runtime} runtime
     * @param {search} search
     * @param {serverWidget} serverWidget
     */
    function(email, file, currency, https, record, runtime, search, serverWidget) {
        var currencyobj = {};
        var main = {
            onRequest: function(context) {
                /*UI Part */
                if (context.request.method === 'GET') {
                    var locationid = context.request.parameters.locationid;
                    var supplierid = context.request.parameters.supplierid;
                    var minquantityfil = context.request.parameters.minquantity;
                    var supplierobj = main.getdata();

                    supplierobj = JSON.parse(supplierobj);
                    log.debug("supplierobj", supplierobj);
                    var form = serverWidget.createForm({
                        title: 'Order Items '
                    });
                    var location = form.addField({
                        id: 'location',
                        type: serverWidget.FieldType.SELECT,
                        label: 'Location',
                        source: 'location'
                    });
                    form.addButton({
                        id: 'backbu',
                        label: 'Go Back',
                        functionName: 'back'
                    });
                    var supplier = form.addField({
                        id: 'supplier',
                        type: serverWidget.FieldType.SELECT,
                        label: 'supplier',
                        source: 'vendor'
                    });
                    var minquantity = form.addField({
                        id: 'minquantity',
                        type: serverWidget.FieldType.TEXT,
                        label: 'MINIMUM QUANTITY'
                    });
                    if (locationid == null || locationid == "") {
                        var locationfilter = ["inventorylocation", "noneof", "@NONE@"];
                    } else {
                        location.defaultValue = locationid;

                        var locationfilter = ["inventorylocation", "anyof", locationid];
                    }
                    if (supplierid == null || supplierid == "") {
                        var supplierfilter = ["othervendor", "noneof", "@NONE@"];
                    } else {
                        var supplierfilter = ["othervendor", "anyof", supplierid]
                        supplier.defaultValue = supplierid;

                    }
                    if (minquantityfil == null || minquantityfil == "") {
                        minquantityfil = 0;
                        var minquantityfilter = ["formulanumeric: NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))", "isnotempty", ""];
                    } else {
                        minquantity.defaultValue = minquantityfil;

                        var minquantityfilter = ["formulanumeric: NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))", "notlessthan", minquantityfil];
                        var minquantityfilter = ["formulanumeric: NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))", "isnotempty", ""];
                    }
                    var userObj = runtime.getCurrentUser();
                    log.debug({ title: "userObj", details: userObj });
                    var role = userObj.role;
                    var subsidiary = userObj.subsidiary;
                    var empid = userObj.id;
                    var newsub = form.addSublist({
                        id: 'itemslist',
                        type: serverWidget.SublistType.LIST,
                        label: 'Item Details'
                    });
                    newsub.addMarkAllButtons();
                    var checkbox = newsub.addField({
                        id: 'custpage_check',
                        label: 'check',
                        type: serverWidget.FieldType.CHECKBOX
                    });
                    checkbox.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    var location = newsub.addField({
                        id: 'listlocation',
                        label: 'LOCATION',
                        type: serverWidget.FieldType.TEXT
                    });
                    var locationid = newsub.addField({
                        id: 'listlocationid',
                        label: 'LOCATION',
                        type: serverWidget.FieldType.TEXT
                    });
                    locationid.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });

                    var internalid = newsub.addField({
                        id: 'iteminternalid',
                        label: 'Hidden',
                        type: serverWidget.FieldType.TEXT
                    });
                    internalid.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                    var item = newsub.addField({
                        id: 'itemname',
                        label: 'ITEM',
                        type: serverWidget.FieldType.TEXT
                    });
                    var description = newsub.addField({
                        id: 'itemdescription',
                        label: 'DESCRIPTION',
                        type: serverWidget.FieldType.TEXT
                    });
                    var supplierid = newsub.addField({
                        id: 'custpage_supplierid',
                        label: 'SUPPLIERid',
                        type: serverWidget.FieldType.TEXT
                    });
                    supplierid.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });

                    var currency = newsub.addField({
                        id: 'currency',
                        label: 'CURRENCY',
                        type: serverWidget.FieldType.SELECT,
                        source: "currency"
                    });
                    currency.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                    var available = newsub.addField({
                        id: 'available',
                        label: 'AVAILABLE',
                        type: serverWidget.FieldType.TEXT
                    });
                    var backordered = newsub.addField({
                        id: 'backordered',
                        label: 'BACK ORDERED',
                        type: serverWidget.FieldType.TEXT
                    });
                    var onorder = newsub.addField({
                        id: 'onorder',
                        label: 'ON ORDER',
                        type: serverWidget.FieldType.TEXT
                    });
                    var reorderpoint = newsub.addField({
                        id: 'reorderpoint',
                        label: 'REORDER POINT',
                        type: serverWidget.FieldType.TEXT
                    });
                    var prefferedstock = newsub.addField({
                        id: 'prefferedstock',
                        label: 'PREFERRED STOCK LEVEL',
                        type: serverWidget.FieldType.TEXT
                    });
                    var ignorequantity = newsub.addField({
                        id: 'ignorequantity',
                        label: 'Ignore QUANTITY',
                        type: serverWidget.FieldType.TEXT
                    });
                    var ignorequantity = newsub.addField({
                        id: 'tempquantity',
                        label: 'Orginal QUANTITY',
                        type: serverWidget.FieldType.TEXT
                    });
                    var supplierdeliverydate = newsub.addField({
                        id: 'supplierdeliverydate',
                        label: 'Supplier Delivery Date',
                        type: serverWidget.FieldType.DATE
                    });
                    supplierdeliverydate.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                    var quantity = newsub.addField({
                        id: 'quantity',
                        label: 'QUANTITY',
                        type: serverWidget.FieldType.TEXT
                    });
                    quantity.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });

                    var rateforiegn = newsub.addField({
                        id: 'rateforiegn',
                        label: 'RATE (FOREIGN CURRENCY)',
                        type: serverWidget.FieldType.TEXT
                    });
                    rateforiegn.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    var exchangerate = newsub.addField({
                        id: 'exchangerate',
                        label: 'exchangerate',
                        type: serverWidget.FieldType.TEXT
                    });
                    exchangerate.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    exchangerate.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                    var totalforiegn = newsub.addField({
                        id: 'totalforiegn',
                        label: 'TOTAL (FOREIGN CURRENCY)',
                        type: serverWidget.FieldType.TEXT
                    });
                    totalforiegn.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    totalforiegn.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                    var rate = newsub.addField({
                        id: 'rate',
                        label: 'RATE',
                        type: serverWidget.FieldType.TEXT
                    });
                    rate.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    rate.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                    var total = newsub.addField({
                        id: 'total',
                        label: 'TOTAL',
                        type: serverWidget.FieldType.TEXT
                    });
                    total.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    total.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });
                    var supplier = newsub.addField({
                        id: 'custpage_supplier',
                        label: 'SUPPLIER',
                        type: serverWidget.FieldType.SELECT,
                        source: "vendor"
                    });
                    supplier.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                    var units = newsub.addField({
                        id: 'units',
                        label: 'UNITS',
                        type: serverWidget.FieldType.TEXT
                    });
                    form.clientScriptFileId = '250673';
                    form.addSubmitButton({
                        label: 'Order Items'
                    });
                    context.response.writePage(form);
                    var itemdetails = main.finditems(locationfilter, minquantityfilter, supplierfilter, supplierobj);
                    main.setsublist(itemdetails, newsub, minquantityfil);
                } else {
                    /*Post Part / Result  page */
                    var itemslist = context.request.parameters.itemslist;
                    var lines = context.request.getLineCount({ group: "itemslist" });
                    var poarray = {};
                    /*getting Sublist values */
                    for (var i = 0; i < lines; i++) {

                        var chkboxvalue = context.request.getSublistValue({
                            group: 'itemslist',
                            name: 'custpage_check',
                            line: i
                        });
                        if (chkboxvalue == 'T') {
                            /*getting Sublist values which are marked  */
                            var supplierid = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'custpage_supplier',
                                line: i
                            });
                            var poobj = {};
                            poobj.location = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'listlocationid',
                                line: i
                            });
                            poobj.supplierdeliverydate = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'supplierdeliverydate',
                                line: i
                            });
                            poobj.iteminternal = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'iteminternalid',
                                line: i
                            });
                            poobj.rate = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'rate',
                                line: i
                            });
                            poobj.rateforiegn = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'rateforiegn',
                                line: i
                            });
                            poobj.description = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'itemdescription',
                                line: i
                            });
                            poobj.quantity = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'quantity',
                                line: i
                            });
                            poobj.amount = context.request.getSublistValue({
                                group: 'itemslist',
                                name: 'total',
                                line: i
                            });

                            var check = poarray[supplierid];
                            if (check == undefined || check == "" || check == null) {
                                poarray[supplierid] = [];
                                poarray[supplierid].push(poobj);
                            } else {
                                poarray[supplierid].push(poobj);
                            }
                        }
                    }
                    log.debug("poarray", poarray);
                    main.createfile(poarray, "poarray");
                    var form = serverWidget.createForm({
                        title: 'Order Items Status'
                    });
                    form.addButton({
                        id: 'backbut',
                        label: 'Go Back',
                        functionName: 'back'
                    });
                    var newsub = form.addSublist({
                        id: 'status',
                        type: serverWidget.SublistType.LIST,
                        label: 'Name'
                    });
                    var status = newsub.addField({
                        id: 'name',
                        label: 'Name',
                        type: serverWidget.FieldType.SELECT,
                        source: "vendor"
                    });
                    status.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                    var status = newsub.addField({
                        id: 'status',
                        label: 'Status',
                        type: serverWidget.FieldType.TEXT
                    });
                    var transaction = newsub.addField({
                        id: 'transaction',
                        label: 'Transaction',
                        type: serverWidget.FieldType.SELECT,
                        source: "transaction"
                    });
                    transaction.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });
                    var amount = newsub.addField({
                        id: 'amount',
                        label: 'Amount',
                        type: serverWidget.FieldType.TEXT
                    });
                    form.clientScriptFileId = '250673';
                    context.response.writePage(form);
                    var j = 0;
                    for (var index in poarray) {
                        main.createpo(poarray[index], index, newsub, j);
                        j++
                    }
                }
            },
            /*Create PO Action*/
            createpo: function(podata, vendor, sublist, j) {
                log.debug("podata.len", podata.length);
                log.debug("index", vendor);
                var locobj = {}
                for (var i = 0; i < podata.length; i++) {
                    var check = locobj[podata[i].location];
                    if (check == undefined || check == "" || check == null) {
                        locobj[podata[i].location] = [];
                        locobj[podata[i].location].push(podata[i]);
                    } else {
                        locobj[podata[i].location].push(podata[i]);
                    }
                }
                log.debug("locobj", locobj);
                for (var index in locobj) {
                    var vendorobj = record.load({
                        type: "vendor",
                        id: vendor
                    })
                    var taxcode = vendorobj.getValue({
                        fieldId: "taxitem"
                    });
                    if (taxcode == "" || taxcode == null)
                        taxcode = 6
                    log.debug("taxcode", taxcode);

                    var POrecord = record.transform({
                        fromType: record.Type.VENDOR,
                        fromId: vendor,
                        toType: record.Type.PURCHASE_ORDER,
                        isDynamic: true,
                    });
                    log.debug("locobj[index].supplierdeliverydate", locobj[index][0].supplierdeliverydate)


                    POrecord.setText({
                        fieldId: 'custbody5',
                        text: locobj[index][0].supplierdeliverydate,
                        ignoreFieldChange: false
                    });

                    POrecord.setValue({
                        fieldId: 'location',
                        value: index,
                        ignoreFieldChange: false
                    });
                    var totalamount = 0;
                    var errorarray = [];
                    for (var i = 0; i < locobj[index].length; i++) {
                        try {
                            /* var lineNum = POrecord.selectLine({
                                 sublistId: 'item',
                                 line: i
                             });*/

                            var lineNum = POrecord.selectNewLine({
                                sublistId: 'item'
                            });
                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'item',
                                value: locobj[index][i].iteminternal,
                                ignoreFieldChange: true
                            });
                            log.debug("locobj[index][i].iteminternal", locobj[index][i].iteminternal);

                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'quantity',
                                value: locobj[index][i].quantity,
                                ignoreFieldChange: true
                            });
                            log.debug("locobj[index][i].quantity", locobj[index][i].quantity);
                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'description',
                                value: locobj[index][i].description,
                                ignoreFieldChange: true
                            });
                            log.debug("locobj[index][i].description", locobj[index][i].description);
                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'rate',
                                value: (parseFloat(locobj[index][i].rateforiegn)).toFixed(2),
                                ignoreFieldChange: true
                            });
                            log.debug("locobj[index][i].rateforiegn", (parseFloat(locobj[index][i].rateforiegn)).toFixed(2));
                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'taxcode',
                                value: taxcode,
                                ignoreFieldChange: true
                            });
                            totalamount += parseFloat(locobj[index][i].amount);
                            POrecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'amount',
                                value: (parseFloat(locobj[index][i].amount)).toFixed(2),
                                ignoreFieldChange: true
                            });
                            log.debug("locobj[index][i].amount", (parseFloat(locobj[index][i].amount)).toFixed(2));
                            POrecord.commitLine({
                                sublistId: 'item'
                            });
                        } catch (e) {
                            errorarray.push(locobj[index][i].iteminternal);
                            log.debug("e", e);
                            // i = i - 1;
                        }
                    }
                    var id = POrecord.save({
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    });

                    log.debug("id", id);
                    log.debug("JJJJ", j);

                    main.createfile(errorarray, "errorarray");
                    sublist.setSublistValue({
                        id: 'name',
                        line: j,
                        value: vendor
                    });

                    sublist.setSublistValue({
                        id: 'status',
                        line: j,
                        value: "complete"
                    });
                    sublist.setSublistValue({
                        id: 'transaction',
                        line: j,
                        value: id
                    });
                    sublist.setSublistValue({
                        id: 'amount',
                        line: j,
                        value: totalamount
                    });
                    j++
                    log.debug("JJJaaJ", j);

                }
            },
            /*Create JSON File */
            createfile: function(netsuitedata, name) {
                if (netsuitedata == null || netsuitedata == "" || netsuitedata == undefined)
                    netsuitedata = { "rambo": "always" }
                var fileObj = file.create({
                    name: name + '.txt',
                    fileType: file.Type.JSON,
                    contents: JSON.stringify(netsuitedata),
                    encoding: file.Encoding.UTF8,
                    folder: 226002,
                    isOnline: true
                });
                var fileid = fileObj.save();
                log.debug("fileid", fileid);
            },
            /*Item Search To display the results on order Page */
            finditems: function(locationfilter, minquantityfilter, supplierfilter, supplierobj) {
                var filterset = [
                    ["cost", "greaterthan", "0.00"],
                    "AND", ["locationpreferredstocklevel", "greaterthanorequalto", "0"],
                    "AND", ["isinactive", "is", "F"]
                ];
                filterset.push("AND", locationfilter, "AND", minquantityfilter, "AND", supplierfilter) //, "AND", supplierfilter
                /*        "AND", ["othervendor", "anyof", supplierid],
                   "AND", ["formulanumeric: NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))", "greaterthanorequalto", minquantityfil]*/
                var itemSearchObj = search.create({
                    type: "item",
                    filters: filterset,
                    columns: [
                        search.createColumn({ name: "itemid", sort: search.Sort.ASC, label: "Name" }),
                        search.createColumn({ name: "salesdescription", label: "Description" }),
                        search.createColumn({ name: "internalid", label: "internalid" }),
                        search.createColumn({ name: "othervendor", label: "Supplier" }),
                        search.createColumn({ name: "unitstype", label: "Units Type" }),
                        search.createColumn({ name: "cost", label: "Purchase Price" }),
                        search.createColumn({ name: "fxcost", label: "Purchase Price (Foreign Currency)" }),
                        search.createColumn({ name: "currency", join: "vendor", label: "Currency" }),
                        search.createColumn({ name: "inventorylocation", label: "Inventory Location" }),
                        search.createColumn({ name: "locationpreferredstocklevel", label: "Location Preferred Stock Level" }),
                        search.createColumn({ name: "locationreorderpoint", label: "Location Reorder Point" }),
                        search.createColumn({ name: "locationquantityavailable", label: "Location Available" }),
                        search.createColumn({ name: "locationquantityonorder", label: "Location On Order" }),
                        search.createColumn({ name: "locationquantitybackordered", label: "Location Back Ordered" }),
                        search.createColumn({
                            name: "formulanumeric",
                            formula: "NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))",
                            label: "Formula (Numeric)"
                        })
                    ]
                });
                var searchResultCount = itemSearchObj.runPaged().count;
                log.debug("itemSearchObj result count", searchResultCount);
                var dataarray = [];
                var i = 0;
                itemSearchObj.run().each(function(result) {
                    i++;
                    var dataobj = {};
                    dataobj.itemid = main.checkifnull(result.getValue("itemid"));
                    dataobj.salesdescription = main.checkifnull(result.getValue("salesdescription"));
                    dataobj.internalid = main.checkifnull(result.getValue("internalid"));


                    dataobj.othervendor = main.checkifnull(result.getValue("othervendor"));
                    dataobj.unitstype = main.checkifnull(result.getText("unitstype"));
                    dataobj.cost = main.checkifnull(result.getValue("cost"));
                    dataobj.fxcost = main.checkifnull(result.getValue("fxcost"));
                    dataobj.currency = main.checkifnull(result.getValue({ name: "currency", join: "vendor" }));
                    dataobj.currencytext = main.checkifnull(result.getText({ name: "currency", join: "vendor" }));
                    dataobj.exchangerate = main.findexchangerate(dataobj.currencytext);
                    dataobj.cost = dataobj.fxcost * dataobj.exchangerate;
                    dataobj.inventorylocation = main.checkifnull(result.getText("inventorylocation"));
                    dataobj.inventorylocationid = main.checkifnull(result.getValue("inventorylocation"));

                    dataobj.inventorylocationid = main.checkifnull(result.getValue("inventorylocation"));

                    dataobj.supplierqty = supplierobj[dataobj.internalid + dataobj.inventorylocationid + dataobj.itemid]
                    dataobj.supplierqty = main.checkifnull(dataobj.supplierqty);
                    dataobj.locationpreferredstocklevel = main.checkifnull(result.getValue("locationpreferredstocklevel"));
                    dataobj.locationreorderpoint = main.checkifnull(result.getValue("locationreorderpoint"));
                    dataobj.locationquantityavailable = main.checkifnull(result.getValue("locationquantityavailable"));
                    dataobj.locationquantityonorder = main.checkifnull(result.getValue("locationquantityonorder"));
                    dataobj.locationquantitybackordered = main.checkifnull(result.getValue("locationquantitybackordered"));
                    dataobj.quantity = result.getValue({
                        name: "formulanumeric",
                        formula: "NVL({locationpreferredstocklevel},0) - ( NVL({locationquantityavailable},0) + NVL({locationquantityonorder},0) - NVL({locationquantitybackordered},0))",
                        label: "Formula (Numeric)"
                    });
                    dataobj.newquantity = parseFloat(dataobj.quantity) + parseFloat(dataobj.supplierqty);
                    dataarray.push(dataobj);
                    return true;
                });
                return dataarray;
            },
            /*To Find Exchange Rate */
            findexchangerate: function(currencyin) {

                var rate = currencyobj[currencyin];
                if (rate == undefined || rate == "" || rate == null) {
                    var rate = currency.exchangeRate({
                        source: currencyin,
                        target: 'NZD',
                        date: new Date()
                    });
                    currencyobj[currencyin] = rate;
                }
                return rate;
            },
            /*Set Sublist Values */
            setsublist: function(itemdetails, sublist, minquantityfil) {
                var j = 0;
                for (var i = 0; i < itemdetails.length; i++) {
                    /*                    Object.keys(itemdetails[i]).forEach(function(key) {
                                            itemdetails[i][key] = main.checkifnull(itemdetails[i][key]);
                                        });*/
                    //   log.debug("itemdetails[i].newquantity ", itemdetails[i].newquantity);
                    //     log.debug("minquantityfil", minquantityfil);

                    if (parseFloat(itemdetails[i].newquantity) > parseInt(minquantityfil)) {

                        sublist.setSublistValue({
                            id: 'custpage_check',
                            line: j,
                            value: 'F'
                        });

                        sublist.setSublistValue({
                            id: 'listlocation',
                            line: j,
                            value: itemdetails[i].inventorylocation
                        });

                        sublist.setSublistValue({
                            id: 'listlocationid',
                            line: j,
                            value: itemdetails[i].inventorylocationid
                        });

                        sublist.setSublistValue({
                            id: 'iteminternalid',
                            line: j,
                            value: itemdetails[i].internalid
                        });

                        sublist.setSublistValue({
                            id: 'itemname',
                            line: j,
                            value: itemdetails[i].itemid
                        });

                        sublist.setSublistValue({
                            id: 'itemdescription',
                            line: j,
                            value: itemdetails[i].salesdescription
                        });

                        sublist.setSublistValue({
                            id: 'custpage_supplier',
                            line: j,
                            value: itemdetails[i].othervendor
                        });

                        sublist.setSublistValue({
                            id: 'currency',
                            line: j,
                            value: itemdetails[i].currency
                        });

                        var date = new Date();
                        var month = date.getMonth() + 1
                        date = date.getDate() + "/" + month + "/" + date.getFullYear();

                        sublist.setSublistValue({
                            id: 'supplierdeliverydate',
                            line: j,
                            value: date
                        });

                        sublist.setSublistValue({
                            id: 'units',
                            line: j,
                            value: itemdetails[i].unitstype
                        });

                        sublist.setSublistValue({
                            id: 'available',
                            line: j,
                            value: itemdetails[i].locationquantityavailable
                        });

                        sublist.setSublistValue({
                            id: 'backordered',
                            line: j,
                            value: itemdetails[i].locationquantitybackordered
                        });

                        sublist.setSublistValue({
                            id: 'onorder',
                            line: j,
                            value: itemdetails[i].locationquantityonorder
                        });

                        sublist.setSublistValue({
                            id: 'reorderpoint',
                            line: j,
                            value: itemdetails[i].locationreorderpoint
                        });

                        sublist.setSublistValue({
                            id: 'prefferedstock',
                            line: j,
                            value: itemdetails[i].locationpreferredstocklevel
                        });

                        sublist.setSublistValue({
                            id: 'tempquantity',
                            line: j,
                            value: itemdetails[i].quantity
                        });

                        sublist.setSublistValue({
                            id: 'quantity',
                            line: j,
                            value: itemdetails[i].newquantity
                        });

                        sublist.setSublistValue({
                            id: 'ignorequantity',
                            line: j,
                            value: itemdetails[i].supplierqty
                        });

                        sublist.setSublistValue({
                            id: 'rateforiegn',
                            line: j,
                            value: itemdetails[i].fxcost
                        });

                        sublist.setSublistValue({
                            id: 'totalforiegn',
                            line: j,
                            value: itemdetails[i].fxcost * itemdetails[i].newquantity
                        });

                        sublist.setSublistValue({
                            id: 'rate',
                            line: j,
                            value: /*itemdetails[i].cost*/ itemdetails[i].fxcost
                        });

                        sublist.setSublistValue({
                            id: 'exchangerate',
                            line: j,
                            value: itemdetails[i].exchangerate
                        });

                        sublist.setSublistValue({
                            id: 'total',
                            line: j,
                            value: itemdetails[i].fxcost * itemdetails[i].newquantity
                        });
                        j++
                    }
                }
                log.debug("num of lines ", j)
            },
            checkifnull: function(data) {
                if (data == "" || data == null) {
                    return 0
                } else {
                    return data
                }
            },
            getdata: function(type) {
                /*              var fileSearchObj = search.create({
                                  type: "file",
                                  filters: [
                                      ["name", "is", type + ".txt"]
                                  ],
                                  columns: [
                                      search.createColumn({
                                          name: "name",
                                          sort: search.Sort.ASC,
                                          label: "Name"
                                      }),
                                      search.createColumn({ name: "internalid", label: "Internal ID" })
                                  ]
                              });
                              var searchResultCount = fileSearchObj.runPaged().count;
                              var fileid = 0;
                              fileSearchObj.run().each(function(result) {
                                  fileid = result.getValue("internalid");
                              });
                              log.debug("fileid", fileid);*/
                var fileObj = file.load({
                    id: 260317
                });
                if (fileObj.size < 10485760) {
                    var JSON = fileObj.getContents();
                }
                return JSON
            }
        }
        for (var key in main) {
            if (typeof main[key] === 'function') {
                main[key] = trycatch(main[key], key);
            }
        }

        function trycatch(myfunction, key) {
            return function() {
                try {
                    return myfunction.apply(this, arguments);
                } catch (e) {
                    log.debug("e in  " + key, e);
                }
            }
        };
        return main;

    });

HTL-1 CL Order Items Page Support

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * HTL
 * **************************************************************************
 * 
 * Date: 11-06-2018
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/http', 'N/https', 'N/record', 'N/runtime', 'N/url', 'N/currency'],

    function(http, https, record, runtime, url, currency) {

        var main = {
            /*Page Init Fucntion */
            pageInit: function(scriptContext) {
                window.onbeforeunload = function() {
                    // blank function do nothing
                }
                jQuery(".uir-custom-field").blur(function() {
                    main.dothemath(jQuery(this)[0]);
                });
                jQuery("#tdbody_submitter").click(function() {
                    var checkarray = jQuery('.checkbox')
                    var count = 0;
                    for (var i = 0; i < checkarray.length; i++) {
                        if (checkarray[i].checked) {
                            count++
                        }
                    }
                    if (count < 1) {
                        if (confirm("Warning No fields Selected ")) {

                        }
                    }
                });
                jQuery("#tdbody_secondarysubmitter").click(function() {
                    var checkarray = jQuery('.checkbox')
                    var count = 0;
                    for (var i = 0; i < checkarray.length; i++) {
                        if (checkarray[i].checked) {
                            count++
                        }
                    }
                    if (count < 1) {
                        if (confirm("Warning No fields Selected ")) {

                        }
                    }
                });
            },
            /*Back button Function*/
            back: function() {
                window.history.back()


            },
            /*Field Change Event */
            fieldChanged: function(scriptContext) {
                var records = scriptContext.currentRecord;
                var currenturl = url.resolveScript({
                    scriptId: "customscripthtl_1_sl_order_items_page",
                    deploymentId: "customdeployhtl_1_sl_order_items_page",
                    returnExternalUrl: false
                });
                if (scriptContext.fieldId == 'location') {
                    var locationid = records.getValue('location');
                    var supplierid = records.getValue('supplier');
                    var minquantity = records.getValue('minquantity');
                    window.location.href = currenturl + "&locationid=" + locationid + "&supplierid=" + supplierid + "&minquantity=" + minquantity;
                }
                if (scriptContext.fieldId == 'supplier') {
                    var locationid = records.getValue('location');
                    var supplierid = records.getValue('supplier');
                    var minquantity = records.getValue('minquantity');
                    window.location.href = currenturl + "&locationid=" + locationid + "&supplierid=" + supplierid + "&minquantity=" + minquantity;

                }
                if (scriptContext.fieldId == 'minquantity') {
                    var locationid = records.getValue('location');
                    var supplierid = records.getValue('supplier');
                    var minquantity = records.getValue('minquantity');
                    window.location.href = currenturl + "&locationid=" + locationid + "&supplierid=" + supplierid + "&minquantity=" + minquantity;
                }
            },
            /*On Save Action ,Currently No save action  */

            ssaveRecord: function(scriptContext) {

                // alert("af")

            },
            /*To For calculating the Exchange Rate  */

            dothemath: function(field) {
                var id = field.id;
                console.log('id', id);
                if (id.indexOf("quantity") > -1) {
                    var linenum = id.substring(8);
                    var rateid = "#rateforiegn" + linenum;
                    var exchangerateid = "#exchangerate" + linenum;
                    var currency = jQuery('[name="inpt_currency' + linenum + '"]').val();
                    var exchangerate = jQuery(exchangerateid).val();
                    var rate = jQuery(rateid).val();
                    var quantity = field.value;
                    console.log('exchangerate   ' + 1);
                    console.log('rate   ' + rate);
                    console.log('quantity   ' + quantity);
                    console.log('currency   ' + currency);


                    var totalfieldid = "#totalforiegn" + linenum;
                    jQuery(totalfieldid).val(quantity * rate);

                    //            jQuery("#rate" + linenum).val( rate);

                    jQuery("#total" + linenum).val(quantity * rate * 1);

                }
                if (id.indexOf("rateforiegn") > -1) {
                    var linenum = id.substring(11);
                    var quantityid = "#quantity" + linenum;
                    var exchangerateid = "#exchangerate" + linenum;
                    var currency = jQuery('[name="inpt_currency' + linenum + '"]').val();
                    var quantity = jQuery(quantityid).val();
                    var rate = field.value;
                    var exchangerate = jQuery(exchangerateid).val();
                    console.log('exchangerate   ' + exchangerate);
                    console.log('rate   ' + rate);
                    console.log('quantity   ' + quantity);
                    console.log('currency   ' + currency);

                    var totalfieldid = "#totalforiegn" + linenum;
                    jQuery(totalfieldid).val(quantity * rate);

                  //  jQuery("#rate" + linenum).val(exchangerate * rate);

                   // jQuery("#total" + linenum).val(quantity * exchangerate * rate);

                    jQuery("#rate" + linenum).val(1 * rate);

                    jQuery("#total" + linenum).val(quantity * 1 * rate);

                }
            },
            /*To find Exchange Rate */
            exchangerate: function(currencies) {
                var rate = currency.exchangeRate({
                    source: currencies,
                    target: 'NZD',
                    date: new Date()
                });
            }
        };
        for (var key in main) {
            if (typeof main[key] === 'function') {
                main[key] = trycatch(main[key], key);
            }
        }

        function trycatch(myfunction, key) {
            return function() {
                try {
                    return myfunction.apply(this, arguments);
                } catch (e) {
                    console.error('e', e);
                }
            }
        };
        return main
    });

Leave a comment

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