Sales Pipeline for webapp

Jira Code: ISO-125
The sales pipeline shows the number of the customer under a sales rep and the sales details. The UI is done using MD Bootstrap and uses the stepper as a basic block. The UI also contains a Pie chart explaining the Sales.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Sales Pipeline</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <!--Core CSS -->
    <!--    Isogoed_03_10/html/bs3/css/bootstrap.min.css-->
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=194765&c=4494215_SB1&h=b18fbe965e354121f450&_xt=.css" rel="stylesheet" media="All">
    <!--    Isogoed_03_10/html/css/bootstrap-reset.css-->
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=194794&c=4494215_SB1&h=7584ca2e7a1a4eadbf1a&_xt=.css" rel="stylesheet" media="All">
    <!--      Isogoed_03_10/html/font-awesome/css/font-awesome.css" -->
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=194796&c=4494215_SB1&h=e8e466e055d44522a489&_xt=.css" rel="stylesheet" / media="All">
    <!-- Custom styles for this template -->
    <!-- Isogoed_03_10/html/css/style.css -->
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=194787&c=4494215_SB1&h=a24d0395aaa7daa53377&_xt=.css" rel="stylesheet" / media="All">
    <!--    Isogoed_03_10/html/css/style-responsive.css-->
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=194786&c=4494215_SB1&h=cb1a7b5a6a2c2980ce43&_xt=.css" rel="stylesheet" media="All">
    <!-- css and js of search autocomplete jquery-->
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <!--    <link rel="stylesheet" href="https://code.jquery.com/resources/demos/style.css">-->
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <!--    Isogoed_03_10/html/css/sweetalert.css-->
    <link rel="stylesheet" href="https://system.eu1.netsuite.com/core/media/media.nl?id=194781&c=4494215_SB1&h=e02bb5f1f1746070b6e9&_xt=.css" media="All">
    <!--Custom JS SalesPipeline-->
    <script src="https://system.eu1.netsuite.com/core/media/media.nl?id=196224&c=4494215_SB1&h=3d5caa5a5519f49a4d78&_xt=.js"></script>
</head>

