Item Pricing Customization

Customization function to copy the custom price from one customer to other customers which belong to the same group. The group is determined by custom field updated for each customer. Since there is a chance that the governance might exceed while updating the customer along with suitelet and Map Reduce script is been used to copy the item pricing.

Suitelet

    /**
     * @NApiVersion 2.x
     * @NScriptType Suitelet
     * @NModuleScope SameAccount
     */
    /*******************************************************************************
     * BTN-621  Customer Pricing 
     * **************************************************************************
     * 
     * Date: 18-04-2019
     * 
     * Author: Jobin & Jismi IT Services LLP
     * 
     *****************************************************************************
     **/
    define(['N/email', 'N/file', 'N/url', 'N/https', 'N/record', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/task'],
        /**
         * @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, url, https, record, runtime, search, serverWidget, task) {
            var currencyobj = {};
            var main = {
                onRequest: function(context) {
                    /*UI Part */
                    if (context.request.method === 'GET') {
                        var category = context.request.parameters.category;
                        var customer = context.request.parameters.customer;
                        var copyFile = context.request.parameters.fileid;

                        var form = serverWidget.createForm({
                            title: 'Customers Pricing '
                        });
                        var customerCategory = form.addField({
                            id: 'category',
                            type: serverWidget.FieldType.SELECT,
                            label: 'Category',
                            source: 'customer'
                        });
                        var currentCustomer = form.addField({
                            id: 'currentcustomer',
                            type: serverWidget.FieldType.TEXT,
                            label: 'currentcustomer'
                        });
                        currentCustomer.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                        currentCustomer.defaultValue = customer;
                        var fileId = form.addField({
                            id: 'fileid',
                            type: serverWidget.FieldType.TEXT,
                            label: 'fileid'
                        });
                        fileId.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                        fileId.defaultValue = copyFile;
                        customerCategory.updateDisplayType({ displayType: serverWidget.FieldDisplayType.DISABLED });

                        customerCategory.defaultValue = category;
                        var userObj = runtime.getCurrentUser();
                        var role = userObj.role;
                        var subsidiary = userObj.subsidiary;
                        var empid = userObj.id;
                        var newsub = form.addSublist({
                            id: 'customerlist',
                            type: serverWidget.SublistType.LIST,
                            label: 'Customers'
                        });
                        newsub.addMarkAllButtons();
                        var checkbox = newsub.addField({
                            id: 'custpage_check',
                            label: 'check',
                            type: serverWidget.FieldType.CHECKBOX
                        });
                        checkbox.updateDisplayType({ displayType: serverWidget.FieldDisplayType.ENTRY });
                        var internalid = newsub.addField({
                            id: 'internalids',
                            label: 'Internal Id ',
                            type: serverWidget.FieldType.TEXT
                        });
                        internalid.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                        var customers = newsub.addField({
                            id: 'customersid',
                            label: 'ID',
                            type: serverWidget.FieldType.TEXT
                        });

                        var customers = newsub.addField({
                            id: 'customers',
                            label: 'Customer',
                            type: serverWidget.FieldType.TEXT
                        });
                        form.clientScriptFileId = '327194';
                        form.addSubmitButton({
                            label: 'Apply Pricing '
                        });
                        form.addButton({
                            id: 'close',
                            label: 'Cancel',
                            functionName: 'closewindow'
                        });
                        context.response.writePage(form);
                        var customersList = main.findCustomers(category, customer);
                        main.setsublist(customersList, newsub);
                    } else {
                        /*Post Part / Result  page */
                        var customerlist = context.request.parameters.customerlist;
                        var customer = context.request.parameters.currentcustomer;

                        var body = context.request.body;
                        log.debug("body", body);
                        if (body == null || body == "" || body === undefined) {
                            var lines = context.request.getLineCount({ group: "customerlist" });
                            var customerArray = [];
                            /*getting Sublist values */
                            for (var i = 0; i < lines; i++) {
                                var chkboxValue = context.request.getSublistValue({
                                    group: 'customerlist',
                                    name: 'custpage_check',
                                    line: i
                                });
                                if (chkboxValue == 'T') {
                                    /* getting Sublist values which are marked*/
                                    var customerId = context.request.getSublistValue({
                                        group: 'customerlist',
                                        name: 'internalids',
                                        line: i
                                    });
                                    customerArray.push(customerId);
                                }
                            }
                            var fileId = main.createfile(customerArray, "customerArray");
                            var customerFile = context.request.parameters.fileid;
                            log.debug("customerFile", customerFile);
                            main.scheduleanother(fileId, customerFile);
                            var form = serverWidget.createForm({
                                title: ' Status'
                            });
                            var statsss = form.addField({
                                id: 'statsss',
                                type: serverWidget.FieldType.TEXT,
                                label: 'statsss'
                            });
                            statsss.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
                            statsss.defaultValue = "success";
                            form.clientScriptFileId = '327194';
                            context.response.writePage(form);

                        } else {
                            var fileId = main.createfile(body, "copyarray");
                            log.debug("fileId", fileId);
                            context.response.write(fileId.toString());
                        }
                    }
                },

                /*Setup map reduce script*/
                scheduleanother: function(fileid, customer) {
                    log.debug("customer", customer);
                    log.debug("fileid", fileid);

                    var scheduleScrptTask = task.create({
                        taskType: task.TaskType.MAP_REDUCE,
                        scriptId: "customscripthtl_2_mu_update_item_pricing",
                        deploymentId: 'customdeployhtl_2_mu_update_item_pricing',
                        params: {
                            custscript_jj_fileid: fileid,
                            custscript_jj_customer_id: customer
                        }
                    });
                    scheduleScrptTask.submit();
                },
                /*Customer  Search To display the results based on Category*/
                findCustomers: function(category, customers) {
                    log.debug("customers", customers);
                    var customerSearchObj = search.create({
                        type: "customer",
                        filters: [
                            ["custentity28", "anyof", category], "AND", ["internalid", "noneof", customers],
                            "AND", ["isinactive", "is", "F"]
                        ],
                        columns: [
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({ name: "custentity15", label: "Cust Category" }),
                            search.createColumn({ name: "altname", label: "Name" }),
                            search.createColumn({ name: "entityid", label: "ID" })
                        ]
                    });
                    var searchResultCount = customerSearchObj.runPaged().count;
                    var customerArray = [];
                    if (searchResultCount < 1000) {
                        customerSearchObj.run().each(function(result) {
                            var customTemp = {};
                            customTemp.internalid = result.getValue("internalid");
                            customTemp.id = result.getValue("entityid");
                            customTemp.name = result.getValue("altname");
                            customerArray.push(customTemp);
                            return true;
                        });

                        return customerArray;
                    } else {
                        var searchPageRanges = customerSearchObj.runPaged({
                            pageSize: 500
                        });
                        var currentdataobj = {};
                        currentdataobj.custom_field_options = [];
                        for (var i = 0; i < searchPageRanges.pageRanges.length; i++) {
                            searchPageRanges.fetch({
                                index: i
                            }).data.forEach(function(result) {
                                var customTemp = {};
                                customTemp.internalid = result.getValue("internalid");
                                customerArray.push(customTemp);
                                return true;
                            });
                        }
                        return customerArray;

                    }

                },
                /*Set Sublist Values */
                setsublist: function(customerDetails, sublist) {
                    for (var i = 0; i < customerDetails.length; i++) {

                        var relativePath = url.resolveRecord({
                            recordType: "customer",
                            recordId: customerDetails[i].internalid,
                            isEditMode: false
                        });
                        sublist.setSublistValue({
                            id: 'custpage_check',
                            line: i,
                            value: 'T'
                        });
                        sublist.setSublistValue({
                            id: 'internalids',
                            line: i,
                            value: customerDetails[i].internalid
                        });
                        sublist.setSublistValue({
                            id: 'customersid',
                            line: i,
                            value: '<a href="' + relativePath + '" target="_blank">' + customerDetails[i].id + '<a>'
                        });
                        sublist.setSublistValue({
                            id: 'customers',
                            line: i,
                            value: main.checkifnull(customerDetails[i].name)
                        });

                    }
                },
                checkifnull: function(data) {
                    if (data == "" || data == null) {
                        return 0
                    } else {
                        return data
                    }
                },
                /*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: 288917,
                        isOnline: true
                    });
                    var fileid = fileObj.save();
                    log.debug("fileid", fileid);
                    return fileid;
                },
                getdata: function(type) {
                    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;

        });

Map Reduce Script

/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * HTL - 2 Customer Pricing 
 * **************************************************************************
 * 
 * Date: 03-07-2018
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/record', 'N/file', 'N/email', 'N/runtime', 'N/search', 'N/email'],

    function(record, file, email, runtime, search, email) {
        var main = {
            getInputData: function() {
                var processfolderid = runtime.getCurrentScript().getParameter("custscript_jj_fileid");
                var fileObj = file.load({
                    id: processfolderid
                });
                if (fileObj.size < 10485760) {
                    var customers = fileObj.getContents();
                }
                var fileContent = JSON.parse(customers);
                return fileContent;
            },
            reduce: function(context) {
                var copyObjid = runtime.getCurrentScript().getParameter("custscript_jj_customer_id");
                var copyfileObj = file.load({
                    id: copyObjid
                });
                if (copyfileObj.size < 10485760) {
                    var copyObj = copyfileObj.getContents();
                }
                var copyContent = JSON.parse(copyObj);
                var copyContent = JSON.parse(copyContent);
                var currentobj = context.values;
                var updateCustomer = JSON.parse(currentobj[0]);
                log.debug("updateCustomer", updateCustomer);
                var pricingDetails = main.updatePrcing(copyContent, updateCustomer)
            },
            updatePrcing: function(copyContent, updateCustomer) {
                var customerRecord = record.load({
                    type: "customer",
                    id: updateCustomer
                });
                var lines = main.removeAll(customerRecord);
                var lines = main.addGrouplines(copyContent.grouppricing, customerRecord);
                var lines = main.addItemlines(copyContent.itemArray, customerRecord);
                customerRecord.save();
            },
            addGrouplines: function(content, customerRecord) {
                for (var k = 0; k < content.length; k++) {
                    customerRecord.insertLine({
                        sublistId: 'grouppricing',
                        line: k,
                    });
                    customerRecord.setSublistValue({
                        sublistId: 'grouppricing',
                        fieldId: 'group',
                        value: content[k].group,
                        line: k
                    });
                    customerRecord.setSublistValue({
                        sublistId: 'grouppricing',
                        fieldId: 'level',
                        value: content[k].level,
                        line: k
                    });
                }
                return true;
            },
            addItemlines: function(content, customerRecord) {
                var i = 0;
                for (var k = 0; k < content.length; k++) {
                    var stat = main.checkForinactive(content[k].item);
                    log.debug("stat", stat);
                    log.debug("content[k].item", content[k].item);

                    if (stat == false) {
                        log.debug("keep", i);

                        customerRecord.insertLine({
                            sublistId: 'itempricing',
                            line: i,
                        });
                        customerRecord.setSublistValue({
                            sublistId: 'itempricing',
                            fieldId: 'item',
                            value: content[k].item,
                            line: i
                        });
                        customerRecord.setSublistValue({
                            sublistId: 'itempricing',
                            fieldId: 'level',
                            value: content[k].level,
                            line: i
                        });
                        i++;
                    }
                }
                return true;
            },
            checkForinactive: function(item) {
                var itemSearchObj = search.create({
                    type: "item",
                    filters: [
                        ["internalid", "anyof", item]
                    ],
                    columns: [
                        search.createColumn({ name: "isinactive", label: "Inactive" })
                    ]
                });
                var searchResultCount = itemSearchObj.runPaged().count;
                var inactive;
                itemSearchObj.run().each(function(result) {
                    inactive = result.getValue("isinactive")
                    return true;
                });
                return inactive;

            },
            removeAll: function(customerRecord) {
                var lines = customerRecord.getLineCount({ sublistId: "grouppricing" });
                for (var i = 0; i < lines; i++) {
                    customerRecord.removeLine({
                        sublistId: 'grouppricing',
                        line: 0,
                        ignoreRecalc: true
                    });
                }
                var lines = customerRecord.getLineCount({ sublistId: "itempricing" });
                for (var i = 0; i < lines; i++) {
                    customerRecord.removeLine({
                        sublistId: 'itempricing',
                        line: 0,
                        ignoreRecalc: true
                    });
                }
                return true;
            },
            summarize: function(summary) {
                /*              email.send({
                                  author: -5,
                                  recipients: emailaddress,
                                  subject: "CSV IMPORT Completed For  Record",
                                  body: "Operation : " + operation + "/n" + "Record :" + recordtype + "/n"
                              });*/
            }
        };
        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;
    });

