CSV import system for the custom record.

Jira Code: MR-107

This is a custom import system for importing custom NetSuite record. The main advantage over the existing NetSuite import system is that it can process an unlimited number of lines at a time. NetSuite import system has a limitation of 10000 lines.

This import system works as a tab delimited. The normal import system works as a comma. Since the mapping is done already, the user need not want to bother about column order. The corresponding values in the columns will be mapped to the body fields.

A map-reduce script is used to process the records. Suitlet is to hold the HTML and does the mapping of the fields also scheduling happens from the suitelet.

<!DOCTYPE html>
<html>

<head>
    <title>CSV IMPORT SYSTEM</title>
    <style>
    .invoice-box {
        max-width: 800px;
        margin: auto;
        padding: 30px;
        border: 1px solid #eee;
        box-shadow: 0 0 10px rgba(0, 0, 0, .15);
        font-size: 14px;
        line-height: 20px;
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
        color: black;
    }

    #paypal-button-container {
        text-align: center;
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    }

    .button {
        background-color: #9C9797;
        border: 1px solid #9C9797;
        color: white;
        padding: 15px 32px;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
        text-align: center;
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
        transition: .5s ease
    }

    .button:hover {
        border: 1px solid #9C9797;
        background-color: #9C9797;
        color: black;
    }

    .invoice-box table {
        width: 100%;
        line-height: inherit;
        text-align: left;
    }

    .invoice-box table td {
        padding: 5px;
        vertical-align: top;
    }

    .invoice-box table tr td:nth-child(2) {
        text-align: right;
    }

    .invoice-box table tr.top table td {
        padding-bottom: 20px;
    }

    .invoice-box table tr.top table td.title {
        font-size: 45px;
        line-height: 45px;
        color: #333;
    }

    .invoice-box table tr.information table td {
        padding-bottom: 40px;
    }

    .invoice-box table tr.heading td {
        background: #BFB9B9;
        border-bottom: 1px solid #BFB9B9;
        font-weight: bold;
    }

    .invoice-box table tr.details td {
        padding-bottom: 20px;
    }

    .invoice-box table tr.item td {
        border-bottom: 1px solid #ffffff;
    }

    .invoice-box table tr.item.last td {
        border-bottom: none;
    }

    .invoice-box table tr.total td:nth-child(2) {
        border-top: 2px solid #ffffff;
        font-weight: bold;
    }

    @media only screen and (max-width: 600px) {
        .invoice-box table tr.top table td {
            width: 100%;
            display: block;
            text-align: center;
        }

        .invoice-box table tr.information table td {
            width: 100%;
            display: block;
            text-align: center;
        }
    }
    /** RTL **/

    .rtl {
        direction: rtl;
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    }

    .rtl table {
        text-align: right;
    }

    .rtl table tr td:nth-child(2) {
        text-align: left;
        background: #CECECE
    }

    #Serial {
        border-radius: 8px;
        width: 300px;
        height: 20px;
    }

    #ss {
        width: 87%;
    }

    #tablecontent {
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
        border-collapse: collapse;
        width: 35%;
    }

    #tablecontent td,
    #tablecontent th {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: center;
    }

    #tablecontent tr:nth-child(even) {
        background-color: #f2f2f2;
        text-align: center;
    }

    #tablecontent tr:hover {
        background-color: #ddd;
    }

    #tablecontent th {
        padding-top: 12px;
        padding-bottom: 12px;
        text-align: center;
        background-color: #3b5998;
        color: white;
    }
    </style>
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://unpkg.com/sweetalert2@7.19.1/dist/sweetalert2.all.js"></script>
    <div class="invoice-box">
        <p></p>
        <p></p>
        <p></p>
        <table cellpadding="0" cellspacing="0" id="podetails">
            <tr class="top">
                <td colspan="2">
                    <table>
                        <tr>
                            <td class="title">
                                <img src="http://static.wixstatic.com/media/d211bc_629e5ed9a74f46bc9723b77dbaed35c4.png" style="width:100%; max-width:300px;">
                            </td>
                            <td>
                                <invoicetranid>
                                    <br> Date:
                                    <invoicecreateddate>
                                        <br>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr class="information">
                <td colspan="2">
                    <table>
                        <tr>
                            <td>
                                <p>
                                    Choose Record Types:
                                    <select name="recordtypes" id="recordtypes" data-mapid="" onchange="recordchange()">
                                        <option data-mapid="20771" value="customrecord_jj_branded_handset">Branded Handset</option>
                                        <option data-mapid="20769" value="customrecord_jj_route_run">Route Run</option>
                                        <option data-mapid="20768" value="customrecord_jj_qpay_marketplace_details">Qpay MarketPlace Details</option>
                                        <option data-mapid="20767" value="customrecord_jj_qpaydetail_transaction">Qpay Detailed transaction</option>
                                        <option data-mapid="20770" value="customrecord_jj_tracfone_activations">Tracfone Activations</option>
                                        <option data-mapid="20766" value="customrecord223">Activation Verizon Vidapay</option>
                                        <option data-mapid="75541" value="customrecord_mw_tracfone_residual_month">Tracfone Residual Monthly</option>
                                    </select>
                                </p>
                            </td>
                            <td>
                                <p>
                                    Choose Actions:
                                    <select name="recordactions" id="recordactions">
                                        <option value="create">Create</option>
                                        <option value="delete">Delete</option>
                                    </select>
                                </p>
                                <p id="deleteactionsp">
                                    Choose Range:
                                    <select name="deleteactions" id="deleteactions">
                                        <option value="today">Created Today</option>
                                        <option value="yesterday">Created Yesterday</option>
                                        <option value="fivedaysago">Created Five Days Ago</option>
                                        <option value="thisweek">Created In This Week</option>
                                        <option value="thismonth">Created This Month</option>
                                        <option value="all">Delete All</option>
                                    </select>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <p>
                                    <input type="file" name="filename" id="filename">
                                </p>
                            </td>
                            <td>
                                <p>
                                    E-mail:
                                    <input type="email" value="al@megatelwireless.com" name="emailaddress"> </p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr class="heading">
                <td>
                    Column Headers
                </td>
                <td>
                    Netsuite Field Names
                </td>
            </tr>
            <replacewithitemdetails>
                <!--<tr class="total">
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr> -->
        </table>
        <p></p>
        <p></p>
        <div id="paypal-button-container">
            <button type="button" class="button" onclick="startproccessing()">Process</button>
            <button type="button" class="button" onclick="startReset()">Reset</button>
        </div>
    </div>
    <script>
    var chunks;
    var title;
    var mapobj;
    var foldername;
    var csvColumns;

    function startReset() {
        location.reload()

    }

    function recordchange() {
        var recordtype = $("#recordtypes").val();
        // var fieldlists = postdata(recordtype, "getfield");
    }

    function csvToArray(text) {
        let p = '',
            row = [''],
            ret = [row],
            i = 0,
            r = 0,
            s = !0,
            l;
        for (l of text) {
            if ('"' === l) {
                if (s && l === p) row[i] += l;
                s = !s;
            } else if ('\t' === l && s) l = row[++i] = '';
            else if ('\n' === l && s) {
                if ('\r' === p) row[i] = row[i].slice(0, -1);
                row = ret[++r] = [l = ''];
                i = 0;
            } else row[i] += l;
            p = l;
        }
        var csvObj = {};
        csvObj.contents = ret.slice(1);
        csvObj.title = ret[0];
        return csvObj;
    };
    var validations = {
        email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
    };
    $(document).ready(function() {
        $("#deleteactionsp").hide();

        $("#recordactions").change(function() {
            if ($("#recordactions").val() == "delete") {
                $("#deleteactionsp").show();
            } else {
                $("#deleteactionsp").hide();
            }
        });
        $("input[type=email]").change(function() {
            validation = new RegExp(validations['email'][0]);

            if (!validation.test(this.value)) {
                swal("Please Enter a Valid Email");
                $("input[type=email]").val("");
            } else {}
        });
    })
    /*Field change event of CSV upload*/
    $("#filename").change(function(e) {
        var ext = $("input#filename").val().split(".").pop().toLowerCase();
        if ($.inArray(ext, ["txt"]) == -1) {
            swal('Please Upload a Text File !!!');
            $("input#filename").val("");
            return false;
        }
        if (e.target.files != undefined) {
            document.getElementById("filename").disabled = true;
            document.getElementById("recordactions").disabled = true;
            var reader = new FileReader();
            reader.onload = function(e) {
                var csvval = e.target.result.split("\n");
                var csvObj = csvToArray(e.target.result);
                // console.log(csvObj.contents);
                setfieldmap(csvObj.title, "title", true);
                title = csvObj.title;
                chunks = splicetochunks(csvObj.contents, 5000);
            };
            reader.readAsText(e.target.files.item(0));
        }
        return false;
    });

    function startproccessing() {
        if ($("input[type=email]").val() == null || $("input[type=email]").val() == "") {
            swal("Email Field Is empty !!! ");
            return false
        }
        var recorddetails = {
            recordtype: $("#recordtypes").val(),
            operation: $("#recordactions").val(),
            recordname: $("#recordtypes option:selected").text()
        }
        if (recorddetails.operation == "delete") {
            if (ConfirmDelete() == false) {

                return false
            }
            foldername = Date.now();
            var contextwork = {};
            contextwork.mapobj = mapobj;
            contextwork.contextdetails = recorddetails;
            contextwork.deletedetail = $("#deleteactions").val();
            contextwork.emailaddress = $("input[type=email]").val();
            postdata(JSON.stringify("chunks[i]"), "endgame", JSON.stringify(contextwork), foldername);
        } else {
            if (chunks == undefined) {
                swal("Please Upload a csv File !!! ");
                return false
            }
            if (jQuery.isEmptyObject(mapobj) == true) {
                swal("Mapping is not Done!!!");
                return false
            }

            var len = chunks.length;

            var contextwork = {};

            contextwork.mapobj = mapobj;
            contextwork.contextdetails = recorddetails;
            contextwork.emailaddress = $("input[type=email]").val();
            contextwork.csvColumns = csvColumns;
            console.log(contextwork)
            foldername = Date.now();
            for (var i = 0; i < len; i++) {
                if (i == len - 1) {
                    postdata(JSON.stringify(chunks[i]), "endgame", JSON.stringify(contextwork), foldername);
                } else {
                    postdata(JSON.stringify(chunks[i]), "processing", JSON.stringify(contextwork), foldername);
                }
            }
        }
        swal("Proccess Started !", "Email Notification will be Sent to " +
            $("input[type=email]").val(), "success");


        swal({
            title: 'Proccess Started !',
            text: 'Email Notification will be Sent to ' + $("input[type=email]").val(),
            type: 'success',
            showCancelButton: true,
            confirmButtonText: 'OK',
            confirmButtonClass: 'btn-success'
        }).then(function() {
            location.reload()
            //success method
        }, function(dismiss) {

        });


    }

    function ConfirmDelete() {
        var x = confirm("Do you want to delete the records of " + $("#recordtypes option:selected").text());
        if (x)
            return true;
        else
            return false;
    }



    function setfieldmap(data, type, flag) {
        //    try{
        //         var row = document.getElementById("maprow");
        //   row.parentNode.removeChild(row);
        //  }
        // catch(e)
        // {
        //  console.debug(e.message)
        // }
        document.getElementById("recordtypes").disabled = true;
        if (flag == true) {
            var appenddata = postdata(data.toString(), "getfield", jQuery("#recordtypes").find(':selected').attr('data-mapid'));
        } else {
            console.log(data);
            data = JSON.parse(data);
            csvColumns = data.csvColumns;
            mapobj = data.mapobj;
            data = data.tempobj;
            console.log("csvColumns", csvColumns)
            var flag = true;
            for (var index in data) {
                var attr = data[index];
                if (flag) {
                    $('#podetails').append('<tr id="maprow" style="background:#E4DFDF;"><td>' + index + '</td><td> ' + data[index] + ' </td></tr>');
                    flag = !flag;
                } else {
                    $('#podetails').append('<tr id="maprow" style="background:white;"><td>' + index + '</td><td> ' + data[index] + ' </td></tr>');
                    flag = !flag;
                }

            }
            /*        for (var i = 0; i < data.length; i++) {
                        $('#podetails').append('<tr><td>' + data[i] + '</td><td>   </td></tr>');
                    }*/
        }
    }
    /*function to cut the elemerns to chunks */
    function splicetochunks(inputArray, chunk) {
        var i, j, temparray = [];
        for (i = 0, j = inputArray.length; i < j; i += chunk) {
            temparray.push(
                inputArray.slice(i, i + chunk));
        }
        return temparray;
    }
    /*To post the data to netsuite suitelet / restlet */
    function postdata(data, type, mapfile, foldername) {
        var response;
        console.log('postdata  ' + type + "  " + mapfile);
        $.post("<scripturl>", {
                datas: data,
                type: type,
                mapfile: mapfile,
                foldername: foldername
            },
            function(data, status) {
                if (type == "getfield") {
                    setfieldmap(data, "setfieldmap", false);
                }
            });
        return response;
    }
    // for getting parameter by name 
    function getParameterByName(name, url) {
        if (!url)
            url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex
            .exec(url);
        if (!results)
            return null;
        if (!results[2])
            return ' ';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    </script>
</body>

</html>

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**

* Script Description

* This suitelet is to load HTML and recive post request
* HTML consists A HTML INPUTS 

*/

/*******************************************************************************
 * 
 * Support Files
 * 
 * *****************************************************************************
 * 
 * 
 * 
 * $Author: Jobin & Jismi IT Services LLP $
 * 
 * DESCRIPTION
 * CSV Import System 
 * 
 * 
 * 
 * 
 ******************************************************************************/
define(['N/file', 'N/url', 'N/search', 'N/runtime', 'N/record', 'N/https', 'N/task', 'N/email'],
    function csvsystem(file, url, search, runtime, record, https, task, email) {
        var main = {
            dopost: function(datas, type, mapfile, foldername) {
                if (type == "getfield") {
                    var csvColumns = datas.split(",");
                    var fileObj = file.load({
                        id: mapfile
                    });
                    if (fileObj.size < 10485760) {
                        var mapping = fileObj.getContents();
                    }
                    var fieldmapobj = JSON.parse(mapping);
                    fieldmapobj = fieldmapobj.fieldmap;
                    var returnobj = {}
                    var tempobj = {}
                    var mapobj = {}
                    for (var i = 0; i < csvColumns.length; i++) {
                        var currentValue = main.checkifnull(fieldmapobj[csvColumns[i]]);
                        if (currentValue == "-") {
                            tempobj[csvColumns[i]] = "-";
                        } else {
                            tempobj[csvColumns[i]] = main.checkifnull(currentValue.name);
                            mapobj[main.checkifnull(fieldmapobj[csvColumns[i]].id)] = i;

                        }
                    }
                    return {
                        tempobj: tempobj,
                        mapobj: mapobj,
                        csvColumns: csvColumns
                    }
                } else {
                    var datas = JSON.parse(datas);
                    log.debug("datas", datas.length);
                    var filename = Date.now();
                    var folderid;
                    var init = main.checkforfolder(foldername);
                    if (init == true) {
                        folderid = main.createfolder(foldername, mapfile);
                    } else {
                        folderid = init;
                    }

                    /*To remove Empty Lines  */
                    var tempArray = [];
                    for (var i = 0; i < datas.length; i++) {
                        for (var k = 0; k < datas[i].length; k++) {
                            if (datas[i][k] == null || datas[i][k] == "") {} else {
                                tempArray.push(datas[i]);
                                break;
                            }
                        }
                    }

                    var processfileid = main.createfile(tempArray, filename, folderid);
                    log.debug("mapid", mapfile);
                    log.debug("type", type)

                    if (type == "endgame") {
                        main.scheduleanother(folderid, mapfile, "mapfileid");
                    }
                    return false;
                }
            },
            createfolder: function(argument, mapfile) {
                var folderRec = record.create({
                    type: record.Type.FOLDER,
                    isDynamic: true
                });
                folderRec.setValue({
                    fieldId: 'parent',
                    value: 10188
                });
                folderRec.setValue({
                    fieldId: 'name',
                    value: argument
                });
                var folderId = folderRec.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                });
                var mapfileid = main.createfile(mapfile, "scriptcontext", folderId);

                return folderId;
            },
            checkforfolder: function(name) {
                var folderSearchObj = search.create({
                    type: "folder",
                    filters: [
                        ["name", "is", name]
                    ],
                    columns: [
                        search.createColumn({
                            name: "name",
                            sort: search.Sort.ASC,
                            label: "Name"
                        }),
                        search.createColumn({ name: "foldersize", label: "Size (KB)" }),
                        search.createColumn({ name: "lastmodifieddate", label: "Last Modified" }),
                        search.createColumn({ name: "internalid", label: "internalid" }),
                        search.createColumn({ name: "numfiles", label: "# of Files" })
                    ]
                });
                var searchResultCount = folderSearchObj.runPaged().count;
                if (searchResultCount < 1) {
                    return true
                } else {
                    var internalid;
                    folderSearchObj.run().each(function(result) {
                        internalid = result.getValue("internalid");
                        return true;
                    });
                    return internalid;
                }

            },
            checkifnull: function(data) {
                if (data == "" || data == null || data == undefined) {
                    return "-";
                }
                return data;
            },
            /*Setup map reduce script*/
            scheduleanother: function(fileid, mapid, mapfile) {
                try {
                    var scheduleScrptTask = task.create({
                        taskType: task.TaskType.MAP_REDUCE,
                        scriptId: "customscript_mr_mapreducerecord",
                        deploymentId: 'customdeploy_mr_mapreducerecord',
                        params: {
                            custscript_json_fileid: fileid,
                            custscript_type: mapfile
                        }
                    });
                    scheduleScrptTask.submit();
                    var mapFileid = JSON.parse(mapid)
                    var emailaddr = mapFileid.emailaddress;
                    var recordtype = mapFileid.contextdetails.recordtype;
                    var recordname = mapFileid.contextdetails.recordname;
                    var mailBody = main.createResponse(recordtype, recordname);
                    email.send({
                        author: -5,
                        recipients: emailaddr,
                        cc: ["edwin@jobinandjismi.com", "feena@jobinandjismi.com"],
                        subject: "Import Process Succesfully Started for " + recordname,
                        body: mailBody
                    });
                } catch (e) {
                    log.debug("e in scheduleanother", e);
                    var params = {
                        custscript_json_fileid: fileid,
                        custscript_type: mapfile
                    }
                    main.createfile(params, Date.now(), 26540);

                }
            },
            /*For Saving the JSON File In File Cabinet */
            createfile: function(netsuitedata, name, folderid) {
                var folderinternal;
                if (folderid > 0) {
                    folderinternal = folderid;
                } else {
                    folderinternal = 10188
                }
                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: folderinternal,
                    isOnline: true
                });
                var fileid = fileObj.save();
                return fileid;
            },
            onRequest: function(context) {
                if (context.request.method === 'POST') {
                    var datas = context.request.parameters.datas;
                    var type = context.request.parameters.type;
                    var mapfile = context.request.parameters.mapfile;
                    var foldername = context.request.parameters.foldername;

                    var data = main.dopost(datas, type, mapfile, foldername);
                    context.response.write(JSON.stringify(data));
                } else {
                    var invoice = context.request.parameters.invoice;
                    var fileid = main.getfileid();
                    var newhtml = main.gethtml(fileid, invoice);
                    context.response.write({
                        output: newhtml
                    });
                }
            },
            getfileid: function() {
                var bundleurl = "MR- 107 SL CSV Import System/";
                try {
                    bundleurl = "MR- 107 SL CSV Import System/";
                    var fileObj = file.load({
                        id: bundleurl + 'CSV Import HTML.html' // '13147'
                    });
                } catch (e) {
                    bundleurl = "SuiteBundles/Bundle 189004/ESW-47 Paypal Integertion/";
                }
                return 20765;
            },
            gethtml: function(fileid, invoice) {
                var scripturl = url.resolveScript({
                    scriptId: 'customscript_mr_107_sl_csv_import_system',
                    deploymentId: 'customdeploy_mr_107_sl_csv_import_system',
                    returnExternalUrl: true
                });
                var fileObj = file.load({
                    id: fileid
                });
                if (fileObj.size < 10485760) {
                    var html = fileObj.getContents();
                }
                var newhtml = html.replace("<scripturl>", scripturl);
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1;
                var yyyy = today.getFullYear();
                if (yyyy < 2000)
                    yyyy = yyyy + 100;
                if (dd < 10) {
                    dd = '0' + dd;
                }
                if (mm < 10) {
                    mm = '0' + mm;
                }
                var datestr = dd + '/' + mm + '/' + yyyy;
                var newhtml1 = newhtml.replace("<invoicecreateddate>", datestr);
                return newhtml1;
            },
            createResponse: function(recordtype, recordname) {
                var htmlFile = file.load({
                    id: 39539
                });
                var htmlFilecontent = htmlFile.getContents();
                var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Process Successfully Started");
                var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record :  " + recordname);
                return htmlFilecontent2;
            }
        }
        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 MapReduceScript
 * @NModuleScope SameAccount
 */