<body>
    <section id="container">
        <!--header start-->
        <header class="header fixed-top clearfix">
            <!--logo start-->
            <div class="brand">
                <a href="https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=303&deploy=1&compid=4494215_SB1&h=826da51da56f79e0c696" class="logo">
                    <img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195830&c=4494215_SB1&h=ec0d94ea98481e047fb0" alt="">
                </a>
            </div>
            <div class="search-container">
                <div class="row" style="width: inherit;">
                    <div class="col-lg-8 col-md-8 col-xs-8">
                        <input style="width:315px" type="text" class="form-control search" id="search" placeholder="Search this website..." onkeypress="enter(this.value,event)" style="color:#127bbe">
                    </div>
                    <div class="col-lg-4 col-md-4 col-xs-4">
                        <button style="width:100px; height: 50px; background-color: black; color:white;" type="submit" id="search" onclick="search_link('', myObj,true)"><i class="fa fa-search"></i></button>
                    </div>
                </div>
            </div>
            <!--logo end-->
            <div class="top-nav clearfix">
                <!--search & user info start-->
                <div class="nav nav-tabs" style="width:100%">
                    <div class="tabicon">
                        <a href="https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=303&deploy=1&compid=4494215_SB1&h=826da51da56f79e0c696"><img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195831&c=4494215_SB1&h=7a091767244784943ef2" /></a>
                    </div>
                    <div class="tabicon">
                        <a href="https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=313&deploy=1&compid=4494215_SB1&h=9d0657391e485741ae40"><img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195828&c=4494215_SB1&h=a66f635efcc0741f9917" /></a>
                    </div>
                    <div class="tabicon">
                        <a href="https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=300&deploy=1&compid=4494215_SB1&h=e4c141bb57a426daeb55"><img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195829&c=4494215_SB1&h=b2f286e34c93531fc226" /></a>
                    </div>
                    <div class="tabicon">
                        <a id="quote"><img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195827&c=4494215_SB1&h=24ad321f1f85b62d6fa3" /></a>
                    </div>
                    <div class="tabicon">
                        <p style="display: inline-block; color: black;" id="username"></p>
                        <a href="javascript:clear_coockie();"><img src="https://system.eu1.netsuite.com/core/media/media.nl?id=195826&c=4494215_SB1&h=d66c6ca7d8708bbbc896" /></a>
                    </div>
                </div>
                <!--search & user info end-->
            </div>
        </header>
        <section class="wrapper">
            <section class="panel">
                <div class="panel-body" id="CustomStepper">
                    
                </div>
            </section>
        </section>
    </section>
    </div>
    <!-- Placed js at the end of the document so the pages load faster -->
    <!--Core js-->
    <!--  Isogoed_03_10/html/js/jquery.js  -->
    <script src="https://system.eu1.netsuite.com/core/media/media.nl?id=194888&c=4494215_SB1&h=8fdf4855115e9b756bc2&_xt=.js"></script>
    <!--  Isogoed_03_10/html/js/jquery-ui-1.9.2.custom.min.js -->
    <script type="text/javascript" src="https://system.eu1.netsuite.com/core/media/media.nl?id=194889&c=4494215_SB1&h=8a5d2806218598d02697&_xt=.js"></script>
    <!--  Isogoed_03_10/html/bs3/js/bootstrap.min.js  -->
    <script src="https://system.eu1.netsuite.com/core/media/media.nl?id=194772&c=4494215_SB1&h=5ca201703385f866e2ac&_xt=.js"></script>
    <!--common script init for all pages-->
    <!--Isogoed_03_10/html/js/scripts.js-->
    <script src="https://system.eu1.netsuite.com/core/media/media.nl?id=194874&c=4494215_SB1&h=dd4a239a5f3425ae58d6&_xt=.js"></script>
    <!--script for this page only-->
    <!--    Isogoed_03_10/html/js/sweetalert.min.js-->
    <script src="https://system.eu1.netsuite.com/core/media/media.nl?id=194861&c=4494215_SB1&h=694a81452af0b297f8e9&_xt=.js"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- Material Design Bootstrap -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.13/css/mdb.min.css" rel="stylesheet">
    <link href="https://system.eu1.netsuite.com/core/media/media.nl?id=195926&c=4494215_SB1&h=4477e44b7acb2dfd29d5&_xt=.css" rel="stylesheet">
    <!-- Bootstrap core CSS
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>-->
    <!-- MDB core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.13/js/mdb.min.js"></script>
    <script type="text/javascript" src="https://system.eu1.netsuite.com/core/media/media.nl?id=195990&c=4494215_SB1&h=6042118ec67e4dc2921a&_xt=.js"></script>
</body>

</html>
var myObj, STATUS, LEAD = {},
    PROSPECT = {},
    CUSTOMER = {};
var backgroundColor = ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", "#00695c", "#0d47a1", "#e040fb", "#7986cb", "#26c6da", "#00838f", "#4db6ac", "#00897b", "#2e7d32", "#9e9d24", "#ef6c00"];
var hoverBackgroundColor = ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774", "#2BBBAD", "#4285F4", "#d500f9", "#5c6bc0", "#00bcd4", "#006064", "#26a69a", "#004d40", "#1b5e20", "#827717", "#e65100"];
var leadename_withid = new Array;
var LOGIN_URL = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=301&deploy=1&compid=4494215_SB1&h=b9721a8650d4422839f0";
var CALENDAR_SCRIPT = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=291&deploy=1&compid=4494215_SB1&h=ad57432f9456f6091c49";
var CUSTOMER_URL = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=302&deploy=1&compid=4494215_SB1&h=acb7943127d6f10bcc33";
var SALESPIPELINE = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=321&deploy=1&compid=4494215_SB1&h=63f34e34c604a3339f17";