User event script for button

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * HTL - 2 Customer Pricing 
 * **************************************************************************
 * 
 * Date: 03-07-2018
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/file', 'N/url', 'N/search', 'N/runtime', 'N/record', 'N/https', 'N/ui/serverWidget'],

    function(file, url, search, runtime, record, https, serverWidget) {
        var main = {
            beforeLoad: function(scriptContext) {
                if (scriptContext.type == "edit") {
                    scriptContext.form.addButton({
                        id: 'custpage_buttons',
                        label: 'Copy Customer Pricing',
                        functionName: 'copypricing'
                    });
                }
                scriptContext.form.clientScriptFileId = '327194';
            }
        };
        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;

    });
    /**
     * @NApiVersion 2.x
     * @NScriptType ClientScript
     * @NModuleScope SameAccount
     */
    /*******************************************************************************
     * HTL - 2 Customer Pricing 
     * **************************************************************************
     * 
     * Date: 03-07-2018
     * 
     * Author: Jobin & Jismi IT Services LLP
     * 
     *****************************************************************************
     **/
    define(['N/search', 'N/https', 'N/record', 'N/currentRecord', 'N/url'],

        function(search, https, record, currentRecord, url) {
            var flag = false;
            var main = {
                pageInit: function(scriptContext) {
                    var records = scriptContext.currentRecord;
                    var type = records.getValue({
                        fieldId: 'statsss'
                    });
                    console.log(type);
                    if (type == "success") {
                        window.close()
                    }
                },
                sublistChanged: function(scriptContext) {
                    console.log(scriptContext.sublistId);
                    if (scriptContext.sublistId == "grouppricing" || scriptContext.sublistId == "itempricing") {
                        flag = true;
                    }

                },
                copyPricing: function() {
                    var records = currentRecord.get();
                    var customerRecord = currentRecord.get();
                    var categoryId = customerRecord.getValue({
                        fieldId: 'custentity28'
                    });
                    var pricingDetails = main.getPricing(customerRecord);
                    var postUrl = url.resolveScript({
                        scriptId: "customscripthtl_2_sl_customer_category_l",
                        deploymentId: "customdeployhtl_2_sl_customer_category_l",
                        returnExternalUrl: false
                    });

                    var response = https.post({
                        url: postUrl,
                        body: JSON.stringify(pricingDetails)
                    });
                    var parameterObj = {
                        category: categoryId,
                        customer: customerRecord.id,
                        fileid: response.body
                    };
                    var dashboardUrl = url.resolveScript({
                        scriptId: "customscripthtl_2_sl_customer_category_l",
                        deploymentId: "customdeployhtl_2_sl_customer_category_l",
                        returnExternalUrl: false,
                        params: parameterObj
                    });
                    window.open(dashboardUrl, "Customer List", 'height=702,width=1000');
                },
                getPricing: function(records) {
                    var lines = records.getLineCount({ sublistId: "grouppricing" });
                    console.log(lines);
                    var pricingDetails = {};
                    var groupArray = [];
                    /*getting Sublist values */
                    for (var i = 0; i < lines; i++) {
                        var tempObj = {};
                        tempObj.group = records.getSublistValue({
                            sublistId: 'grouppricing',
                            fieldId: 'group',
                            line: i
                        });
                        tempObj.level = records.getSublistValue({
                            sublistId: 'grouppricing',
                            fieldId: 'level',
                            line: i
                        });
                        groupArray.push(tempObj);
                    }
                    pricingDetails.grouppricing = groupArray;
                    var itemArray = [];
                    /*getting Sublist values */
                    var lines = records.getLineCount({ sublistId: "itempricing" });

                    for (var i = 0; i < lines; i++) {
                        var tempObj = {};
                        tempObj.item = records.getSublistValue({
                            sublistId: 'itempricing',
                            fieldId: 'item',
                            line: i
                        });
                        tempObj.level = records.getSublistValue({
                            sublistId: 'itempricing',
                            fieldId: 'level',
                            line: i
                        });
                        itemArray.push(tempObj);
                    }
                    pricingDetails.itemArray = itemArray;

                    return pricingDetails;
                },
                saveRecord: function(scriptContext) {
                    var parentUrl = window.location.href;

                    if (parentUrl.indexOf("custjob") > -1) {

                        console.log(flag);
                        if (flag == true) {
                            main.copyPricing()
                        }
                        return true

                    } else {
                        var result = confirm("Are you sure you want to Copy Pricing ? ");
                        if (result) {
                            return true
                        }
                    }
                },
                closewindow: function() {
                    window.close();
                }

            };

            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);
                    }
                }
            };


            return main
        });

Leave a comment

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