/**

* Script Description

* This Map Reduce to create and delete the records 
* 
*/

/*******************************************************************************
 * 
 * Support Files
 * 
 * *****************************************************************************
 * 
 * 
 * 
 * $Author: Jobin & Jismi IT Services LLP $
 * 
 * DESCRIPTION
 * CSV Import System 
 * 
 * 
 * 
 * 
 ******************************************************************************/
define(['N/record', 'N/file', 'N/email', 'N/runtime', 'N/search', 'N/email', 'N/encode', 'N/task', 'N/format'],
    function(record, file, email, runtime, search, email, encode, task, format) {
        var main = {
            /*Get inputData for Processing */
            getInputData: function(context) {
                //log.debug('context',context)
                var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid");
                var mapinternal = main.findprocessfiles(processfolderid, false);
                var contextfile = file.load({
                    id: mapinternal
                });
                var contextContent = contextfile.getContents();
                var contextContent = JSON.parse(contextContent);
                var contextobj = JSON.parse(contextContent)
                var operation = contextobj.contextdetails.operation;
                var recordtype = contextobj.contextdetails.recordtype;
                if (operation == "create") {
                    //                      log.debug('enter create')
                    var processFilles = main.findprocessfiles(processfolderid, true);
                    var fileContent = main.setupProccessfiles(processFilles);
                } else if (operation == "delete") {
                    //log.debug("contextobj.contextdetails.deletedetail", contextobj.deletedetail)
                    var fileContent = main.searchRecord(contextobj.contextdetails.recordtype, contextobj.deletedetail);
                }
                try {
                    log.debug("fileContent", fileContent.length);
                } catch (e) {
                    log.debug('error', e)
                }
                return fileContent;
            },
            /*Concatnate the Arrays from Chunks Folder  */
            setupProccessfiles: function(filefolder) {
                var len = filefolder.length;
                var array = [];
                for (var i = 0; i < len; i++) {
                    if (filefolder[i].name != "scriptcontext.txt") {
                        var processFile = file.load({
                            id: filefolder[i].internalid
                        });
                        var fileContent = processFile.getContents();
                        var temparray = JSON.parse(fileContent);
                        array.push(temparray);
                    }
                }
                var fullarray = [].concat.apply([], array);
                return fullarray;
            },
            /*If Process is Delete then get the internalids */
            searchRecord: function(recordtype, date) {
                var filterarry = []
                if (date == "all") {

                } else {
                    filterarry.push(["created", "within", date])
                }
                //                    log.debug("date", date);
                var SearchObj = search.create({
                    type: recordtype,
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        })
                    ],
                    filters: filterarry

                });
                var searchPageRanges = SearchObj.runPaged({
                    pageSize: 1000
                });
                var internalids = [];
                for (var i = 0; i < searchPageRanges.pageRanges.length; i++) {
                    searchPageRanges.fetch({
                        index: i
                    }).data.forEach(function(result) {
                        internalids.push(result.getValue("internalid"));
                        return true;
                    });
                }
                //                    log.debug("deletearray length", internalids.length);
                return internalids;
            },
            /*Find JSON chunks From the Folder For Processing */
            findprocessfiles: function(folderid, flag) {
                var fileSearchObj = search.create({
                    type: "file",
                    filters: [
                        ["folder", "anyof", folderid]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "name",
                            sort: search.Sort.ASC,
                            label: "Name"
                        })
                    ]
                });
                var searchResultCount = fileSearchObj.runPaged().count;
                if (flag == true) {
                    var processarray = [];
                    fileSearchObj.run().each(function(result) {
                        var tempobj = {};
                        tempobj.internalid = result.getValue("internalid");
                        tempobj.name = result.getValue("name");
                        processarray.push(tempobj);
                        return true;
                    });
                    return processarray;
                } else {
                    var mapinternal;
                    fileSearchObj.run().each(function(result) {
                        if (result.getValue("name") == "scriptcontext.txt") {
                            mapinternal = result.getValue("internalid");
                        }
                        return true;
                    });
                    return mapinternal;
                }
            },
            /*Reduce Function of map Reduce */
            reduce: function(context) {
                var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid");
                var mapinternal = main.findprocessfiles(processfolderid, false);
                var contextfile = file.load({
                    id: mapinternal
                });
                var contextContent = contextfile.getContents();
                var contextContent = JSON.parse(contextContent);
                var contextobj = JSON.parse(contextContent)
                var operation = contextobj.contextdetails.operation;
                var recordtype = contextobj.contextdetails.recordtype;
                var mapobj = contextobj.mapobj;
                var currentobj = context.values;
                var convertedfile = JSON.parse(currentobj[0]);
                if (operation == "create") {
                    if (recordtype == "customrecord_jj_tracfone_activations") {
                        var tracfone_record = true;
                        var simno_tracfone = convertedfile[mapobj['custrecordjj_tra_sim']]

                        var customrecord_jj_tracfone_activationsSearchObj = search.create({
                            type: "customrecord_jj_tracfone_activations",
                            filters: [
                                ["custrecordjj_tra_sim", "is", simno_tracfone]
                            ],
                            columns: [
                                search.createColumn({ name: "internalid", label: "Internal ID" })
                            ]
                        });

                        var searchResult = customrecord_jj_tracfone_activationsSearchObj.run().getRange({
                            start: 0,
                            end: 1
                        });
                    }
                    for (var j = 0; j < searchResult.length; j++) {
                        var intrId = searchResult[j].getValue({
                            name: "internalid"
                        });

                    }
                    if (intrId && tracfone_record) {
                        log.debug('simno_tracfone : ' + simno_tracfone, 'intrId: ' + intrId);
                        main.updateRecord(recordtype, mapobj, convertedfile, processfolderid, intrId);
                    } else {
                        main.createrecord(recordtype, mapobj, convertedfile, processfolderid);
                    }
                } else if (operation == "delete") {
                    //     log.debug("convertedfile", convertedfile);
                    main.deleteRecord(recordtype, convertedfile);
                }
            },
            /*To Find Error Files */
            finderrorfiles: function(errorfolderid) {
                var fileSearchObj = search.create({
                    type: "folder",
                    filters: [
                        ["name", "is", errorfolderid]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "name",
                            sort: search.Sort.ASC,
                            label: "Name"
                        })
                    ]
                });
                var resultSet = fileSearchObj.run();
                var firstResult = resultSet.getRange({
                    start: 0,
                    end: 1
                })[0];
                //                    log.debug('firstResult',firstResult)
                var value = firstResult.getValue(resultSet.columns[0]);
                var fileError = search.create({
                    type: "file",
                    filters: [
                        ["folder", "anyof", value]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "name",
                            sort: search.Sort.ASC,
                            label: "Name"
                        })
                    ]
                })
                var processarray = [];
                fileError.run().each(function(result) {
                    var tempobj = {};
                    tempobj.internalid = result.getValue("internalid");
                    tempobj.name = result.getValue("name");
                    processarray.push(tempobj);
                    return true;
                });
                var len = processarray.length;
                var array = [];
                for (var i = 0; i < len; i++) {
                    if (processarray[i].name != "scriptcontext.txt") {
                        var processFile = file.load({
                            id: processarray[i].internalid
                        });
                        var fileContent = processFile.getContents();
                        array.push(fileContent);
                    }
                }
                //     var fullarray = [].concat.apply([], array);
                return array;

            },
            /*Error Folder For Logging and send Email*/
            createfolder: function(data) {
                var folderRec = record.create({
                    type: record.Type.FOLDER,
                    isDynamic: true
                });
                folderRec.setValue({
                    fieldId: 'parent',
                    value: 10189
                });
                folderRec.setValue({
                    fieldId: 'name',
                    value: data
                });
                var folderId = folderRec.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                });

                return folderId;
            },
            /*To check whether there is any folder existing for error log*/
            checkforfolder: function(name) {
                var folderSearchObj = search.create({
                    type: "folder",
                    filters: [
                        ["name", "is", name]
                    ],
                    columns: [

                        search.createColumn({
                            name: "internalid",
                            label: "internalid"
                        })
                    ]
                });
                var searchResultCount = folderSearchObj.runPaged().count;
                if (searchResultCount < 1) {
                    return true
                } else {
                    var internalid;
                    folderSearchObj.run().each(function(result) {
                        internalid = result.getValue("internalid");
                        return true;
                    });
                    return internalid;
                }
            },
            /* Create the error file in the error error log */
            createfile: function(name, folderid, convertedfile) {
                var folderinternal;
                if (folderid > 0) {
                    folderinternal = folderid;
                } else {
                    folderinternal = 10189
                }
                var fileObj = file.create({
                    name: name + '.txt',
                    fileType: file.Type.PLAINTEXT,
                    contents: convertedfile,
                    folder: folderinternal,
                    isOnline: true
                });

                var fileid = fileObj.save();
                return fileid;
            },
            /*Delete Process Actions */
            deleteRecord: function(type, internalid) {
                record.delete({
                    type: type,
                    id: internalid
                });
            },
            /*Update record actions Process */
            updateRecord: function(recordtype, mapobj, convertedfile, processfolderid, intrId) {
                if (recordtype == "customrecord_jj_tracfone_activations") {
                    var value_xl = convertedfile[mapobj['custrecord_jj_plan']]
                    //                       log.debug('value_xl',value_xl)
                    var commission_xl = convertedfile[mapobj['custrecord_ao_spiff_paid_amouunt']]
                    //                       log.debug('commission_xl',commission_xl)
                    var activationMonth_xl = convertedfile[mapobj['custrecord_ao_spiff_paid_date']]
                    //                       log.debug('activationMonth_xl',activationMonth_xl)


                    //                       log.debug('intrId',intrId)
                    var newDate = activationMonth_xl.split('-')
                    //                       log.debug('newDate',newDate)
                    var parsedDateStringAsRawDateObject = format.parse({
                        value: newDate[0] + "/" + newDate[1] + "/" + newDate[2],
                        type: format.Type.DATE
                    });
                    //                       log.debug("parsedDateStringAsRawDateObject", parsedDateStringAsRawDateObject)
                    var formattedDateString = format.format({
                        value: parsedDateStringAsRawDateObject,
                        type: format.Type.DATE
                    });
                    //                                        log.debug("dueDate after getdate", formattedDateString)

                    var cust_load = record.load({
                        type: 'customrecord_jj_tracfone_activations',
                        id: intrId
                        /*,
                        isDynamic: true */
                    });
                    cust_load.setValue({
                        fieldId: "custrecord_jj_plan",
                        value: value_xl
                    });
                    cust_load.setValue({
                        fieldId: "custrecord_ao_spiff_paid_amouunt",
                        value: commission_xl
                    });
                    cust_load.setText({
                        fieldId: "custrecord_ao_spiff_paid_date",
                        text: formattedDateString
                    });
                    var id = cust_load.save();
                    log.debug("Record updated ", id);

                }
            },
            /*Create record actions Process */
            createrecord: function(recordtype, mapobj, convertedfile, processfolderid) {

                var duplicate = false;
                if (convertedfile.length > 0) {
                    var objRecord = record.create({
                        type: recordtype,
                        isDynamic: true
                    });
                    for (var key in mapobj) {
                        if (key != "-") {
                            var currentValue = main.doValidations(convertedfile[mapobj[key]], recordtype);
                            try {
                                objRecord.setValue({
                                    fieldId: key,
                                    value: currentValue.toString().trim()
                                });
                            } catch (e) {
                                try {
                                    objRecord.setText({
                                        fieldId: key,
                                        text: currentValue.toString().trim()
                                    });
                                } catch (error) {
                                    // log.debug("Error for creating record", error.message)
                                    convertedfile.push(error.message);
                                    //                                        log.debug("Econvertedfile", convertedfile)
                                    main.errorlog(processfolderid, convertedfile);
                                    return error;
                                }
                            }
                        }
                    };
                    if (recordtype == "customrecord_jj_branded_handset") {
                        var simno = convertedfile[mapobj['custrecord_jj_sim']]
                        var esnno = convertedfile[mapobj['custrecord_jj_esn']]
                        duplicate = main.checksim(simno, esnno, processfolderid, convertedfile);
                        var tectraId = objRecord.getValue({
                            fieldId: 'custrecord_jj_branded_tcetraid'
                        });
                        var customerDetails = main.findCustomerdetails(tectraId, "custentity1");
                        objRecord.setValue({
                            fieldId: "custrecord_jj_customer",
                            value: customerDetails.customerId
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_sales_rep",
                            value: customerDetails.salesreppartner
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_subof_sales_partner",
                            value: customerDetails.subof
                        });
                    } else if (recordtype == "customrecord_jj_route_run") {

                        var tectraId = objRecord.getValue({
                            fieldId: 'custrecord_jj_tcetraid'
                        });
                        var customerDetails = main.findCustomerdetails(tectraId, "custentity1");
                        objRecord.setValue({
                            fieldId: "custrecord_jj_customerid",
                            value: customerDetails.customerId
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_sales_rep_route",
                            value: customerDetails.salesreppartner
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_subof_route",
                            value: customerDetails.subof
                        });
                    } else if (recordtype == "customrecord_jj_qpay_marketplace_details") {

                        var incommId = objRecord.getValue({
                            fieldId: 'custrecord_jj_branchid'
                        });
                        var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid");
                        objRecord.setValue({
                            fieldId: "custrecord_qpay_customerid",
                            value: customerDetails.customerId
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_sales_rep_maeket",
                            value: customerDetails.salesreppartner
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_subof_market",
                            value: customerDetails.subof
                        });
                    } else if (recordtype == "customrecord_jj_qpaydetail_transaction") {
                        /*as per discusions on 07-07 parent id and parent name need not to be set*/
                        var incommId = objRecord.getValue({
                            fieldId: 'custrecord_jj_qpaydetail_incommid'
                        });
                        var parentId = objRecord.getValue({
                            fieldId: 'custrecord_jj_details_parentid'
                        });
                        //getting the parent name
                        var parentName = objRecord.getValue({
                            fieldId: 'custrecord_jj_qpaydetail_parent_nm'
                        });
                        var customerDetails = main.findCustomerdetails(incommId, "custentityincomeexclusiveid");
                        objRecord.setValue({
                            fieldId: "custrecord_jj_qpaydetail_custid",
                            value: customerDetails.customerId
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_sales_rep_qpay",
                            value: customerDetails.salesreppartner
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_subof_salesrep",
                            value: customerDetails.subof
                        });

                        // set the parent id id in the customer record
                        /*            var parId = record.submitFields({
                        type: record.Type.CUSTOMER,
                        id: customerDetails.customerId,
                        values: {
                        custentity_jj_parentaccountid: parentId,
                        custentity_jj_parentname: parentName
                        }
                        });*/

                    } else if (recordtype == "customrecord223") {
                        var tectraId = objRecord.getValue({
                            fieldId: 'custrecord6'
                        });
                        var customerDetails = main.findCustomerdetails(tectraId, "custentity1");
                        //                            log.debug(tectraId, customerDetails);
                        objRecord.setValue({
                            fieldId: "custrecord_jj_customer_vidapay",
                            value: customerDetails.customerId
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_salesrep_vidapay",
                            value: customerDetails.salesreppartner
                        });
                        objRecord.setValue({
                            fieldId: "custrecord_jj_subof_vidapay",
                            value: customerDetails.subof
                        });
                    } else if (recordtype == "customrecord_jj_tracfone_activations") {



                    } else if (recordtype == "customrecord_mw_tracfone_residual_month") {
                        var sim = objRecord.getValue({
                            fieldId: 'custrecord_jj_trc_mnthly_sim'
                        });
                        //                            log.debug("sim", sim)
                        try {
                            var activationsSearchObj = search.create({
                                type: 'customrecord_jj_tracfone_activations',
                                columns: [{
                                        name: "custrecord_jj_tracfone_activa_cusid"
                                    },
                                    {
                                        name: 'custrecord_jj_sales_rep_tracfone'
                                    },
                                    {
                                        name: 'custrecord_jj_city'
                                    },
                                    {
                                        name: 'custrecord_jj_state'
                                    }
                                ],
                                filters: ["custrecordjj_tra_sim", "is", sim]
                            });
                            var activationsResultCount = activationsSearchObj.runPaged().count;
                            if (activationsResultCount == 1) {
                                //then there will be 1 sim in tracfone activation record
                                var searchResult = activationsSearchObj.run().getRange({
                                    start: 0,
                                    end: 1
                                });
                                //                                    log.debug("searchResult", searchResult);
                                var custID = searchResult[0].getValue({
                                    name: 'custrecord_jj_tracfone_activa_cusid'
                                });
                                //                                    log.debug("custID from Tracfone", custID);
                                if (custID != '') {
                                    var searchResultForCustomer = main.searchForCustomer(custID);
                                    objRecord.setValue({
                                        fieldId: "custrecord_mw_tracfone_customer",
                                        value: custID
                                    });
                                }
                                //                                    log.debug("searchResultForCustomer", searchResultForCustomer);
                                var salesRepTrcMnthly = searchResult[0].getText({
                                    name: 'custrecord_jj_sales_rep_tracfone'
                                });
                                var cityTrcMnthly = searchResult[0].getValue({
                                    name: 'custrecord_jj_city'
                                });
                                var stateTrcMnthly = searchResult[0].getValue({
                                    name: 'custrecord_jj_state'
                                });
                            }

                            objRecord.setValue({
                                fieldId: "custrecord_jj_sales_name",
                                value: salesRepTrcMnthly
                            });
                            objRecord.setValue({
                                fieldId: "custrecord_jj_trc_mnthly_city",
                                value: cityTrcMnthly
                            });
                            objRecord.setValue({
                                fieldId: "custrecord_jj_trc_mnthly_state",
                                value: stateTrcMnthly
                            });
                            objRecord.setValue({
                                fieldId: "custrecord_jj_parent_name",
                                value: searchResultForCustomer.parentName
                            });
                            objRecord.setValue({
                                fieldId: "custrecord_jj_parent_id",
                                value: searchResultForCustomer.parentID
                            });
                            objRecord.setValue({
                                fieldId: "custrecord_incomm_id",
                                value: searchResultForCustomer.incommId
                            });
                            objRecord.setValue({
                                fieldId: "custrecordcustrecord_tcetra_id",
                                value: searchResultForCustomer.tectraId
                            });
                        } catch (e) {
                            log.debug("e", e);
                        }
                    }
                }
                if (duplicate == false) {
                    var id = objRecord.save();
                    log.debug("Record Created ", id);
                } else {
                    log.debug("duplicate ", duplicate);
                }

            },
            /* create a search in customer record to find the corresponding  customer according to the tcetra id*/
            /*Route Run  and Branded Handset*/
            findCustomerdetails: function(tectraId, searchField) {
                var customerSearchObj = search.create({
                    type: "customer",
                    filters: [
                        [searchField, "contains", tectraId], "AND", ["subsidiary", "anyof", "2"]
                    ],
                    columns: [searchField, "internalid"]
                });
                var searchResultCount = customerSearchObj.runPaged().count;
                if (searchResultCount <= 0) {

                    customerSearchObj = search.create({
                        type: "customer",
                        filters: [
                            [searchField, "contains", tectraId]
                        ],
                        columns: [searchField, "internalid"]
                    });
                    searchResultCount = customerSearchObj.runPaged().count;
                    //                        log.debug("searchResultCount insidfa", searchResultCount);

                }
                // var searchResultCount = customerSearchObj.runPaged().count;
                var returnObj = {};
                customerSearchObj.run().each(function(result) {
                    // get the customer id
                    returnObj.customerId = result.getValue('internalid');
                    // To get the sales rep partner id from the customer record         
                    var lookupfieldofpartner = search.lookupFields({
                        type: 'customer',
                        id: returnObj.customerId,
                        columns: ['partner']
                    });
                    if (lookupfieldofpartner.partner[0]) {
                        returnObj.salesreppartner = lookupfieldofpartner.partner[0].value;
                    }
                    // to get parent id from partner record
                    var lookupfieldofsub = search.lookupFields({
                        type: 'partner',
                        id: returnObj.salesreppartner,
                        columns: ['parent']
                    });
                    if (lookupfieldofsub.parent[0]) {
                        returnObj.subof = lookupfieldofsub.parent[0].value;
                    }
                });
                return returnObj;
            },
            checksim: function(simno, esnno, processfolderid, convertedfile) {
                var branded_handset_search_sim = search.create({
                    type: "customrecord_jj_branded_handset",
                    filters: [
                        ["custrecord_jj_sim", "is", simno]
                    ],
                    columns: [
                        search.createColumn({
                            name: "id",
                            sort: search.Sort.ASC,
                            label: "ID"
                        }),
                        search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }),
                        search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }),
                        search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }),
                        search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" })
                    ]
                });
                var searchResultCountSim = branded_handset_search_sim.runPaged().count;
                //                    log.debug("Brandend Handset Sim Search Count", searchResultCountSim);
                if (searchResultCountSim > 0) {
                    convertedfile.push("Duplicate Sim Number");
                    main.errorlog(processfolderid, convertedfile);
                    //                        log.debug("duplicate SIM ", simno)
                    return true;
                } else {
                    var branded_handset_search_esn = search.create({
                        type: "customrecord_jj_branded_handset",
                        filters: [
                            ["custrecord_jj_esn", "is", esnno]
                        ],
                        columns: [
                            search.createColumn({
                                name: "id",
                                sort: search.Sort.ASC,
                                label: "ID"
                            }),
                            search.createColumn({ name: "custrecord_jj_customer", label: "Customer" }),
                            search.createColumn({ name: "custrecord_jj_sim", label: "SIM" }),
                            search.createColumn({ name: "custrecord_jj_esn", label: "ESN" }),
                            search.createColumn({ name: "custrecord_jj_branded_tcetraid", label: "Tcetra Id" })
                        ]
                    });
                    var searchResultCountESN = branded_handset_search_esn.runPaged().count;
                    //                        log.debug("Brandend Handset ESN Search Count", searchResultCountESN);
                    //  customrecord_jj_branded_handsetSearchObj.run().each(function(result){
                    //     // .run().each has a limit of 4,000 results
                    //     return true;
                    //  });
                    if (searchResultCountESN > 0) {
                        convertedfile.push("Duplicate ESN Number");
                        main.errorlog(processfolderid, convertedfile);
                        //                            log.debug("duplicate ESN ", esnno)

                        return true;
                    }
                }
                return false
            },
            searchForCustomer: function(custID) {
                var obj = {};
                var customerSearchObj = search.create({
                    type: "customer",
                    filters: [
                        ["internalidnumber", "equalto", custID]
                    ],
                    columns: [{
                            name: "custentity_jj_parentname"
                        },
                        {
                            name: "custentity_jj_parentaccountid"
                        },
                        {
                            name: "custentity1"
                        },
                        {
                            name: "custentityincomeexclusiveid"
                        }
                    ]
                });
                var searchResultCount = customerSearchObj.runPaged().count;
                if (searchResultCount > 0) {

                    var searchResult1 = customerSearchObj.run().getRange({
                        start: 0,
                        end: 1
                    });
                    //      log.debug("searchResult1",searchResult1);


                    obj.parentName = searchResult1[0].getValue({
                        name: 'custentity_jj_parentname'
                    });
                    //      log.debug("parentName",obj.parentName);

                    obj.parentID = searchResult1[0].getValue({
                        name: 'custentity_jj_parentaccountid'
                    });
                    obj.incommId = searchResult1[0].getValue({
                        name: 'custentityincomeexclusiveid'
                    });
                    obj.tectraId = searchResult1[0].getValue({
                        name: 'custentity1'
                    });
                    //  log.debug("parentID",obj.parentID);

                }
                //  log.debug("obj",obj);

                return obj;

            },
            /*Delete JSON chunks Folder after the Import Process */
            folderdelete: function(mapinternal) {
                var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid");
                var processarray = main.findprocessfiles(processfolderid, true);
                for (i = 0; i < processarray.length; i++) {
                    file.delete({
                        id: processarray[i].internalid
                    });
                }
                file.delete({
                    id: mapinternal
                });
                var folderdelete = record.delete({
                    type: "folder",
                    id: processfolderid
                });
            },
            /*To create an folder that contain all the errors */
            errorlog: function(processfolderid, convertedfile) {
                var filename = Date.now();
                var folderid;
                var init = main.checkforfolder(processfolderid);
                if (init == true) {
                    folderid = main.createfolder(processfolderid);
                } else {
                    folderid = init;

                }
                var processfileid = main.createfile(filename, folderid, convertedfile);
            },
            /*Check whether the input string is Date or number or String */
            /*if date format is mm/dd/yyy*/
            doValidations: function(string, recordtype) {
                /*check whether inputed data is date*/
                //                    log.debug("string date in dovalidation", string);
                var inputString = main.isDate(string);
                log.debug("inputString", inputString)
                if (inputString == false) {
                    if (isNaN(string)) {
                        return string;
                    } else {
                        if (string == null || string == "") {
                            return "";
                        } else {
                            return Number(string);
                        }
                    }
                } else {
                    if (recordtype == "customrecord_mw_tracfone_residual_month") {
                        if (string.indexOf("-") > 0) {
                            var dateArray = string.split("-");
                            var datestr = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2];
                            //                                log.debug("date last of do validation", datestr);
                            return datestr;

                        } else {
                            return string
                        }

                    }
                    var string = string.replace(/-/g, "/");
                    if (new Date(string.toString()) == "Invalid Date") {
                        return string;
                    } else {
                        var today = new Date(string);
                        //                            log.debug("today", today)
                        var dd = today.getDate();
                        var mm = today.getMonth() + 1;
                        var yyyy = today.getFullYear();
                        if (yyyy < 2000)
                            yyyy = yyyy + 100;
                        // if (mm < 10) {
                        //     mm = mm;
                        // }
                        var datestr = mm + '/' + dd + '/' + yyyy;
                        //                            log.debug("date last of do validation", datestr)
                        return datestr;
                    }
                }
            },
            /*To find whether the input string is date or not */
            isDate: function(value) {
                var dateFormat;
                if (toString.call(value) === '[object Date]') {
                    return true;
                }
                if (typeof value.replace === 'function') {
                    value.replace(/^\s+|\s+$/gm, '');
                }
                dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})?$/;
                return dateFormat.test(value);
            },
            /*Summary function Of map reduce */
            summarize: function(summary) {
                var errorfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid");
                var errorfolder = main.finderrorfiles(errorfolderid);

                var processfolderid = runtime.getCurrentScript().getParameter("custscript_json_fileid");
                var mapinternal = main.findprocessfiles(processfolderid, false);
                var contextfile = file.load({
                    id: mapinternal
                });
                var contextContent = contextfile.getContents();
                var contextContent = JSON.parse(contextContent);

                var contextobj = JSON.parse(contextContent);
                var operation = contextobj.contextdetails.operation;
                var emailaddr = contextobj.emailaddress;
                var recordtype = contextobj.contextdetails.recordtype;
                var recordname = contextobj.contextdetails.recordname;

                if (operation == "create") {
                    if (errorfolder == null || errorfolder == "" || errorfolder == undefined) {
                        var mailBody = main.createResponse(recordtype, recordname, "success");
                        email.send({
                            author: -5,
                            recipients: emailaddr,
                            cc: ["edwin@jobinandjismi.com", "feena@jobinandjismi.com"],
                            subject: "IMPORT Completed For  " + recordname,
                            body: mailBody
                        });
                    } else {
                        main.errortocsv(contextobj, errorfolder);
                    }
                } else {
                    var mailBody = main.createResponse(recordtype, recordname, "delete");
                    email.send({
                        author: -5,
                        recipients: emailaddr,
                        cc: ["edwin@jobinandjismi.com", "feena@jobinandjismi.com"],
                        subject: "Succesfully Deleted the  " + recordname,
                        body: mailBody
                    });
                }
                main.folderdelete(mapinternal);
                var pendingId = main.findPending();
                //                    log.debug("pendingId", pendingId)
                if (pendingId != false) {
                    var pendingFile = file.load({
                        id: pendingId
                    });
                    var pendingContent = pendingFile.getContents();
                    var pendingContent = JSON.parse(pendingContent);
                    //                        log.debug("pendingContent", pendingContent);
                    //                        log.debug("pendingContent", pendingContent.custscript_json_fileid);
                    main.scheduleanother(pendingContent.custscript_json_fileid, "", "", pendingContent);
                    file.delete({ id: pendingId });
                }
            },
            /*Setup map reduce script*/
            scheduleanother: function(fileid, mapid, mapfile, catchFile) {
                try {
                    var scheduleScrptTask = task.create({
                        taskType: task.TaskType.MAP_REDUCE,
                        scriptId: "customscript_mr_mapreducerecord",
                        deploymentId: 'customdeploy_mr_mapreducerecord',
                        params: {
                            custscript_json_fileid: fileid,
                            custscript_type: mapfile
                        }
                    });
                    scheduleScrptTask.submit();
                    /*            var mapFileid = JSON.parse(mapid)
                    var emailaddr = mapFileid.emailaddress;
                    var recordtype = mapFileid.contextdetails.recordtype;
                    var recordname = mapFileid.contextdetails.recordname;
                    var mailBody = main.createResponse(recordtype, recordname);
                    email.send({
                    author: -5,
                    recipients: emailaddr,
                    subject: "Import Process Succesfully Started for " + recordname,
                    body: mailBody
                    });*/
                } catch (e) {
                    log.debug("e in scheduleanother", e);
                    var params = {
                        custscript_json_fileid: fileid,
                        custscript_type: mapfile
                    }
                    main.createfile(Date.now(), 26540, params);

                }
            },
            findPending: function() {
                var fileSearchObj = search.create({
                    type: "file",
                    filters: [
                        ["folder", "anyof", 26540]
                    ],
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "name",
                            sort: search.Sort.ASC,
                            label: "Name"
                        })
                    ]
                });
                var searchResultCount = fileSearchObj.runPaged().count;
                if (searchResultCount < 1) {
                    return false
                } else {
                    var internalid;
                    fileSearchObj.run().each(function(result) {
                        internalid = result.getValue("internalid");
                        return true;
                    });
                    return internalid;
                }
            },
            createResponse: function(recordtype, recordname, flag) {
                var htmlFile = file.load({
                    id: 39539
                });
                var htmlFilecontent = htmlFile.getContents();
                if (flag == "success") {
                    var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed Successfully");
                    var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record :  " + recordname);
                } else if (flag == "unsuccess") {
                    var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Import Completed With Some issues ");
                    var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record   " + recordname);
                } else if (flag == "delete") {
                    var htmlFilecontent1 = htmlFilecontent.replace("<-replacewithtype->", "Succesfully Deleted The Record  ");
                    var htmlFilecontent2 = htmlFilecontent1.replace("<-ReplaceWithRecord->", "For Record   " + recordname);
                }
                return htmlFilecontent2;
            },
            errortocsv: function(contextobj, errorfolder) {
                try {
                    // to get the data
                    //To create the CSV file
                    var XML_TO_PRINT = main.getXMLDataExcel(file, contextobj, errorfolder);
                    var strXmlEncoded = encode.convert({
                        string: XML_TO_PRINT,
                        inputEncoding: encode.Encoding.UTF_8,
                        outputEncoding: encode.Encoding.BASE_64
                    });
                    var fileObj = file.create({
                        name: 'report.xls',
                        fileType: file.Type.EXCEL,
                        contents: strXmlEncoded
                    });

                    // var id = fileObj.save();
                    // log.debug('id Of newly created CSV', id);
                    var emailaddr = contextobj.emailaddress;
                    var recordtype = contextobj.contextdetails.recordtype;
                    var recordname = contextobj.contextdetails.recordname;
                    var mailBody = main.createResponse(recordtype, recordname, "unsuccess");
                    email.send({
                        author: -5,
                        recipients: emailaddr,
                        cc: ["edwin@jobinandjismi.com", "feena@jobinandjismi.com"],
                        subject: "CSV IMPORT Completed For  Record",
                        attachments: [fileObj],
                        body: mailBody
                    });
                } catch (e) {
                    log.debug("Err @ errortocsv", e.message);
                }
            },
            getXMLDataExcel: function(file, contextobj, errorfolder) {
                var XML = "";
                var TABLE = "";
                var HEADING = "";
                var x = 0,
                    errArray = [],
                    headingArray = [],
                    i, contents, j;
                var myXMLFile = file.load({
                    id: '39548'
                });
                var myXMLFile_value = myXMLFile.getContents();

                headingArray = contextobj.csvColumns;

                errArray = errorfolder;
                headingArray.push("Error Message");
                errArray.unshift(headingArray.toString());
                // to get the total no.of err entries
                var errLength = errArray.length;
                var headingLength = headingArray.length;
                var strVar = "";
                var headVar = "";

                for (i = 0; i < errLength; i++) {
                    var temparray = errArray[i].split(',');
                    strVar += "<Row ss:AutoFitHeight=\"0\">";
                    for (j = 0; j < temparray.length; j++) {
                        strVar += "<Cell><Data ss:Type=\"String\">" + temparray[j] + "<\/Data><\/Cell>";
                    }
                    strVar += "<\/Row>";
                }
                TABLE = TABLE + strVar;
                // HEADING = HEADING +headVar;
                XML = myXMLFile_value.replace('<!-- REPLACEWITHTABLEBODY -->', TABLE);
                return XML;
            }
        };


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

Leave a comment

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