$(document).ready(function() {
    var name = getCookie("name");
    $('#username').text(name);
    var user = getCookie("sessid"); //taking session id
    var empid = user.match(/[0-9]+/g); //extract only number(custmer id) from session

    if (empid != null) {
        event(empid[0]);
    } else {
        window.location = LOGIN_URL;
    }

    var quote_url = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=299&deploy=1&compid=4494215_SB1&h=5bb1bfab5092d3c297fb&edit=F&empid=" + empid[0];
    document.getElementById("quote").href = quote_url;

    $.post(SALESPIPELINE, { 'empid': empid[0] }, function(data, status) {
        data = JSON.parse(data)

        var split = SplitData(data);
        var table = createTable();
        var pie = createPie();
        $('.stepper').mdbStepper();

        var screenWidth = screen.width;
        if (screenWidth < 490) {
            $('#LEADchart').css('display', 'none');
            $('#PROSPECTchart').css('display', 'none');
            $('#CUSTOMERchart').css('display', 'none');
        } else {
            $('#LEADchart').css('display', 'block');
            $('#PROSPECTchart').css('display', 'block');
            $('#CUSTOMERchart').css('display', 'block');
        }
    });





});

function SplitData(data) {
    STATUS = data['TOTAL_SALES'];
    var Sales = data['STATUS'];
    console.log('STATUS', STATUS);
    Object.keys(Sales).filter(function(el) {

        if (Sales[el].name.toString().toLowerCase().indexOf("lead") > -1)
            return LEAD[el] = Sales[el];
        return false;

    });

    Object.keys(Sales).filter(function(el) {
        if (Sales[el].name.toString().toLowerCase().indexOf("prospect") > -1)
            return PROSPECT[el] = Sales[el];
        return false;

    });

    Object.keys(Sales).filter(function(el) {
        if (Sales[el].name.toString().toLowerCase().indexOf("customer") > -1)
            return CUSTOMER[el] = Sales[el];
        return false;

    });
    return true;
}

function createPie() {
    var obj = { 'LEAD': LEAD, 'PROSPECT': PROSPECT, 'CUSTOMER': CUSTOMER };

    for (var key in obj) {
        var filteredrObj = filterObj(obj[key]);
        var objcount = Object.keys(filteredrObj).length;
        if (objcount > 0) {
            var labels = [],
                count = [];
            Object.keys(filteredrObj).filter(function(el) {
                labels.push(filteredrObj[el]['name']);
                count.push(filteredrObj[el]['count']);
            });

            var bgcolor = backgroundColor.slice(0, objcount);

            var bgHovercolor = hoverBackgroundColor.slice(0, objcount);

            var ChartName = key + 'chart';

            var ctxP = document.getElementById(ChartName).getContext('2d');
            var myPieChart = new Chart(ctxP, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: count,
                        backgroundColor: bgcolor,
                        hoverBackgroundColor: bgHovercolor
                    }]
                },
                options: {
                    responsive: true
                }
            });
        }
    }
}

function filterObj(data) {
    var temp = {};
    Object.keys(data).filter(function(el) {

        if (data[el].count > 0)
            return temp[el] = data[el];
        return false;

    });

    return temp;
}

