Create duplicate Bin records-Fix inventory counting

Jira Code: TSI-7

Description

Customer do cycle counting daily at each location. They do this by using NetSuite’s inventory counts. Apparently, some of their locations have moved inventory items from bin to bin which causes the inventory counts created to show every bin the item has ever been in. These branches spend a large portion of their time going to old bins and not finding the product there because it’s been moved.

We will create a script,
-that can rename old bins
-create new bins with the old bin names,
-move inventory out of one bin and into the new bin,
-then inactivate the old bin.
Keeping in mind that we have Lot Numbered and Serial items that would need to be moved too.

Code:

/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * CLIENTNAME:Thermal Scientific, Inc. TSI-10 To add email on failure bin
 * transfer
 * ************************************************************************ Date :
 * 
 * Author: Jobin & Jismi IT Services LLP Script Description : Date created :
 * 
 * REVISION HISTORY
 * 
 * Revision 1.0 ${} atna rose : created 
 *          1.1 ${30/4/2019} aj : modified to add
 * 
 * 
 ******************************************************************************/

define(['N/search', 'N/record', 'N/email', 'N/runtime', 'N/error', 'N/render'],

    function(search, record, email, runtime, error, render) {

        /**
         * Marks the beginning of the Map/Reduce process and generates input
         * data.
         * 
         * @typedef {Object} ObjectRef
         * @property {number} id - Internal ID of the record instance
         * @property {string} type - Record type id
         * 
         * @return {Array|Object|Search|RecordRef} inputSummary
         * @since 2015.1
         */
        function getInputData() {

            var binObjArray = [];

            var binSearchObj = search.create({
                type: "bin",
                filters: [
                    ["inactive", "is", "F"],
                    "AND",
                    ["location", "anyof", "2"]
                ],
                columns: [
                    search.createColumn({
                        name: "binnumber",
                        sort: search.Sort.ASC,
                        label: "Bin Number"
                    }),
                    search.createColumn({
                        name: "location",
                        label: "Location"
                    }),
                    search.createColumn({
                        name: "memo",
                        label: "Memo"
                    }),
                    search.createColumn({
                        name: "inactive",
                        label: "Inactive"
                    })
                ]
            });
            var searchResultCount = binSearchObj.runPaged().count;


            return binSearchObj;
        }



        /**
         * Executes when the reduce entry point is triggered and applies to
         * each group.
         * 
         * @param {ReduceSummary}
         *            context - Data collection containing the groups to
         *            process through the reduce stage
         * @since 2015.1
         */
        function reduce(context) {



            searchObj = JSON.parse(context.values[0]);

            var loc = searchObj.values.location.value;
            var binTransferArray = [];
            // create new bin

            var toBin = createNewBin(context.key, searchObj);

            // create serach to create bin transfer data(search for
            // serialized and lot numbered)
            log.debug("context.key", context.key)
            log.debug("loc", loc)
            log.debug("binTransferArray", binTransferArray)
            log.debug("toBin", toBin)

            binTransferArray = serializedLotBinSearch(context.key, loc, binTransferArray, toBin);

            // create serach to create bin transfer data(search for
            // inventory)
            log.debug("binTransferArray1", binTransferArray)

            binTransferArray = inventorybinSearch(context.key, loc, binTransferArray, toBin);

            log.debug("binTransferArray2", binTransferArray)




            // create bin transfer from old bin to newly created bin
            if (binTransferArray.length != 0) {

                log.debug("binTransferArray.length!=0", binTransferArray.length)

                var itemArray = createBinTransfer(loc, binTransferArray, searchObj.values.binnumber);

                log.debug("itemArray", itemArray)

                if (itemArray.length != 0) {

                    log.debug("itemArray.length!=0", itemArray.length)
                    // Make the new bin created as prefered for the items
                    makeBinPrefered(loc, binTransferArray, itemArray, context.key);
                    try {
                        // inactivate the old bin

                        // change the name of the old bin
                        var id = record.submitFields({
                            type: record.Type.BIN,
                            id: context.key,
                            values: {
                                isinactive: true
                            },
                            options: {
                                enableSourcing: false,
                                ignoreMandatoryFields: true
                            }
                        });
                        log.error("id old rec", id);

                    } catch (err) {
                        handleErrorAndSendNotification(err, 'inactivatebin');
                        log.error("err", err);
                    }
                }
            } else {

                record.delete({
                    type: record.Type.BIN,
                    id: toBin
                });
                // change the name of the old bin
                var id = record.submitFields({
                    type: record.Type.BIN,
                    id: context.key,
                    values: {
                        binnumber: searchObj.values.binnumber

                    },
                    options: {
                        enableSourcing: true,
                        ignoreMandatoryFields: true
                    }
                });
            }
        }


        /**
         * Executes when the summarize entry point is triggered and applies
         * to the result set.
         * 
         * @param {Summary}
         *            summary - Holds statistics regarding the execution of
         *            a map/reduce script
         * @since 2015.1
         */
        function summarize(summary) {
            try {


                var author = -5;
                var recipients = ['anju@jobinandjismi.com'];
                var subject = 'A scheduled scrips for bin transfer' + runtime.getCurrentScript().id + ' has completed on ' + new Date();
                var body = 'A scheduled script for bin transfers has completed. This script was created to generate new bins and inactivate old bins in order to help reduce inventory cycle counts problems native to NetSuite.'
                body = 'Script details:/n Script Name: TSI-7 MR Create New Bin Transfer/n Deployment Name: TSI-7 MR Create New Bin Transfer/n Last Date Run: ' + new Date() + '/n Status: Completed/n Next Scheduled Run:' + new Date(new Date().getFullYear() + 1, new Date().getMonth(), new Date().getDate())

                email.send({
                    author: author,
                    recipients: recipients,
                    subject: subject,
                    body: body
                });



                // to get all the negative inventory bins
                var subjectOfErrMsg = "Bin transfer to do manually"
                var bodyOfErrMsg = "Error occured while bin transferring,attached are the bin numbers to do manually. Please manually do the bin transfer!"

                // to create a search for showing the error 

                var errorBin = gettingErrorBins();

                if (errorBin.length > 0) {


                    var toPdf = createPDF(errorBin);


                    email.send({
                        author: author,
                        recipients: recipients,
                        subject: subjectOfErrMsg,
                        body: bodyOfErrMsg,
                        attachments: [toPdf]
                    });


                }


            } catch (err) {
                log.error("err", err);
            }

        }

        function createNewBin(oldBinId, searchObj) {


            try {

                var binNumb = searchObj.values.binnumber;
                log.debug('binNumb', binNumb)

                log.debug('binNumb.length', binNumb.length)
                if (binNumb.length >= 16) {
                    binNumb = binNumb.slice(16 - binNumb.length);
                    log.debug('binNumb inn', binNumb)
                }

                binNumb = binNumb + (new Date().getMonth() + 1) + ((new Date().getFullYear() + '').slice(-2));
                log.debug('binNumb out', binNumb)
                // change the name of the old bin
                var id = record.submitFields({
                    type: record.Type.BIN,
                    id: oldBinId,
                    values: {
                        binnumber: binNumb

                    },
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    }
                });

                // create new bin
                // Start
                var newBinObj = record.create({
                    type: record.Type.BIN,
                    isDynamic: true
                });
                newBinObj.setValue({
                    fieldId: 'location',
                    value: searchObj.values.location.value
                });
                newBinObj.setValue({
                    fieldId: 'binnumber',
                    value: searchObj.values.binnumber
                });
                newBinObj.setValue({
                    fieldId: 'memo',
                    value: searchObj.values.memo
                });

                var newBin = newBinObj.save({
                    enableSourcing: false,
                    ignoreMandatoryFields: false
                });
                // End
                log.debug("newBin", newBin);
                return newBin;
            } catch (err) {
                handleErrorAndSendNotification(err, 'CreateNewBin');
                log.debug("err", err);
                log.error("err", err);
            }
        }


        function createBinTransfer(location, binTransferArray, binNumb) {
            try {

                var obj = record.create({
                    type: record.Type.BIN_TRANSFER,
                    isDynamic: true
                });

                obj.setValue({
                    fieldId: 'location',
                    value: location
                });

                obj.setText({
                    fieldId: 'memo',
                    text: 'new bin'
                });
                var itemArray = [];
                var i;
                for (i = 0; i < binTransferArray.length; i++) {


                    log.debug("i", i)

                    obj.selectNewLine({
                        sublistId: 'inventory'
                    });
                    obj.setCurrentSublistText({
                        sublistId: 'inventory',
                        fieldId: 'item',
                        text: binTransferArray[i].item
                    });
                    // get item array

                    if (itemArray.indexOf(binTransferArray[i].itemId) == -1) {

                        log.debug("inn -1 if", i)
                        itemArray.push(binTransferArray[i].itemId);
                    }

                    obj.setCurrentSublistValue({
                        sublistId: 'inventory',
                        fieldId: 'quantity',
                        value: binTransferArray[i].qty
                    });

                    obj.setCurrentSublistValue({
                        sublistId: 'inventory',
                        fieldId: 'itemunits',
                        value: binTransferArray[i].stockUnit
                    });

                    var invDetail = obj.getCurrentSublistSubrecord({
                        sublistId: 'inventory',
                        fieldId: 'inventorydetail',
                    });
                    invDetail.selectNewLine({
                        sublistId: 'inventoryassignment'
                    });
                    if (binTransferArray[i].invNumber != null) {
                        log.debug("inn ! null if", i);
                        invDetail.setCurrentSublistValue({
                            sublistId: 'inventoryassignment',
                            fieldId: 'issueinventorynumber',
                            value: binTransferArray[i].invNumber
                        });
                    }
                    invDetail.setCurrentSublistValue({
                        sublistId: 'inventoryassignment',
                        fieldId: 'binnumber',
                        value: binTransferArray[i].fromBin
                    });
                    invDetail.setCurrentSublistValue({
                        sublistId: 'inventoryassignment',
                        fieldId: 'tobinnumber',
                        value: binTransferArray[i].toBin
                    });
                    invDetail.setCurrentSublistValue({
                        sublistId: 'inventoryassignment',
                        fieldId: 'quantity',
                        value: binTransferArray[i].qty
                    });
                    invDetail.commitLine({
                        sublistId: 'inventoryassignment'
                    });

                    obj.commitLine({
                        sublistId: 'inventory'
                    });
                }

                var recordId = obj.save({
                    enableSourcing: false,
                    ignoreMandatoryFields: false
                });


                return itemArray;
            } catch (err) {

                log.debug("err@ create bin", err);
                // to check the error occured bcs of -ve inventory item
                var errMsg = err.message;

                // var isStartWith = (errMsg.indexOf("The following Bin numbers are not available:") > -1) ? errMsg.indexOf("The following Bin numbers are not available:") : errMsg.indexOf("Please configure the inventory detail for this line");
                var isStartWith = errMsg.indexOf("The following Bin numbers are not available:");


                if (isStartWith > -1) {

                    try {


                        // create an custom record entry
                        var customRecord = record.create({
                            type: 'customrecord_jj_tsi10_err_record',
                            isDynamic: false
                        });
                        // to set the values
                        customRecord.setText({
                            fieldId: 'custrecord_tsi10_bin_num',
                            text: binNumb,
                            ignoreFieldChange: true

                        });
                        // from bin

                        customRecord.setValue({
                            fieldId: 'custrecord131',
                            value: binTransferArray[0].fromBin,
                            ignoreFieldChange: true

                        });


                        var custID = customRecord.save();
                        log.debug("custID", custID)
                    } catch (e) {
                        log.debug("err @ creating custom record", e)
                        log.error("err @ creating custom record", e)
                    }
                }
                record.delete({
                    type: record.Type.BIN,
                    id: binTransferArray[0].toBin
                });
                log.debug('binTransferArray[0]', binTransferArray[0]);
                log.debug('binNumb', binNumb);

                // change the name of the old bin
                var id = record.submitFields({
                    type: record.Type.BIN,
                    id: binTransferArray[0].fromBin,
                    values: {
                        binnumber: binNumb,
                        isinactive: false

                    },
                    options: {
                        enableSourcing: true,
                        ignoreMandatoryFields: true
                    }
                });



                handleErrorAndSendNotification(err, 'createBinTransfer');
                return [];

            }
        }


        function serializedLotBinSearch(binId, location, binTransferArray, toBin) {
            try {
                var invcount = serializedInventoryCheck(binId, location);
                if (invcount == 0) {
                    // create search
                    var itemSearchObj = search.create({
                        type: "item",
                        filters: [
                            ["inventorynumberbinonhand.binnumber", "anyof", binId],
                            "AND",
                            ["inventorynumberbinonhand.location", "anyof", location],
                            "AND",
                            [
                                ["islotitem", "is", "T"], "OR", ["isserialitem", "is", "T"]
                            ],
                            "AND",
                            ["inventorynumberbinonhand.quantityavailable", "greaterthan", "0"],
                            "AND",
                            ["isinactive", "is", "F"]

                        ],
                        columns: [
                            // 0
                            search.createColumn({
                                name: "itemid",
                                sort: search.Sort.ASC,
                                label: "Name"
                            }),
                            // 1
                            search.createColumn({
                                name: "isserialitem",
                                label: "Is Serialized Item"
                            }),
                            // 2
                            search.createColumn({
                                name: "islotitem",
                                label: "Is Lot Numbered Item"
                            }),
                            // 3
                            search.createColumn({
                                name: "inventorynumber",
                                join: "inventoryNumberBinOnHand",
                                label: "Inventory Number"
                            }),
                            // 4
                            search.createColumn({
                                name: "quantityavailable",
                                join: "inventoryNumberBinOnHand",
                                label: "Available"
                            }),
                            // 5
                            search.createColumn({
                                name: "location",
                                join: "inventoryNumberBinOnHand",
                                label: "Location"
                            }),
                            // 6
                            search.createColumn({
                                name: "quantityonhand",
                                join: "inventoryNumberBinOnHand",
                                label: "On Hand"
                            }),
                            // 7
                            search.createColumn({
                                name: "binnumber",
                                join: "inventoryNumberBinOnHand",
                                label: "Bin Number"
                            }),
                            // 8
                            search.createColumn({
                                name: "stockunit",
                                label: "Stock Unit"
                            }),
                            // 9
                            search.createColumn({
                                name: "internalid",
                                label: "Internal ID"
                            })
                        ]
                    });
                    var searchResultCount = itemSearchObj.runPaged().count;


                    // run search and create the data object for bin transfer
                    itemSearchObj.run().each(function(result) {
                        var binTransferObj = {};

                        binTransferObj.fromBin = binId;
                        binTransferObj.toBin = toBin;

                        binTransferObj.item = result.getValue({
                            name: itemSearchObj.columns[0]
                        });
                        binTransferObj.itemId = result.getValue({
                            name: itemSearchObj.columns[9]
                        });
                        binTransferObj.qty = result.getValue({
                            name: itemSearchObj.columns[4]
                        });
                        binTransferObj.invNumber = result.getValue({
                            name: itemSearchObj.columns[3]
                        });
                        binTransferObj.stockUnit = result.getValue({
                            name: itemSearchObj.columns[8]
                        });


                        binTransferArray.push(binTransferObj);

                        return true;
                    });
                }
                return binTransferArray;

            } catch (err) {

                log.debug("err", err)
                log.error("err", err)

            }

        }

        function inventorybinSearch(binId, location, binTransferArray, toBin) {
            try {
                var invCount = invItemInventoryCheck(binId, location);
                if (invCount == 0) {
                    // search to get inventory details of inventory items
                    var itemSearchObj = search.create({
                        type: "item",
                        filters: [
                            ["binonhand.binnumber", "anyof", binId],
                            "AND",
                            ["binonhand.location", "anyof", location],
                            "AND",
                            [
                                ["islotitem", "is", "F"], "AND", ["isserialitem", "is", "F"]
                            ],
                            "AND",
                            ["binonhand.quantityavailable", "greaterthan", "0"],
                            "AND",
                            ["isinactive", "is", "F"]
                        ],
                        columns: [
                            // 0
                            search.createColumn({
                                name: "itemid",
                                sort: search.Sort.ASC,
                                label: "Name"
                            }),
                            // 1
                            search.createColumn({
                                name: "isserialitem",
                                label: "Is Serialized Item"
                            }),
                            // 2
                            search.createColumn({
                                name: "islotitem",
                                label: "Is Lot Numbered Item"
                            }),
                            // 3
                            search.createColumn({
                                name: "binnumber",
                                join: "binOnHand",
                                label: "Bin Number"
                            }),
                            // 4
                            search.createColumn({
                                name: "location",
                                join: "binOnHand",
                                label: "Location"
                            }),
                            // 5
                            search.createColumn({
                                name: "quantityavailable",
                                join: "binOnHand",
                                label: "Available"
                            }),
                            // 6
                            search.createColumn({
                                name: "stockunit",
                                label: "Stock Unit"
                            }),
                            // 7
                            search.createColumn({
                                name: "internalid",
                                label: "Internal ID"
                            })

                        ]
                    });
                    var searchResultCount = itemSearchObj.runPaged().count;

                    itemSearchObj.run().each(function(result) {
                        // create the bin transfer data
                        var binTransferObj = {};

                        binTransferObj.fromBin = binId;
                        binTransferObj.toBin = toBin;

                        binTransferObj.item = result.getValue({
                            name: itemSearchObj.columns[0]
                        });
                        binTransferObj.itemId = result.getValue({
                            name: itemSearchObj.columns[7]
                        });
                        binTransferObj.qty = result.getValue({
                            name: itemSearchObj.columns[5]
                        });
                        binTransferObj.invNumber = null;
                        binTransferObj.stockUnit = result.getValue({
                            name: itemSearchObj.columns[6]
                        });



                        binTransferArray.push(binTransferObj);

                        return true;
                    });
                }
                return binTransferArray;
            } catch (err) {
                log.debug("err", err);
                log.error("err", err);
            }
        }


        function makeBinPrefered(loc, binTransferArray, itemArray, oldBinId) {
            try {


                var itemSearchObj = search.create({
                    type: "item",
                    filters: [
                        ["internalid", "anyof", itemArray],
                        "AND",
                        ["binnumber.internalid", "anyof", oldBinId],
                        "AND",
                        ["inventorylocation", "anyof", loc]

                    ],
                    columns: [
                        // 0
                        search.createColumn({
                            name: "itemid",
                            sort: search.Sort.ASC,
                            label: "Name"
                        }),
                        // 1
                        search.createColumn({
                            name: "binnumber",
                            label: "Bin Number"
                        }),
                        // 2
                        search.createColumn({
                            name: "preferredbin",
                            label: "Preferred Bin"
                        }),
                        // 3
                        search.createColumn({
                            name: "inventorylocation",
                            label: "Inventory Location"
                        }),
                        // 4
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        // 5
                        search.createColumn({
                            name: "islotitem",
                            label: "Is Lot Numbered Item"
                        }),
                        // 6
                        search.createColumn({
                            name: "isserialitem",
                            label: "Is Serialized Item"
                        })
                    ]
                });
                var searchResultCount = itemSearchObj.runPaged().count;

                itemSearchObj.run().each(function(result) {
                    var invType;
                    // item is lot numbered
                    if (result.getValue({
                            name: itemSearchObj.columns[5]
                        }) == true) {
                        invType = "LOT_NUMBERED_INVENTORY_ITEM";
                    }
                    // item is serialized
                    else if (result.getValue({
                            name: itemSearchObj.columns[6]
                        }) == true) {
                        invType = "SERIALIZED_INVENTORY_ITEM";
                    } else {
                        invType = "INVENTORY_ITEM";
                    }


                    // set bin preferred
                    // start
                    var t = record.Type[invType];


                    var objRecord = record.load({
                        type: t,
                        id: result.getValue({
                            name: itemSearchObj.columns[4]
                        }),
                        isDynamic: true,
                    });


                    objRecord.selectNewLine({
                        sublistId: 'binnumber'
                    });
                    objRecord.setCurrentSublistValue({
                        sublistId: 'binnumber',
                        fieldId: 'location',
                        value: loc,
                        ignoreFieldChange: false
                    });
                    objRecord.setCurrentSublistValue({
                        sublistId: 'binnumber',
                        fieldId: 'binnumber',
                        value: binTransferArray[0].toBin,
                        ignoreFieldChange: false
                    });

                    objRecord.setCurrentSublistValue({
                        sublistId: 'binnumber',
                        fieldId: 'preferredbin',
                        value: result.getValue({
                            name: itemSearchObj.columns[2]
                        }),
                        ignoreFieldChange: false
                    });

                    objRecord.commitLine({
                        sublistId: 'binnumber'
                    });

                    var recordId = objRecord.save({
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    });


                    // End
                    return true;
                });

            } catch (err) {
                handleErrorAndSendNotification(err, 'makeBinPrefered');
                log.debug("err", err);
                log.error("err", err);
            }
        }

        function invItemInventoryCheck(binId, location) {
            // search to get inventory details of inventory items
            var itemSearchObj = search.create({
                type: "item",
                filters: [
                    ["binonhand.binnumber", "anyof", binId],
                    "AND",
                    ["binonhand.location", "anyof", location],
                    "AND",
                    [
                        ["islotitem", "is", "F"], "AND", ["isserialitem", "is", "F"]
                    ],
                    "AND",
                    ["binonhand.quantityavailable", "greaterthan", "0"],
                    "AND",
                    ["isinactive", "is", "F"],
                    "AND",
                    ["formulanumeric: CASE WHEN {binonhand.quantityavailable}={binonhand.quantityonhand} THEN 1 ELSE 0 END", "equalto", "0"]
                ],
                columns: [
                    // 0
                    search.createColumn({
                        name: "itemid",
                        sort: search.Sort.ASC,
                        label: "Name"
                    }),
                    // 1
                    search.createColumn({
                        name: "isserialitem",
                        label: "Is Serialized Item"
                    }),
                    // 2
                    search.createColumn({
                        name: "islotitem",
                        label: "Is Lot Numbered Item"
                    }),
                    // 3
                    search.createColumn({
                        name: "binnumber",
                        join: "binOnHand",
                        label: "Bin Number"
                    }),
                    // 4
                    search.createColumn({
                        name: "location",
                        join: "binOnHand",
                        label: "Location"
                    }),
                    // 5
                    search.createColumn({
                        name: "quantityavailable",
                        join: "binOnHand",
                        label: "Available"
                    }),
                    // 6
                    search.createColumn({
                        name: "stockunit",
                        label: "Stock Unit"
                    }),
                    // 7
                    search.createColumn({
                        name: "internalid",
                        label: "Internal ID"
                    })

                ]
            });
            var searchResultCount = itemSearchObj.runPaged().count;

            return searchResultCount;
        }

        function serializedInventoryCheck(binId, location) {
            // create search to check whether there is any items which ahve on hand> available
            var itemSearchObj = search.create({
                type: "item",
                filters: [
                    ["inventorynumberbinonhand.binnumber", "anyof", binId],
                    "AND",
                    ["inventorynumberbinonhand.location", "anyof", location],
                    "AND",
                    [
                        ["islotitem", "is", "T"], "OR", ["isserialitem", "is", "T"]
                    ],
                    "AND",
                    ["inventorynumberbinonhand.quantityavailable", "greaterthan", "0"],
                    "AND",
                    ["isinactive", "is", "F"],
                    "AND",
                    ["formulanumeric: CASE WHEN {inventorynumberbinonhand.quantityavailable}={inventorynumberbinonhand.quantityonhand} THEN 1 ELSE 0 END", "equalto", "0"]
                ],
                columns: [
                    // 0
                    search.createColumn({
                        name: "itemid",
                        sort: search.Sort.ASC,
                        label: "Name"
                    }),
                    // 1
                    search.createColumn({
                        name: "isserialitem",
                        label: "Is Serialized Item"
                    }),
                    // 2
                    search.createColumn({
                        name: "islotitem",
                        label: "Is Lot Numbered Item"
                    }),
                    // 3
                    search.createColumn({
                        name: "inventorynumber",
                        join: "inventoryNumberBinOnHand",
                        label: "Inventory Number"
                    }),
                    // 4
                    search.createColumn({
                        name: "quantityavailable",
                        join: "inventoryNumberBinOnHand",
                        label: "Available"
                    }),
                    // 5
                    search.createColumn({
                        name: "location",
                        join: "inventoryNumberBinOnHand",
                        label: "Location"
                    }),
                    // 6
                    search.createColumn({
                        name: "quantityonhand",
                        join: "inventoryNumberBinOnHand",
                        label: "On Hand"
                    }),
                    // 7
                    search.createColumn({
                        name: "binnumber",
                        join: "inventoryNumberBinOnHand",
                        label: "Bin Number"
                    }),
                    // 8
                    search.createColumn({
                        name: "stockunit",
                        label: "Stock Unit"
                    }),
                    // 9
                    search.createColumn({
                        name: "internalid",
                        label: "Internal ID"
                    })
                ]
            });
            var searchResultCount = itemSearchObj.runPaged().count;
            return searchResultCount;

        }

        function handleErrorAndSendNotification(e, stage) {

            var author = -5;
            var recipients = 'anju@jobinandjismi.com';
            var subject = 'Map/Reduce script ' + runtime.getCurrentScript().id + ' failed for stage: ' + stage;
            var body = 'An error occurred with the following information:\n' +
                'Error code: ' + e.name + '\n' +
                'Error msg: ' + e.message;

            email.send({
                author: author,
                recipients: recipients,
                subject: subject,
                body: body
            });
        }

        function binnameSearch(id) {
            try {
                var binSearchObj = search.create({
                    type: "bin",
                    filters: [
                        ["internalidnumber", "equalto", id]
                    ],
                    columns: [
                        search.createColumn({
                            name: "binnumber",
                            sort: search.Sort.ASC,
                            label: "Bin Number"
                        }),
                        search.createColumn({
                            name: "location",
                            label: "Location"
                        }),
                        search.createColumn({
                            name: "memo",
                            label: "Memo"
                        }),
                        search.createColumn({
                            name: "custrecord_tsi_7_old_bin_number",
                            label: "Old Bin number"
                        })
                    ]
                });
                var searchResultCount = binSearchObj.runPaged().count;

                // to get the bin name

                if (searchResultCount > 0) {

                }

            } catch (e) {
                log.debug("Err @ bin Num finding", e)
                log.error("Err @ bin Num finding", e)

            }
        }

        function gettingErrorBins() {
            try {
                var retnArray = [];
                var errRecSearch = search.create({
                    type: "customrecord_jj_tsi10_err_record",
                    filters: [],
                    columns: [
                        search.createColumn({
                            name: "id",
                            sort: search.Sort.ASC,
                            label: "ID"
                        }),

                        search.createColumn({
                            name: "custrecord_tsi10_bin_num",
                            label: "Bin Number"
                        }),
                        search.createColumn({
                            name: "custrecord131",
                            label: "From Bin"
                        }),

                    ]
                });
                var searchResultCount = errRecSearch.runPaged().count;
                var retObj = {};



                // to get search result more than 1000
                var start = 0;
                var end = 1000;

                var resultarray = [];
                var result;
                var singleresult;

                for (var i = 0; i < Math.ceil(searchResultCount / 1000); i++) {
                    result = errRecSearch.run().getRange({
                        start: start,
                        end: end
                    });
                    // logme('result', result);

                    for (var j = 0; j < result.length; j++) {
                        singleresult = result[j];

                        resultarray.push(singleresult);
                    }

                    start = end;
                    end = end + 1000;

                }


                // to get the result
                if (resultarray.length > 0) {
                    for (var i = 0; i < resultarray.length; i++) {
                        var single_result = resultarray[i];

                        var columns = errRecSearch.columns;
                        retObj.id = single_result.getValue({
                            name: "id",
                            sort: search.Sort.ASC,
                            label: "ID"
                        });

                        retObj.fromBin = single_result.getValue(
                            columns[1]
                        );

                        retObj.fromBinID = single_result.getValue(
                            columns[2]
                        );


                        retnArray.push(retObj)


                    }
                }




                return retnArray;

            } catch (e) {
                log.debug("Err @ gettingErrorBins", e)
                log.error("Err @ gettingErrorBins", e)
            }
        }

        function createPDF(binObj) {
            try {
                var toPdf = '' +
                    '<pdf>' +
                    '    <head>' +
                    '<style>' +
                    '                      table, tr, td,th{' +
                    '                        border:0.2;' +
                    '                       ' +
                    '                       cellpadding:10px;' +
                    '                       ' +
                    '                      }' +
                    '                      th{' +
                    '                        font-weight:bold;' +
                    '                      }' +
                    '                   </style>' +
                    '    </head>' +
                    '    <body>' +
                    '        <table>' +
                    '<thead><tr>' +
                    '        <th>' +
                    '            From bin' +
                    '            </th>' +
                    '            <th>' +
                    '             From bin internal ID' +
                    '            </th>' +

                    '</tr></thead>';
                for (var i = 0; i < binObj.length; i++) {
                    toPdf = toPdf + '<tr><td>' +
                        binObj[i].fromBin +
                        '</td><td>' +
                        binObj[i].fromBinID +
                        '</td>' +
                        '</tr>';


                }
                toPdf = toPdf + '        ' +
                    '        </table>' +
                    '    ' +
                    '    </body>' +
                    '</pdf>';




                var pdfFile = render.xmlToPdf({
                    xmlString: toPdf
                });

                return pdfFile;




            } catch (e) {
                log.debug("Err @ createPDF", e)
                log.error("Err @ createPDF", e)
            }
        }




        return {
            getInputData: getInputData,
            reduce: reduce,
            summarize: summarize
        };

    });

Blocker and its solutions:

  1. There can be errors while doing the bin transfer. Like the negative inventory issue.
    -Create the a custom record to store the errors that are occurring in the script while bin transfer.
    -Email to the Admin by summarizing these errors ,So that admin can manually work on it and correct them.
    -After correcting we have written another script. When you run this script it will take the bins which got error and run again.
    The only difference is in the getInputData() function ,the data is fetched from the custom record.

Leave a comment

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