Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
37 kB
3
Indexable
Never
    /**
     * @NApiVersion 2.0
     * @NScriptType Suitelet
     * @NModuleScope Public
     * @Author TC025 Gino
     * @Description Called by 025UE_computeUtilityBtn.js to compute for the Utility
     * Version    Date          Author      Remarks
     * 1.00       30 Mar 2021   TC025 Gino  Initial Version
     * 1.01       01 Jun 2021   TC025 Gino  There is no VAT for solar utility and topline electricity. 12% VAT fixed for water topline.
    */

    define(['N/search','N/record','N/ui/serverWidget','N/redirect', 'N/runtime', './moment'], function (search, record, ui, redirect, runtime, moment){
        /**
         * @Description Suitelet entry point
         * @SavedSearch n/a
         * @Parameters  {context} context user event script context object
         * @Returns n/a
        */

        function onRequest (context) {
            var request = context.request;
            var type = request.parameters.recordType;
            var id = request.parameters.recordId;

            var mtrReadingRecord = record.load({
                type: type,
                id: id,
                isDynamic: false,
            });
            var projectId = mtrReadingRecord.getValue('custrecord_sol_meterreading_project');
            var businessUnit = mtrReadingRecord.getValue('custrecord_sol_meterreading_businessunit');
            var mRType = mtrReadingRecord.getValue('custrecord_sol_meterreading_type');

            var taxCodeList = getTaxCodeList();
            var taxCodeListObj = {};
            taxCodeList.forEach( function(v, i) {
                taxCodeListObj[v.name] = v.rate;
            });
            var meterPriceList = getMeterPrice(projectId,businessUnit,mRType);

            var scriptObj = runtime.getCurrentScript();
            var solarBusUnit = scriptObj.getParameter({name: 'custscript_solarbusinessunit'})
            var toplineBusUnit = scriptObj.getParameter({name: 'custscript_toplinebusinessunit'})


            log.error('solarBusUnit',solarBusUnit);
            log.error('toplineBusUnit',toplineBusUnit);
            log.error('mtrReadingRecord',mtrReadingRecord);

            //First thing to do is compute for previousReading
            var utilityObj = getUtilityLines(id); //Utility Records under this MR
            var allUtilityObj = getAllUtilityLines(); //All Utility Records (used for getting previous Readings)
            var solarUtility = [];
            var toplineUtility = [];
            var allSolarUtility = [];
            var allToplineUtility = [];
            var listOfCasRef = [];

            log.error('utilityObj',utilityObj)
            //Separate Solar from Topline
            utilityObj.forEach( function(v, i) {
                if(v.busUnit == solarBusUnit){ //Solar
                    solarUtility.push(v);
                }else if(v.busUnit == toplineBusUnit){ //Topline
                    toplineUtility.push(v);
                }
                listOfCasRef.push(v.casRefId);
            });

            //Separate ALL Solar from ALL Topline
            allUtilityObj.forEach( function(v, i) {
                if(v.busUnit == solarBusUnit){ //Solar
                    allSolarUtility.push(v);
                }else if(v.busUnit == toplineBusUnit){ //Topline
                    allToplineUtility.push(v);
                }
            });
            log.error('allSolarUtility',allSolarUtility);
            //Compute previousReading for uncomputed
            //Logic: Compare 2 SS to match the recent Utility record with the same meter 
            if(solarUtility.length > 0){
                solarUtility.forEach( function(v, i) {
                    if(v.invoiceRef == '' || !v.invoiceRef || v.invoiceRef == " "){
                        var prevReadIsSet = false;
                        allSolarUtility.forEach( function(pastV, pastI) {
                            if(prevReadIsSet){
                                return;
                            }else if(pastV.meter == v.meter && pastV.internalId != v.internalId && v.currentReading >= pastV.currentReading){
                               v.previousReading = pastV.currentReading;
                                v['mrOfPreviousReading'] = pastV.MRRefText
                                prevReadIsSet = true;
                            }else if(pastV.meter == v.meter && pastV.internalId != v.internalId && moment(pastV.startDate).isBefore(v.startDate)){
                                v.previousReading = pastV.currentReading;
                                v['mrOfPreviousReading'] = pastV.MRRefText
                                prevReadIsSet = true;
                            };
                        });
                        if(!prevReadIsSet){ //This utility record has no past. Therefore setting 0 as previous reading
                            v.previousReading = 0;
                        };
                    };
                });
            };

            log.error('solarUtility',solarUtility);

            if(toplineUtility.length > 0){
                toplineUtility.forEach( function(v, i) {
                    if(v.invoiceRef == '' || !v.invoiceRef || v.invoiceRef == " "){
                        var prevReadIsSet = false;
                        allToplineUtility.forEach( function(pastV, pastI) {
                            if(prevReadIsSet){
                                return;
                            }else if(pastV.meter == v.meter && pastV.internalId != v.internalId && v.currentReading >= pastV.currentReading){
                               v.previousReading = pastV.currentReading;
                                v['mrOfPreviousReading'] = pastV.MRRefText
                                prevReadIsSet = true;
                            }else if(pastV.meter == v.meter && pastV.internalId != v.internalId && moment(pastV.startDate).isBefore(v.startDate)){
                                v.previousReading = pastV.currentReading;
                                v['mrOfPreviousReading'] = pastV.MRRefText
                                prevReadIsSet = true;
                            };
                        });
                        if(!prevReadIsSet){ //This utility record has no past. Therefore setting 0 as previous reading
                            v.previousReading = 0;
                        };
                    };
                });
            };

            log.error('toplineUtility',toplineUtility);
            //End of Computing Previous Readings

            //Second thing to do is compute for all missing fields
            //Solar
            listOfCasRef = removeDups(listOfCasRef);
            var penaltyObj = getPenaltyDetails(listOfCasRef);

            log.error('listOfCasRef',listOfCasRef)
            log.error('penaltyObj',penaltyObj)

            if(solarUtility.length > 0){
                solarUtility.forEach( function(v, i) {
                    // log.error(i,v.invoiceRef);
                    // log.error("v.invoiceRef == ''",v.invoiceRef == '')
                    // log.error('!v.invoiceRef',!v.invoiceRef)
                    // log.error('v.invoiceRef  == " "',v.invoiceRef  == " ")
                    // log.error(' v.invoiceRef', v.invoiceRef)

                    if(v.invoiceRef == '' || !v.invoiceRef || v.invoiceRef  == " "){
                        log.error('solar computing line number: ',i)
                        log.error('computing for: v.invoiceRef',v)
                        log.error('v.mrOfPreviousReading',v.mrOfPreviousReading)
                        v.consumption = v.currentReading - v.previousReading;
                        if(v.consumption < 0){
                            throw 'Computing stopped. A previously dated Meter Reading (' + v.mrOfPreviousReading + ') has lesser current reading than (' + v.MRRefText + ') for Meter: ' + v.meterText + '.'
                        }
                        v.totalConsumption = (parseFloat(parseFloat(v.consumption) * v.billableRate).toFixed(2));
                        v.systemLoss = parseFloat(v.consumption * (parseFloat(v.systemLossPerc)/100));
                        v.systemLossAmt = parseFloat(v.billableRate * v.systemLoss);
                        v.serviceCharge = parseFloat((parseFloat(v.serviceChargePerc)/100) * v.totalConsumption);
                        v.billableAmt = parseFloat(parseFloat(v.totalConsumption) + parseFloat(v.systemLossAmt) + parseFloat(v.serviceCharge));
                        log.error('v.billableAmt',{
                            'totalCons' : parseFloat(v.totalConsumption),
                            'systemLossAmt' : parseFloat(v.systemLossAmt),
                            'serviceCharge' : parseFloat(v.serviceCharge),
                            'v.billableAmt' : v.billableAmt,
                            'v.billableRate' : v.billableRate,
                            'v.systemLoss' : v.systemLoss,
                            'v.consumption' : v.consumption,
                            'v.systemLossPerc' : v.systemLossPerc
                        })
                        v.totalConsumption = addCommas(v.totalConsumption)
                        // log.error('v.totalConsumption',v.totalConsumption)
                        // log.error('parseFloat(v.totalConsumption)',parseFloat(v.totalConsumption))
                        // log.error('parseFloat(v.systemLossAmt)',parseFloat(v.systemLossAmt))
                        // log.error('parseFloat(v.serviceCharge)',parseFloat(v.serviceCharge))
                        // log.error('v.billableAmt',v.billableAmt)
                        //v1.01 No VAT for solar utility
                        v['VAT'] = 0.00;
                        v.totalAmt = parseFloat(parseFloat(v.billableAmt) + parseFloat(v.VAT) + parseFloat(v.reconnectionFee));

                        //Compute for Penalty this month
                        if(v.meterType == 2){ 
                            if(penaltyObj.length > 0){
                                v.penaltyAmount = 0;
                                penaltyObj.forEach( function(invoiceData,index){
                                    if(invoiceData.casRef == v.casRefId){
                                        log.error('equal cas refs',{
                                            invoiceData: invoiceData
                                        })
                                        var minRateMultiplier = invoiceData.daysOverDue * (parseFloat(invoiceData.minPenaltyRate) / 100)
                                        var maxRateMultiplier = parseFloat(invoiceData.maxPenaltyRate) / 100

                                        log.error('equal cas refs',{
                                            minRateMultiplier: minRateMultiplier,
                                            maxRateMultiplier: maxRateMultiplier
                                        })
                                        if(minRateMultiplier > maxRateMultiplier){
                                            var penaltySub = maxRateMultiplier;
                                        }else{
                                            var penaltySub = minRateMultiplier;
                                        }

                                        log.error('penaltySub',penaltySub);
                                        //v.penaltyAmount = parseFloat(parseFloat(v.penaltyAmount) + (invoiceData.amountRemaining * penaltySub)).toFixed(2)
                                        v.penaltyAmount = 0
                                        log.error('v.penaltyAmount',v.penaltyAmount);
                                    }
                                })
                            }
                        }
                        log.error('inside no invoice ref ' + v.internalId,v)
                    };
                });
            };
            log.error('solarUtility after compute',solarUtility);

            //Topline - Uses Meter Price for Total Consumption
            if(toplineUtility.length > 0){
                var listOfComputed = [];
                toplineUtility.forEach( function(v, i) {
                    // log.error(' v.invoiceRef', v.invoiceRef)
                    if(v.invoiceRef == '' || !v.invoiceRef || v.invoiceRef  == " "){
                        // log.error('solar computing line number: ',i)
                        // log.error('computing for: v.invoiceRef',v)
                        // log.error("v.invoiceRef == ''",v.invoiceRef == '')
                        // log.error('!v.invoiceRef',!v.invoiceRef)
                        // log.error('v.mrOfPreviousReading',v.mrOfPreviousReading)
                        v.consumption = v.currentReading - v.previousReading;
                        if(v.consumption < 0){
                            throw 'Computing stopped. A previously dated Meter Reading (' + v.mrOfPreviousReading + ') is lesser than current reading (' + v.MRRefText + ') for Meter: ' + v.meterText + '.'
                        }

                        if(v.meterType == 1){//Electric
                            if(v.invoiceRef == '' || !v.invoiceRef || v.invoiceRef  == " "){
                                
                                v.totalConsumption = (parseFloat(parseFloat(v.consumption) * v.billableRate).toFixed(2));
                                v.systemLoss = parseFloat(v.consumption * (parseFloat(v.systemLossPerc)/100));
                                v.systemLossAmt = parseFloat(v.billableRate * v.systemLoss);
                                v.serviceCharge = parseFloat((parseFloat(v.serviceChargePerc)/100) * v.totalConsumption);
                                v.billableAmt = parseFloat(parseFloat(v.totalConsumption) + parseFloat(v.systemLossAmt) + parseFloat(v.serviceCharge));
                                v.totalConsumption = addCommas(v.totalConsumption)

                                log.error(' v.billableAmt', v.billableAmt)
                                //v1.01 No VAT for Electric
                                v['VAT'] = 0.00;
                                v.totalAmt = parseFloat(parseFloat(v.billableAmt) + parseFloat(v.VAT) + parseFloat(v.reconnectionFee));
                            };
                        }else if(v.meterType == 2){ //Water
                            //Get totalConsumption using Meter Price
                            var metAdditionalPrice = 0;
                            var foundEquivalent = false;
                            meterPriceList.forEach( function(mpList, mpIndex) {
                                if(mpList.unitType == v.unitType && mpList.meterType == v.meterType && mpList.min >= v.consumption && foundEquivalent == false){
                                    log.audit('INSIDE mpList.min : v.consumption',mpList.min + ' : ' + v.consumption);
                                    foundEquivalent = true;
                                    var minDiff = v.consumption - mpList.min;
                                    if(minDiff > 0){
                                        metAdditionalPrice = parseFloat(mpList.rateExVat * minDiff).toFixed(2);
                                    }
                                    metAdditionalPrice = parseFloat(parseFloat(metAdditionalPrice) + parseFloat(mpList.accumulatedRate)).toFixed(2)
                                }else if(mpList.unitType == v.unitType && mpList.meterType == v.meterType && foundEquivalent == false){
                                    log.audit('INSIDE ELSE mpList.min : v.consumption',mpList.min + ' : ' + v.consumption);
                                    //foundEquivalent = true;
                                    var minDiff = v.consumption - mpList.min;
                                    if(minDiff > 0){
                                        metAdditionalPrice = parseFloat(mpList.rateExVat * minDiff).toFixed(2);
                                    }
                                    metAdditionalPrice = parseFloat(parseFloat(metAdditionalPrice) + parseFloat(mpList.accumulatedRate)).toFixed(2)
                                };
                            });
                            if(metAdditionalPrice == 0){
                                throw 'One or more utility record under Topline has no matching Meter Price setup'
                            };

                            v.totalConsumption = metAdditionalPrice;
                            v.systemLoss = parseFloat(v.consumption * (parseFloat(v.systemLossPerc)/100)).toFixed(2);
                            v.systemLossAmt = parseFloat(v.billableRate * v.systemLoss).toFixed(2);
                            v.serviceCharge = parseFloat((parseFloat(v.serviceChargePerc)/100) * v.totalConsumption).toFixed(2);
                            v.billableAmt = parseFloat(parseFloat(v.totalConsumption) + parseFloat(v.systemLossAmt) + parseFloat(v.serviceCharge)).toFixed(2);
                            v.totalConsumption = parseFloat(v.totalConsumption);
                            v['VAT'] = parseFloat(v.billableAmt * 0.12);
                        };

                        //Compute for Penalty this month

                        if(v.meterType == 2){ 
                            if(penaltyObj.length > 0){
                                v.penaltyAmount = 0;
                                penaltyObj.forEach( function(invoiceData,index){
                                    if(invoiceData.casRef == v.casRefId){
                                        log.error('equal cas refs',{
                                            invoiceData: invoiceData
                                        })
                                        var minRateMultiplier = invoiceData.daysOverDue * (parseFloat(invoiceData.minPenaltyRate) / 100)
                                        var maxRateMultiplier = parseFloat(invoiceData.maxPenaltyRate) / 100

                                        log.error('equal cas refs',{
                                            minRateMultiplier: minRateMultiplier,
                                            maxRateMultiplier: maxRateMultiplier
                                        })
                                        if(minRateMultiplier > maxRateMultiplier){
                                            var penaltySub = maxRateMultiplier;
                                        }else{
                                            var penaltySub = minRateMultiplier;
                                        }

                                        log.error('penaltySub',penaltySub);
                                        //v.penaltyAmount = parseFloat(parseFloat(v.penaltyAmount) + (invoiceData.amountRemaining * penaltySub)).toFixed(2)
                                        v.penaltyAmount = 0;
                                        log.error('v.penaltyAmount',v.penaltyAmount);
                                    }
                                })
                            }
                        }
                        
                        v.totalAmt = parseFloat(parseFloat(v.billableAmt) + parseFloat(v.VAT) + parseFloat(v.reconnectionFee)).toFixed(2);
                        listOfComputed.push(v.internalId);
                        log.error('listOfComputed',listOfComputed);
                    };
                });
            };
            log.error('toplineUtility after compute',toplineUtility);
            //End of Computing Missing Fields

            //Third thing to do is set the values to their own fields
            var lineCount = mtrReadingRecord.getLineCount('recmachcustrecord_sol_utility_mrref');
            for(var counter = 0; counter < lineCount; counter++){
                var lineId = mtrReadingRecord.getSublistValue({
                    sublistId: 'recmachcustrecord_sol_utility_mrref',
                    fieldId: 'id',
                    line: counter,
                });

                if(solarUtility.length > 0){
                    solarUtility.forEach( function(solarUtil) {
                        if(solarUtil.internalId == lineId){
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_prevreading',counter,solarUtil.previousReading);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_consumption',counter,solarUtil.consumption);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_billablerate',counter,solarUtil.billableRate);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_totalconsumption',counter,solarUtil.totalConsumption);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_systemloss',counter,solarUtil.systemLoss);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_systemlossamt',counter,solarUtil.systemLossAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_servicecharge',counter,solarUtil.serviceCharge);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_billableamt',counter,solarUtil.billableAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_vat',counter,solarUtil.VAT);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_totalamount',counter,solarUtil.totalAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_project',counter,solarUtil.project);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_customer',counter,solarUtil.customer);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_metertype',counter,solarUtil.meterType);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_meter',counter,solarUtil.meter);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_penaltyamount',counter,solarUtil.penaltyAmount);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_computed',counter,true);

                        };
                    });
                };

                if(toplineUtility.length > 0){
                    toplineUtility.forEach( function(topUtil) {
                        if(topUtil.internalId == lineId){
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_prevreading',counter,topUtil.previousReading);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_consumption',counter,topUtil.consumption);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_billablerate',counter,topUtil.billableRate);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_totalconsumption',counter,topUtil.totalConsumption);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_systemloss',counter,topUtil.systemLoss);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_systemlossamt',counter,topUtil.systemLossAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_servicecharge',counter,topUtil.serviceCharge);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_billableamt',counter,topUtil.billableAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_vat',counter,topUtil.VAT);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_totalamount',counter,topUtil.totalAmt);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_project',counter,topUtil.project);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_customer',counter,topUtil.customer);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_metertype',counter,topUtil.meterType);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_meter',counter,topUtil.meter);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_penaltyamount',counter,topUtil.penaltyAmount);
                            mtrReadingRecord.setSublistValue('recmachcustrecord_sol_utility_mrref','custrecord_sol_utility_computed',counter,true);
                            
                        };
                    });
                };
            };

            log.error('mtrReadingRecord',mtrReadingRecord)
            mtrReadingRecord.save({
                enableSourcing: false,
                ignoreMandatoryFields: true
            });

            redirect.toRecord({
                type: type,
                id: id
            });

            
        };

        // /**
        // * DONOT ALTER THIS FUNCTION
        // * Retrieves all(even if data is more than 2000) 
        // * search results of an nlobjSearchResultSet
        // *
        // * @param  {resultSet} set search result set to retrieve results
        // * @return {Array}     array containing search results
        // */
        var getResults = function(set) {
            var holder = [];
            var i = 0;
            while (true) {
                var result = set.getRange({
                    start: i,
                    end: i + 1000
                    });
                if (!result) break;
                    holder = holder.concat(result);
                if (result.length < 1000) break;
                    i += 1000;
                }
                return holder;
        };

        function getUtilityLines(mrId) {
            var query = search.load({ //[SCRIPT] Utility Record List
                id: 'customsearch_025_utilityrecordlist'
            });
         
            query.filters.push(search.createFilter({
                name: 'custrecord_sol_utility_mrref',
                join: '',
                operator: search.Operator.ANYOF,
                values: mrId
            }));

            var results = getResults(query.run())
            log.error('results',results);
            results = results.map(function (x) {
                return {
                    'internalId': x.getValue(x.columns[0]),
                    'utilityName': x.getValue(x.columns[1]),
                    'startDate': x.getValue(x.columns[2]),
                    'CASRef': x.getValue(x.columns[3]),
                    'MRRef': x.getValue(x.columns[4]),
                    'MRRefText': x.getText(x.columns[4]),
                    'meter': x.getValue(x.columns[5]),
                    'meterText': x.getText(x.columns[5]),
                    'customer': x.getValue(x.columns[6]),
                    'project': x.getValue(x.columns[7]),
                    'billableAmt': x.getValue(x.columns[8]) || 0.00,
                    'billableRate': x.getValue(x.columns[9]) || 0.00,
                    'consumption': x.getValue(x.columns[10]) || 0.00,
                    'previousReadingMod' : x.getValue(x.columns[11]) || 0.00,
                    'currentReadingMod' : x.getValue(x.columns[12]) || 0.00,
                    'reconnectionFee': x.getValue(x.columns[13]) || 0.00,
                    'serviceCharge': x.getValue(x.columns[14]) || 0.00,
                    'systemLoss': x.getValue(x.columns[15]) || 0.00,
                    'systemLossAmt': x.getValue(x.columns[16]) || 0.00,
                    'totalAmt': x.getValue(x.columns[17]) || 0.00,
                    'totalConsumption': x.getValue(x.columns[18]) || 0.00,
                    'unitType': x.getValue(x.columns[19]),
                    'isComputed': x.getValue(x.columns[20]),
                    'busUnit': x.getValue(x.columns[21]),
                    'systemLossPerc': x.getValue(x.columns[22]),
                    'serviceChargePerc': x.getValue(x.columns[23]),
                    'taxItem': x.getValue(x.columns[24]),
                    'meterType': x.getValue(x.columns[25]),
                    'invoiceRef': x.getValue(x.columns[26]),
                    'maxReading' : x.getValue(x.columns[27]) || 0,
                    'previousReading': x.getValue(x.columns[28]) || 0.00,
                    'currentReading': x.getValue(x.columns[29]) || 0.00,
                    'penaltyAmount' : x.getValue(x.columns[30]) || 0,
                    'casRefId' : x.getValue(x.columns[31]),

                }
            })
            log.error('results UR in this MR',results)
            return results;
        };

        function getAllUtilityLines() {
            var query = search.load({ //[SCRIPT] Utility Record List
                id: 'customsearch_025_utilityrecordlist'
            });

            var results = getResults(query.run())

            results = results.map(function (x) {
                return {
                    'internalId': x.getValue(x.columns[0]),
                    'utilityName': x.getValue(x.columns[1]),
                    'startDate': x.getValue(x.columns[2]),
                    'CASRef': x.getValue(x.columns[3]),
                    'MRRef': x.getValue(x.columns[4]),
                    'MRRefText': x.getText(x.columns[4]),
                    'meter': x.getValue(x.columns[5]),
                    'meterText': x.getText(x.columns[5]),
                    'customer': x.getValue(x.columns[6]),
                    'project': x.getValue(x.columns[7]),
                    'billableAmt': x.getValue(x.columns[8]) || 0.00,
                    'billableRate': x.getValue(x.columns[9]) || 0.00,
                    'consumption': x.getValue(x.columns[10]) || 0.00,
                    'previousReadingMod' : x.getValue(x.columns[11]) || 0.00,
                    'currentReadingMod' : x.getValue(x.columns[12]) || 0.00,
                    'reconnectionFee': x.getValue(x.columns[13]) || 0.00,
                    'serviceCharge': x.getValue(x.columns[14]) || 0.00,
                    'systemLoss': x.getValue(x.columns[15]) || 0.00,
                    'systemLossAmt': x.getValue(x.columns[16]) || 0.00,
                    'totalAmt': x.getValue(x.columns[17]) || 0.00,
                    'totalConsumption': x.getValue(x.columns[18]) || 0.00,
                    'unitType': x.getValue(x.columns[19]),
                    'isComputed': x.getValue(x.columns[20]),
                    'busUnit': x.getValue(x.columns[21]),
                    'systemLossPerc': x.getValue(x.columns[22]),
                    'serviceChargePerc': x.getValue(x.columns[23]),
                    'taxItem': x.getValue(x.columns[24]),
                    'meterType': x.getValue(x.columns[25]),
                    'invoiceRef': x.getValue(x.columns[26]),
                    'maxReading' : x.getValue(x.columns[27]) || 0,
                    'previousReading': x.getValue(x.columns[28]) || 0.00,
                    'currentReading': x.getValue(x.columns[29]) || 0.00,
                    'penaltyAmount' : x.getValue(x.columns[30]) || 0,
                }
            })
            log.error('results',results)
            return results;
        };

        function getPenaltyDetails(casRefArr){
            var query = search.load({ //[SCRIPT] PENALTY UTILITY
                id: 'customsearch_sol_penalty_utility'
            });

            query.filters.push(search.createFilter({
                name: 'custbody_sol_inv_casref',
                join: '',
                operator: search.Operator.ANYOF,
                values: casRefArr
            }));

            var results = getResults(query.run())

            results = results.map(function (x) {
                return {
                    'invoiceName': x.getValue(x.columns[0]),
                    'invoiceIntId': x.getValue(x.columns[1]),
                    'dueDate': x.getValue(x.columns[2]),
                    'daysOverDue': x.getValue(x.columns[3]),
                    'amountRemaining': x.getValue(x.columns[4]),
                    'casRef': x.getValue(x.columns[5]),
                    'minPenaltyRate': x.getValue(x.columns[6]),
                    'maxPenaltyRate': x.getValue(x.columns[7]),
                }
            })
            log.error('results',results)
            return results;
        }

        function getTaxCodeList() {
            var query = search.load({ //[SCRIPT] Tax Code
                id: 'customsearch_025_taxcodelist'
            });

            var results = getResults(query.run())

            results = results.map(function (x) {
                return {
                    'internalId': x.getValue(x.columns[0]),
                    'name': x.getValue(x.columns[1]),
                    'itemId': x.getValue(x.columns[2]),
                    'rate': x.getValue(x.columns[3]),
                    'country': x.getValue(x.columns[4]),
                    'category': x.getValue(x.columns[5]),
                }
            })
            log.error('results',results)
            return results;
        };

        function getMeterPrice(projectId,busUnit,mRType) {
            var query = search.load({ //[SCRIPT] Meter Price
                id: 'customsearch_025_meterpricelist'
            });

            query.filters.push(search.createFilter({
                name: 'custrecord_sol_meterprice_project',
                join: '',
                operator: search.Operator.ANYOF,
                values: projectId
            }));

            query.filters.push(search.createFilter({
                name: 'custrecord_sol_meterprice_type',
                join: '',
                operator: search.Operator.ANYOF,
                values: mRType
            }));

            var results = getResults(query.run())

            results = results.map(function (x) {
                return {
                    'internalId': x.getValue(x.columns[0]),
                    'project': x.getValue(x.columns[1]),
                    'meterType': x.getValue(x.columns[2]),
                    'unitType': x.getValue(x.columns[3]),
                    'min': x.getValue(x.columns[4]),
                    'rateExVat': x.getValue(x.columns[5]),
                    'accumulatedRate': x.getValue(x.columns[6]),
                }
            })
            log.error('results',results)
            return results;
        };

        function removeDups(arr){
            var noDup = arr.filter(function(item, pos) {
                return arr.indexOf(item) == pos;
            })

            return noDup;
        }

        function addCommas(nStr) {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }
        
        return {
            onRequest : onRequest
        };

    });