function createTable() {
    var HTML = "<ul class=\"stepper horizontal horizontal-fix\" id=\"horizontal-stepper-fix\" style=\"margin-top:10px\">";
    //LEAD
    HTML += "<li class=\"step active\">";
    HTML += "<div class=\"step-title waves-effect waves-dark\">LEAD</div>";
    HTML += "<div class=\"step-new-content\"><div class=\"row\"><div class=\"col-xs-12 col-md-6\">";
    HTML += "<button type=\"button\" class=\"btn btn-primary btn-lg\" style=\"margin-bottom:15px\">";
    HTML += "TOTAL LEADS:  <span class=\"badge badge-success ml-2\">" + STATUS['LEAD']['count'] + "</span>";
    HTML += "</button>";
    HTML += "<div class=\"list-group\">";

    for (var key in LEAD) {

        if (LEAD[key].count == 0) {
            HTML += "<a class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += LEAD[key].name;
            HTML += "<span class=\"badge badge-danger badge-pill\">" + LEAD[key].count + "</span>";
        } else {
            var params = '&type=lead&status=' + key + '&statusName=' + LEAD[key].name;
            HTML += "<a href='https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=316&deploy=1&compid=4494215_SB1&h=78696085d35a9b54dfcc" + params + "' class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += LEAD[key].name;
            HTML += "<span class=\"badge badge-primary badge-pill\">" + LEAD[key].count + "</span>";
        }

        HTML += "</a>";
    }
    HTML += "</div></div>";
    HTML += "<div class=\"col-xs-12 col-md-6\"><canvas id=\"LEADchart\"></canvas></div>";
    HTML += "</div></div></li>";

    //PROSPECT
    HTML += "<li class=\"step\">";
    HTML += "<div class=\"step-title waves-effect waves-dark\">PROSPECT</div>";
    HTML += "<div class=\"step-new-content\"><div class=\"row\"><div class=\"col-xs-12 col-md-6\">";
    HTML += "<button type=\"button\" class=\"btn btn-primary btn-lg\" style=\"margin-bottom:15px\">";
    HTML += "TOTAL PROSPECT:  <span class=\"badge badge-success ml-2\">" + STATUS['PROSPECT']['count'] + "</span>";
    HTML += "</button>";
    HTML += "<button type=\"button\" class=\"btn btn-primary btn-lg\" style=\"margin-bottom:15px\">";
    HTML += "QUOTE AMOUNT:  <span class=\"badge badge-secondary ml-2\">" + STATUS['PROSPECT']['amount'] + "</span>";
    HTML += "</button>";
    HTML += "<div class=\"list-group\">";

    for (var key in PROSPECT) {

        if (PROSPECT[key].count == 0) {
            HTML += "<a class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += PROSPECT[key].name;
            HTML += "<span class=\"badge badge-danger badge-pill\">" + PROSPECT[key].count + "</span>";
        } else {
            var params = '&type=prospect&status=' + key + '&statusName=' + PROSPECT[key].name;
            HTML += "<a href='https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=316&deploy=1&compid=4494215_SB1&h=78696085d35a9b54dfcc" + params + "' class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += PROSPECT[key].name;
            HTML += "<span class=\"badge badge-primary badge-pill\">" + PROSPECT[key].count + "</span>";
        }
        HTML += "</a>";
    }
    HTML += "</div></div>";
    HTML += "<div class=\"col-xs-12 col-md-6\"><canvas id=\"PROSPECTchart\"></canvas></div>";
    HTML += "</div></div></li>";

    //CUSTOMER
    HTML += "<li class=\"step\">";
    HTML += "<div class=\"step-title waves-effect waves-dark\">CUSTOMER</div>";
    HTML += "<div class=\"step-new-content\"><div class=\"row\"><div class=\"col-xs-12 col-md-6\">";
    HTML += "<button type=\"button\" class=\"btn btn-primary btn-lg\" style=\"margin-bottom:15px\">";
    HTML += "TOTAL CUSTOMER:  <span class=\"badge badge-success ml-2\">" + STATUS['CUSTOMER']['count'] + "</span>";
    HTML += "</button>";
    HTML += "<button type=\"button\" class=\"btn btn-primary btn-lg\" style=\"margin-bottom:15px\">";
    HTML += "SALES AMOUNT:  <span class=\"badge badge-secondary ml-2\">" + STATUS['CUSTOMER']['amount'] + "</span>";
    HTML += "</button>";
    HTML += "<div class=\"list-group\">";

    for (var key in CUSTOMER) {

        if (CUSTOMER[key].count == 0) {
            HTML += "<a class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += CUSTOMER[key].name;
            HTML += "<span class=\"badge badge-danger badge-pill\">" + CUSTOMER[key].count + "</span>";
        } else {
            var params = '&type=customer&status=' + key + '&statusName=' +CUSTOMER[key].name;
            HTML += "<a href='https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=316&deploy=1&compid=4494215_SB1&h=78696085d35a9b54dfcc" + params + "' class=\"list-group-item d-flex justify-content-between align-items-center\">";
            HTML += CUSTOMER[key].name;
            HTML += "<span class=\"badge badge-primary badge-pill\">" + CUSTOMER[key].count + "</span>";
        }
        HTML += "</a>";
    }
    HTML += "</div></div>";
    HTML += "<div class=\"col-xs-12 col-md-6\"><canvas id=\"CUSTOMERchart\"></canvas></div>";
    HTML += "</div></div></li></ul>";

    $('#CustomStepper').html(HTML);
    return true;
}

function getCookie(session) {
    var name = session + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var cookiearray = decodedCookie.split(';');
    for (var i = 0; i < cookiearray.length; i++) {
        var check = cookiearray[i];
        while (check.charAt(0) == ' ') {
            check = check.substring(1);
        }
        if (check.indexOf(name) == 0) {
            return check.substring(name.length, check.length);
        }
    }
    return "";
}

function enter(customername, event) {
    var x = event.which || event.keyCode;
    if (x == 13) {
        search_link(customername, myObj, false);
    }
}

function clear_coockie() {
    document.cookie = "sessid" + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';

    window.location = "https://forms.eu1.netsuite.com/app/site/hosting/scriptlet.nl?script=301&deploy=1&compid=4494215_SB1&h=b9721a8650d4422839f0";

}

function event(empid) {

    var u = CALENDAR_SCRIPT + "&empid=" + empid;
    cb = 'myCallBack';

    getJSONP(u + "&callback=" + cb);

}

function myCallBack(data) {
    myObj = JSON.parse(data);
    console.log(myObj);
    //var viewdate=myObj[0];
    if (myObj[0] == "success") {
        search(myObj);
    } else {
        console.log("no events");
    }
}

function search(myObj) {
    var name = myObj[3];

    var leadid = myObj[4];




    if (leadid != null) {
        for (i = 0; i < name.length; i++) {
            leadename_withid.push(unescape(name[i]) + '(' + leadid[i] + ')');
        }

    }


    var availableTags = leadename_withid;
    console.log('leadename_withid', leadename_withid);
    $("#search").autocomplete({
        source: availableTags
    });

}

function getJSONP(url) {
    var script = document.createElement('script');
    var head = document.getElementsByTagName('head')[0] || document.documentElement;
    script.src = url
    head.appendChild(script);
}


function search_link(customername, myObj, isevent) {
    console.log('isevent', isevent);
    if (isevent) {
        var customer = $('#search').val();
        document.getElementById("search").value = "";
        //console.log("customer:"+customername);
        var name = myObj[3];

        var leadid = myObj[4];

        var index = leadename_withid.indexOf(customer);
        if (index == -1) {
            swal("Warning", "Search not found!", "warning");
        } else {
            console.log(index);
            var id = leadid[index];
            console.log(id);
            if (id >= 0) {
                window.location = CUSTOMER_URL + '&recordid=' + id;
            }

        }
    } else {
        document.getElementById("search").value = "";
        //console.log("customer:"+customername);
        var name = myObj[3];

        var leadid = myObj[4];

        var index = leadename_withid.indexOf(customername);
        if (index == -1) {
            swal("Warning", "Search not found!", "warning");
        } else {
            console.log(index);
            var id = leadid[index];
            console.log(id);
            if (id >= 0) {
                window.location = CUSTOMER_URL + '&recordid=' + id;
            }

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

* Script Description

* This Suitelet Load and do functionalities for Salespipeline in webapp

*/

/*******************************************************************************
 * 
 * 
 * NetSuite Name :ISO-125 JJ SL Load Salespipeline
 * Script ID: 
 * 
 * *****************************************************************************
 * 
 *  
 * $Author: Jobin & Jismi IT Services LLP $ R A
 * 
 * DESCRIPTION
 * This Suitelet Load and do functionalities for Salespipeline in webapp
 * 
 * Date Created :17-04-2019 
 * 
 * REVISION HISTORY Update:
 * 
 * 
 * 
 ******************************************************************************/
var STATUS = {};
var TOTAL_SALES = { 'LEAD': {}, 'PROSPECT': {}, 'CUSTOMER': {} };

define(['N/search', 'N/file', 'N/record'],
    function(search, file, record) {
        var main = {
            onRequest: function(context) {
                if (context.request.method === 'GET') {
                    var index = file.load({ id: '196223' });
                    var html = index.getContents();
                    context.response.write({
                        output: html
                    });

                } else {
                    var Employee = context.request.parameters.empid;
                    var setStatus = main.getStatus();
                    var totalCustomerSearch = main.findcustomer(Employee);
                    var totalSales = main.findTotalSales(Employee);
                    var arr = {'STATUS':STATUS, 'TOTAL_SALES':TOTAL_SALES};
                    context.response.write(JSON.stringify(arr));
                }
            },
            getStatus: function() {
                var stage = ["LEAD", "PROSPECT", "CUSTOMER"];
                for (var i = 0; i < stage.length; i++) {
                    var objRecord = record.create({
                        type: record.Type[stage[i]],
                        isDynamic: true
                    });
                    var status = objRecord.getField({
                        fieldId: 'entitystatus'
                    });
                    var statusList = status.getSelectOptions();

                    for (var j = 0; j < statusList.length; j++) {
                        STATUS[statusList[j].value] = {
                            name: statusList[j].text,
                            count: 0
                        };
                    }
                }

                return true;
            },
            findcustomer: function(empid) {

                for (var key in TOTAL_SALES) {
                    var customerObj = search.create({
                        type: key.toLowerCase(),
                        filters: [
                            ["stage", "anyof", key],
                            "AND",
                            ["salesrep", "anyof", empid],
                            "AND",
                            ["custentity_jj_assign_to_sales_rep", "is", "T"]
                        ],
                        columns: [
                            search.createColumn({
                                name: "internalid",
                                summary: "COUNT",
                                label: "Internal ID"
                            })
                        ]
                    }).run().getRange({ start: 0, end: 2 });
                    if (customerObj.length > 0 && key == 'LEAD') {
                        TOTAL_SALES[key] = { count: customerObj[0].getValue({ name: "internalid", summary: "COUNT", label: "Internal ID" }) };
                    } else if (customerObj.length > 0 && key == 'PROSPECT') {
                        TOTAL_SALES[key] = {
                            count: customerObj[0].getValue({ name: "internalid", summary: "COUNT", label: "Internal ID" }),
                            amount: main.prosAmountTotSerch(empid)
                        };
                    } else if (customerObj.length > 0 && key == 'CUSTOMER') {
                        TOTAL_SALES[key] = {
                            count: customerObj[0].getValue({ name: "internalid", summary: "COUNT", label: "Internal ID" }),
                            amount: main.customerAmountTotSerch(empid)
                        };
                    }
                }

                return true;

            },
            customerAmountTotSerch: function(empid) {

                var customerAmountTot;
                var salesorderSearchObj = search.create({
                    type: "salesorder",
                    filters: [
                        ["type", "anyof", "SalesOrd"],
                        "AND",
                        ["salesrep", "anyof", empid],
                        "AND",
                        ["customer.stage", "anyof", "CUSTOMER"],
                        "AND",
                        ["mainline", "is", "T"]
                    ],
                    columns: [
                        search.createColumn({
                            name: "amount",
                            summary: "SUM",
                            label: "Amount"
                        })
                    ]
                }).run().getRange({ start: 0, end: 2 });

                if (salesorderSearchObj.length > 0)
                    return '€ ' + salesorderSearchObj[0].getValue({ name: "amount", summary: "SUM", label: "Amount" });
                else
                    return '€ 0';
            },
            prosAmountTotSerch: function(empid) {

                var estimateSearchObj = search.create({
                    type: "estimate",
                    filters: [
                        ["type", "anyof", "Estimate"],
                        "AND",
                        ["customer.stage", "anyof", "PROSPECT"],
                        "AND",
                        ["salesrep", "anyof", empid],
                        "AND",
                        ["mainline", "is", "T"]
                    ],
                    columns: [
                        search.createColumn({
                            name: "amount",
                            summary: "SUM",
                            label: "Amount"
                        })
                    ]
                }).run().getRange({ start: 0, end: 2 });

                if (estimateSearchObj.length > 0)
                    return '€ ' + estimateSearchObj[0].getValue({ name: "amount", summary: "SUM", label: "Amount" });
                else
                    return '€ 0';
            },
            // getEstimateAmount: function(CUSTOMER_ID) {
            //     var estimateSearchObj = search.create({
            //         type: "estimate",
            //         filters: [
            //             ["customer.internalidnumber", "equalto", CUSTOMER_ID],
            //             "AND",
            //             ["type", "anyof", "Estimate"],
            //             "AND",
            //             ["mainline", "is", "T"]
            //         ],
            //         columns: [
            //             search.createColumn({ name: "amount", summary: "SUM", label: "Amount" })
            //         ]
            //     }).run().getRange({ start: 0, end: 2 });
            //     if (estimateSearchObj.length > 0)
            //         return estimateSearchObj[0].getValue({ name: "amount", summary: "SUM", label: "Amount" });
            //     else
            //         return '0';
            // },
            // getSalesAmount: function(CUSTOMER_ID) {
            //     var SOSearchObj = search.create({
            //         type: "salesorder",
            //         filters: [
            //             ["customer.internalidnumber", "equalto", CUSTOMER_ID],
            //             "AND",
            //             ["type", "anyof", "SalesOrd"],
            //             "AND",
            //             ["mainline", "is", "T"]
            //         ],
            //         columns: [
            //             search.createColumn({ name: "amount", summary: "SUM", label: "Amount" })
            //         ]
            //     }).run().getRange({ start: 0, end: 2 });
            //     if (SOSearchObj.length > 0)
            //     {
            //         log.debug('amount',SOSearchObj[0].getValue({ name: "amount", summary: "SUM", label: "Amount" }));
            //         return SOSearchObj[0].getValue({ name: "amount", summary: "SUM", label: "Amount" });
            //     }
            //     else
            //         return '0';
            // },
            findTotalSales: function(empid) {
                var stage = ["LEAD", "PROSPECT", "CUSTOMER"];
                for (var i=0 ;i<stage.length;i++) {
                    var leadSearchObj = search.create({
                        type: stage[i].toLowerCase(),
                        filters: [
                            ["stage", "anyof", stage[i]],
                            "AND",
                            ["salesrep", "anyof", empid],
                            "AND",
                            ["custentity_jj_assign_to_sales_rep", "is", "T"]
                        ],
                        columns: [
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({ name: "entitystatus", label: "Status" })
                        ]
                    });
                    if (stage[i] == "LEAD") {
                        leadSearchObj.run().each(function(result) {
                            var STATUS_ID = result.getValue({ name: "entitystatus", label: "Status" });
                            if (STATUS[STATUS_ID]) 
                                STATUS[STATUS_ID]['count'] = STATUS[STATUS_ID]['count'] + 1;
                           
                            return true;
                        });
                    }
                    else if(stage[i] == "PROSPECT")
                    {
                         leadSearchObj.run().each(function(result) {
                            var STATUS_ID = result.getValue({ name: "entitystatus", label: "Status" });
                            var id = result.getValue({ name: "internalid", label: "Internal ID" });
                            if (STATUS[STATUS_ID])
                            {
                                STATUS[STATUS_ID]['count'] = STATUS[STATUS_ID]['count'] + 1;
                                //STATUS[STATUS_ID]['amount'] = Number(STATUS[STATUS_ID]['amount'])+Number(main.getEstimateAmount(id));
                            } 
                                
                           
                            return true;
                        });
                    }
                    else if(stage[i] == "CUSTOMER")
                    {
                         leadSearchObj.run().each(function(result) {
                            var STATUS_ID = result.getValue({ name: "entitystatus", label: "Status" });
                            var id = result.getValue({ name: "internalid", label: "Internal ID" });
                            if (STATUS[STATUS_ID])
                            {
                                STATUS[STATUS_ID]['count'] = STATUS[STATUS_ID]['count'] + 1;
                                //STATUS[STATUS_ID]['amount'] = Number(STATUS[STATUS_ID]['amount'])+Number(main.getSalesAmount(id));
                            } 
                                
                           
                            return true;
                        });
                    }
                }
            }

        }
        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 *