Hi All, I have a script that had been working fine...
# suitescript
b
Hi All, I have a script that had been working fine and now it's stopped working and I can't find the cause. It's a map reduce script and it basically runs on selected purchase invoices and creates another purchase invoice from the data on the original invoice and then adjusts the original invoice. It is still doing the later part and adjusting the original invoice but the new invoice is not being created. This is causing an eternal loop as since it doesn't create the new invoice it keeps trying... each time adjusting the data on the original invoice making the numbers wildly incorrect. I've put some debug lines is and it seems to create the new invoice - it gets an internal ID etc, but then it looses it somewhere... When I look at the list of all transaction internal IDs there always seems to be a gap of 100 numbers starting from the new id. This is the extract of the code where the record is saved. Attached image shows some of the debug notes.. including the two within this part of the script.
Copy code
var intWhInvoiceId = objWhInvoice.save({
                    ignoreMandatoryFields: true,
                    enableSourcing: true
                });
              log.audit('Internal ID of New Transaction', intWhInvoiceId);
                var objInvoiceLookup = search.lookupFields({
                    type: search.Type.VENDOR_BILL,
                    id: intWhInvoiceId,
                    columns: ['transactionnumber']
                });
                var stWhInvoiceTranId = objInvoiceLookup.transactionnumber;
log.debug('NEW CREATED TRANSACTION', stWhInvoiceTranId);
I'm banging my head against a wall... so any help would be appreciated.
n
have you added logging in your summary section to show any errors?
v
I'd probably wrap the entire reduce() block in a try.. catch too, and log the catch
b
@verikott All the code is wrapped in try... catch which at the moment just is set to return log.error('Error on update: ' + intRecordId, ex); but it doesn't error so no error is thrown
n
if you haven't already, add in the summary logging.
b
@NElliott I was just looking at that - the summary section is just like below, so not logging anything. What sort of things can I put in here to log?
Copy code
function summarize(summary) {
        // log.debug('summarize()', 'START');

        try {
            // log.debug('END OF M/R');
        }
        catch (ex) {
            var stError = (ex.getCode != null) ? ex.getCode() + '\n' + ex.getDetails() + '\n' : ex.toString();
            log.error('Error: summarize()', stError);
        }
    }
n
I provided a link to the logging you can use
Click through the link to where I've discussed it before 😉
b
Just looking at that now....
@NElliott I've read through all in that link and think this should get me to the bottom of the problem as it is discussing a link about a record which wasn't saving as well. Do I put the logging in the summarize function? For example would I put this code in there...
Copy code
summary.reduceSummary.errors.iterator().each(function (key, error) {
    log.error('Reduce Error for key: ' + key, error);
    return true;
});
I've put in a reduce error and map error as per your example and nothing comes back.. does this mean it's not finding the error?
b
what does your code look like
b
There is lots commented out whilst I've been trying to identify the issue but this is the code...
Copy code
/**
 *@NApiVersion 2.x
 *@NScriptType MapReduceScript
 */
define(['N/record', 'N/runtime', 'N/search', 'N/email'], function(record, runtime, search, email) {
    var objScript = runtime.getCurrentScript();
    var param_transactionsearch = objScript.getParameter({name: 'custscript_tv_bwt_txn_search'});

    function getInputData() {
        // log.debug('getInputData()', 'START');

        try {
            var arrResults = [];
            var objTransactionSearch = loadSearch(null, param_transactionsearch);

            objTransactionSearch.forEach(function(result){
                arrResults.push(result.getValue({
                    name: 'internalid',
                    summary: 'GROUP',
                }));
            });
            log.debug('arrResults', arrResults);

            return arrResults;
        }
        catch (ex) {
            var stError = (ex.getCode != null) ? ex.getCode() + '\n' + ex.getDetails() + '\n' : ex.toString();
            log.error('Error: getInputData()', stError);
        }
    }

    function map(context) {
        // log.debug('map()', 'START');

        try {
            // var objData = JSON.parse(context.value);
            var intRecordId  = context.value;

            context.write({
                key: intRecordId,
                value: intRecordId
            });
        }
        catch (ex) {
            var stError = (ex.getCode != null) ? ex.getCode() + '\n' + ex.getDetails() + '\n' : ex.toString();
            log.error('Error: map()', stError);
        }
    }

    function reduce(context) {
        // log.debug('reduce()', 'START');

        try {
            var intRecordId = context.key;
            var intPurchaseInvoiceId = createPurchaseInvoice(intRecordId);
            log.debug('reduce Original Purchase Invoice', intRecordId);
            log.debug('reduce Created Purchase Invoice', intPurchaseInvoiceId);
        }
        catch (ex) {
            var stError = (ex.getCode != null) ? ex.getCode() + '\n' + ex.getDetails() + '\n' : ex.toString();
            log.error('Error: reduce()', stError);
        }
    }

    function summarize(summary) {
        // log.debug('summarize()', 'START');
        log.debug('Script Summary','Records Processed: ' + summary.inputSummary.totalRecords );
        try {
            log.debug('END OF M/R');
            summary.reduceSummary.errors.iterator().each(function (key, error) {
    log.error('Reduce Error for key: ' + key, error);
    return true;
});
        }
        catch (ex) {
            var stError = (ex.getCode != null) ? ex.getCode() + '\n' + ex.getDetails() + '\n' : ex.toString();
            log.error('Error: summarize()', stError);
        }
    }

    function getWhTaxTypeTotal(intInvoiceId, intTaxTypeId) {
      //log.debug('TEST 1 intInvoiceId', intInvoiceId);
      //log.debug('TEST 2 intTaxTypeId', intTaxTypeId);
      try {
      //if (intTaxTypeId == '') {
      //  intTaxTypeId = 11
      //}
        var objTransactionSearch = search.create({
            type: search.Type.VENDOR_BILL,
            filters:
                [
                    ['type', 'anyof', 'VendBill'],
                    'AND',
                    ['internalid', 'anyof', intInvoiceId],
                    'AND',
                    ['custcol_tht_wht_taxt_type', 'anyof', intTaxTypeId]
                ],
            columns:
                [
                    search.createColumn({
                        name: 'amount',
                        summary: 'SUM'
                    })
                ]
        });
        var objResults = objTransactionSearch.run().getRange({
            start: 0,
            end: 1
        });

        for (var i in objResults) {
            return parseFloat(objResults[i].getValue({
                name: 'amount',
                summary: 'SUM'
            }));
        }
    } catch (ex) {
                log.error('ERROR', 'getWhTaxTypeTotal failed');
                return false;
            }
    }

    function createPurchaseInvoice(intRecordId) {
        try {
            var objRecord = record.load({
                type: record.Type.VENDOR_BILL,
                id: intRecordId
            });

            // Get header level fields
            var intAccountId = objRecord.getValue('account');
            var flExchangeRate = objRecord.getValue('exchangerate');
            var dtDate = objRecord.getValue('trandate');
            var intPostingPeriod = objRecord.getValue('postingperiod');
            var intLocationId = objRecord.getValue('location');
            var intOriginalSupplierId = objRecord.getValue('entity');
            var OrigMemo = objRecord.getValue('memo')
            var OrigCreator = objRecord.getValue('custbody_creator')

            // Supplier lookup
            var objSupplierLookup = search.lookupFields({
                type: search.Type.LOCATION,
                id: intLocationId,
                columns: ['custrecord_tht_wht_tax_agency'],
            });
            var intSupplierId;
            try {
                intSupplierId = objSupplierLookup.custrecord_tht_wht_tax_agency[0].value;
            } catch (ex) {
                log.error('ERROR', 'Supplier does not exist for location ' + intLocationId + '.');
                return false;
            }
            var NewSupplierId;
            try {
                NewSupplierId = objSupplierLookup.custrecord_tht_wht_tax_agency[0].value;
            } catch (ex) {
                log.error('ERROR', 'Supplier does not exist for location ' + intLocationId + '.');
                return false;
            }
            // Supplier frequency lookup
            var objSupplierLookup = search.lookupFields({
                type: search.Type.VENDOR,
                id: intOriginalSupplierId,
                columns: ['custentity_wht_frequent_supplier'],
            });
            var bIsFrequentSupplier = objSupplierLookup.custentity_wht_frequent_supplier;
            // var bIsProcessed = objRecord.getValue('custbody_tht_wht_is_processed');
            // log.debug('bIsFrequentSupplier', bIsFrequentSupplier);

            var flOriginalTotal = 0;
            var flWhTaxAmount = 0;
            var arrOrigItems = [];
            var arrTaxItems = [];
            var arrOrigExpenses = [];
            var arrTaxExpenses = [];

            var intItemCount = objRecord.getLineCount({
                sublistId: 'item'
            });
            var intExpenseLineCount = objRecord.getLineCount({
                sublistId: 'expense'
            });
            log.debug('intItemCount', intItemCount);
            log.debug('intExpenseLineCount', intExpenseLineCount);

            // Access expense sublist --------------------------------------------------------------------------------------------------------------------------------
            if (intExpenseLineCount > 0) {
                for (var k = 0; k < intExpenseLineCount; k++) {
                    // Sublist data
                    var intTaxType = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_wht_taxt_type',
                        line: k
                    });
                  //log.debug('intTaxType TEST 3', intTaxType);
                    var flBaseAmount = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_wht_base_amt',
                        line: k
                    });
                    var flAmount = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'amount',
                        line: k
                    });
                    var flAmountSameWh = getWhTaxTypeTotal(intRecordId, intTaxType);
//                    log.debug('XXX flAmountSameWh', flAmountSameWh);

                    var intLineAccountId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'account',
                        line: k
                    });
                    var intLocalGLId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_localgl',
                        line: k
                    });
                    var EnglishMemo = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_englishmemo',
                        line: k
                    });
                   var pv = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_pvno',
                        line: k
                    });
                   var Memo = objRecord.getSublistText({
                        sublistId: 'expense',
                        fieldId: 'description',
                        line: k
                    });
                  log.debug('description', Memo);
                    var intCostCenterId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_project',
                        line: k
                    });
                    var intContractId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_parentproject',
                        line: k
                    });
Copy code
var intContractNameId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'customer',
                        line: k
                    });
                    var intLineLocationId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'location',
                        line: k
                    });
                    var intLineGlLocationId = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_gllocation',
                        line: k
                    });
                    var intLineTransDate = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_pvtransactiondate',
                        line: k
                    });
                    var lnTaxCode = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'taxcode',
                        line: k
                    });
                    var lnTaxAmt = objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'taxamount',
                        line: k
                    });
                    var flWhPercentage = (objRecord.getSublistValue({
                        sublistId: 'expense',
                        fieldId: 'custcol_tht_wht_percentage',
                        line: k
                    })) / 100;

log.debug('tax code', lnTaxCode);
log.debug('tax amt', lnTaxAmt);                  
                  
                    var flNewAmount = Number(Math.round(flAmount - (flAmount * flWhPercentage)));
                    var flTaxAmount = Number(Math.round(flAmount * flWhPercentage));
                    flOriginalTotal = flOriginalTotal + flAmount;
Copy code
var fxrate = objRecord.getValue({fieldId: 'exchangerate'});
//log.debug('fxrate', fxrate);
//log.debug('intTaxType TEST 4', intTaxType);
//log.debug('bIsFrequentSupplier', bIsFrequentSupplier);
//log.debug('flBaseAmount', flBaseAmount);
//log.debug('flAmountSameWh', flAmountSameWh);
                //    if (!isEmpty(intTaxType) && ((bIsFrequentSupplier == true) || ((bIsFrequentSupplier == false) && (flBaseAmount  <= flAmountSameWh)))) {
                  	if (!isEmpty(intTaxType) && ((bIsFrequentSupplier == true) || ((bIsFrequentSupplier == false) && (flBaseAmount  <= (flAmountSameWh/fxrate))))) {
                        var objOrigExpense = {
                          custcol_tht_wht_taxt_type: intTaxType,
                            line: k,
                            account: intLineAccountId,
                          custcol_localgl: intLocalGLId,
                            amount: flNewAmount,
                            custcol_tht_total_amt: flAmount,
                            custcol_tht_wh_amt: flTaxAmount
                        };
//                      	log.debug('objOrigExpense', objOrigExpense);
//                        log.debug('intLocalGLId', intLocalGLId);
                        var objTaxExpense = {
                            account: intLineAccountId,
                            custcol_localgl: intLocalGLId,
                            description: Memo,
                            custcol_pvno: pv,
                            custcol_englishmemo: EnglishMemo,
                            amount: flTaxAmount,
                            rate: flTaxAmount,
                            custcol_tht_project: intCostCenterId,
                            custcol_tht_parentproject: intContractId,
                            customer: intContractNameId,
                            location: intLineLocationId,
                            custcol_tht_gllocation: intLineGlLocationId,
                            custcol_pvtransactiondate: intLineTransDate
                        };
                        flWhTaxAmount = flWhTaxAmount + flTaxAmount;
                        arrOrigExpenses.push(objOrigExpense);
                        arrTaxExpenses.push(objTaxExpense)
                    }
                }
                log.debug('arrOrigExpenses', arrOrigExpenses);
                log.debug('arrTaxExpenses', arrTaxExpenses);
            }


            // Access item sublist
            if (intItemCount > 0) {
                for (var i = 0; i < intItemCount; i++) {
                    // Sublist data
                    var intTaxType = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_tht_wht_taxt_type',
                        line: i
                    });

                    var flBaseAmount = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_tht_wht_base_amt',
                        line: i
                    });
                    var flAmount = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        line: i
                    });
                    var flAmountSameWh = getWhTaxTypeTotal(intRecordId, intTaxType);

                    var intItemId = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        line: i
                    });
                    var intContractId = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'customer',
                        line: i
                    });
                    var flWhPercentage = (objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_tht_wht_percentage',
                        line: i
                    })) / 100;
                    var intLineLocationId = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'location',
                        line: i
                    });
                    var intLineTransDate = objRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_pvtransactiondate',
                        line: i
                    });
                    var flNewAmount = flAmount - (flAmount * flWhPercentage);
                    var flTaxAmount = flAmount * flWhPercentage;

                    flOriginalTotal = flOriginalTotal + flAmount;
                    if (!isEmpty(intTaxType) && ((bIsFrequentSupplier == true) || ((bIsFrequentSupplier == false) && (flBaseAmount  <= flAmountSameWh)))) {
                        var objOrigItem = {
                            line: i,
                            item: intItemId,
                            amount: flNewAmount,
                            rate: flNewAmount,
                            location: intLineLocationId,
                            custcol_tht_wht_taxt_type: intTaxType,
                            custcol_tht_total_amt: flAmount,
                            custcol_tht_wh_amt: flTaxAmount
                        };
                        var objTaxItem = {
                            item: intItemId,
                            location: intLineLocationId,
                            amount: flTaxAmount,
                            rate: flTaxAmount,
                            customer: intContractId,
                            custcol_pvtransactiondate: intLineTransDate
                        };
                        flWhTaxAmount = flWhTaxAmount + flTaxAmount;
                        arrOrigItems.push(objOrigItem);
                        arrTaxItems.push(objTaxItem);
                    }
                }
                log.debug('arrOrigItems', arrOrigItems);
                log.debug('arrTaxItems', arrTaxItems);
            }

            // ************************************************************************************************************************************************************* //
            // Create purchase invoice if criteria is met
            if (arrOrigItems.length > 0 || arrOrigExpenses.length > 0) {
                var objWhInvoice = record.create({
                    type: record.Type.VENDOR_BILL
                });
                objWhInvoice.setValue({
                    fieldId: 'customform',
                    value: '156'				// needs to be ID of HALO Colombia Vendor Bill
                });
                objWhInvoice.setValue({
                    fieldId: 'entity',
                    value: intSupplierId
                });

                objWhInvoice.setValue({
                    fieldId: 'custbody_localsupplier',
                    value: intSupplierId
                });

                objWhInvoice.setValue({
                    fieldId: 'account',
                    value: intAccountId
                });
                objWhInvoice.setValue({
                    fieldId: 'memo',
                    value: 'WHT : ' + OrigMemo
                });
                objWhInvoice.setValue({
                    fieldId: 'exchangerate',
                    value: flExchangeRate
                });
                objWhInvoice.setValue({
                    fieldId: 'trandate',
                    value: dtDate
                });

                objWhInvoice.setValue({
                    fieldId: 'postingperiod',
                    value: intPostingPeriod
                });
                objWhInvoice.setValue({
                    fieldId: 'location',
                    value: intLocationId
                });
                objWhInvoice.setValue({
                    fieldId: 'custbody_tht_wh_tax_inv',
                    value: intRecordId
                });

                if (arrOrigItems.length > 0) {
                    for (var j = 0; j < arrOrigItems.length; j++) {
                        var objTaxFields = arrTaxItems[j];
                        for (var field in objTaxFields) {
                            objWhInvoice.setSublistValue({
                                sublistId: 'item',
                                fieldId: field,
                                value: objTaxFields[field],
                                line: j
                            });
                        }
                    }
                }
Copy code
if (arrOrigExpenses.length > 0) {
                    for (var m = 0; m < arrOrigExpenses.length; m++) {
                        var objTaxFields = arrTaxExpenses[m];
                        for (var field in objTaxFields) {
                            objWhInvoice.setSublistValue({
                                sublistId: 'expense',
                                fieldId: field,
                                value: objTaxFields[field],
                                line: m
                            });
                        }
                    }
                }

//               objWhInvoice.setValue({fieldId: 'custbody_creator', value: OrigCreator});
//               objWhInvoice.setValue({fieldId: 'approvalstatus', value: '2'});        
               var intWhInvoiceId = objWhInvoice.save({
                    ignoreMandatoryFields: true,
                    enableSourcing: true
                });
              log.audit('Internal ID of New Transaction', intWhInvoiceId);
                var objInvoiceLookup = search.lookupFields({
                    type: search.Type.VENDOR_BILL,
                    id: intWhInvoiceId,
                    columns: ['transactionnumber']
                });
                var stWhInvoiceTranId = objInvoiceLookup.transactionnumber;
log.debug('NEW CREATED TRANSACTION', stWhInvoiceTranId);              
/*                record.submitFields({
                    type: record.Type.VENDOR_BILL,
                    id: intWhInvoiceId,
                    values: {
                        tranid: stWhInvoiceTranId,
                      	custbody_localsupplier: intSupplierId
                    }
                });
                
                var objUpdateApproval = record.load({type: record.Type.VENDOR_BILL,id: intWhInvoiceId})
                objUpdateApproval.setValue({fieldId: 'approvalstatus', value: '2'});  
                var objUpdateApprovalId = objUpdateApproval.save({ignoreMandatoryFields: true,enableSourcing: true});
*/
              // update original invoice...
              log.debug('Update','ORIGINAL - START')
                var objOrigInvoice = record.load({
                    type: record.Type.VENDOR_BILL,
                    id: intRecordId
                })

                objOrigInvoice.setValue({
                    fieldId: 'custbody_tht_wh_tax_inv',
                    value: intWhInvoiceId
                });
              log.debug('intWhInvoiceId - WH Tax Invoice',intWhInvoiceId)
/*****
                objOrigInvoice.setValue({
                    fieldId: 'custbody_whtid',
                    value: intWhInvoiceId
                });
              log.debug('custbody_whtid - WH Tax Invoice ZZZZ',intWhInvoiceId)
*/
              
                objOrigInvoice.setValue({
                    fieldId: 'custbody_tht_orig_total_before_wh',
                    value: flOriginalTotal
                });
                objOrigInvoice.setValue({
                    fieldId: 'custbody_tht_wh_tax_amt',
                    value: flWhTaxAmount
                });

                // objOrigInvoice.setValue({
                //     fieldId: 'tranid',
                //     value: stTranId
                // });

                for (var a = 0; a < arrOrigItems.length; a++) {
                    var objOrigFields = arrOrigItems[a];
                    log.debug('objOrigFields', JSON.stringify(objOrigFields));
                    for (var field in objOrigFields) {
                        if (field != 'line') {
                            objOrigInvoice.setSublistValue({
                                sublistId: 'item',
                                fieldId: field,
                                value: objOrigFields[field],
                                line: objOrigFields['line']
                            });
                        }
                    }
                }
Copy code
for (var b = 0; b < arrOrigExpenses.length; b++) {
                    var skipline = 'N';
                  log.debug('skipline START',skipline)
                    var objOrigFields = arrOrigExpenses[b];
                    log.debug('objOrigFields', JSON.stringify(objOrigFields));
                    for (var field in objOrigFields) {
                      if (field == 'custcol_tht_wht_taxt_type'){
                        if (objOrigFields[field] == '14'){
                        	var skipline = "Y"
                            log.debug('skipline ADJUST',skipline)
                        }
                      }
					if (skipline == "Y") {
                        if (field == 'custcol_tht_total_amt') {
                            objOrigInvoice.setSublistValue({
                                sublistId: 'expense',
                                fieldId: field,
                                value: objOrigFields[field] + objOrigFields['custcol_tht_wh_amt'],
                                line: objOrigFields['line']
                            });
                        }
                        if (field == 'custcol_tht_wh_amt') {
                            objOrigInvoice.setSublistValue({
                                sublistId: 'expense',
                                fieldId: field,
                                value: objOrigFields[field],
                                line: objOrigFields['line']
                            });
                        }
                    }
                    if (skipline == "N") {
                        if (field != 'line') {
                            objOrigInvoice.setSublistValue({
                                sublistId: 'expense',
                                fieldId: field,
                                value: objOrigFields[field],
                                line: objOrigFields['line']
                            });
                        }
                    }
                    }
                }

                var intOrigInvoiceId = objOrigInvoice.save({
                    ignoreMandatoryFields: true,
                    enableSourcing: true
                });
                log.debug('SAVED ORIGINAL INVOICE :', intOrigInvoiceId);

                /////
/*
                var objOrigInvoiceX = record.load({
                    type: record.Type.VENDOR_BILL,
                    id: intRecordId
                })

                objOrigInvoiceX.setValue({
                    fieldId: 'custbody_tht_wh_tax_inv',
                    value: intWhInvoiceId
                });

                var intOrigInvoiceIdX = objOrigInvoiceX.save({
                    ignoreMandatoryFields: true,
                    enableSourcing: true
                });
*/                
                /////
                return intWhInvoiceId;
            } else {
                // record.submitFields({
                //     type: record.Type.VENDOR_BILL,
                //     id: intRecordId,
                //     values: {
                //         custbody_tht_wht_is_processed: true
                //     }
                // });
                return false;
            }
        } catch (ex) {
            log.error('Error on update: ' + intRecordId, ex);
        }

    }

    function isEmpty(value) {
        return ((value === '' || value == null || value == undefined) ||
            (value.constructor === Array && value.length == 0) ||
            (value.constructor === Object && (function(v) { for (var k in v) return 'F'; return true; })(value)));
    }

    function loadSearch(stRecordType, stSearchId, arrSearchFilter, arrSearchColumn) {
        if (stRecordType == null && stSearchId == null)
        {
            error.create(
                {
                    name: 'SSS_MISSING_REQD_ARGUMENT',
                    message: 'search: Missing a required argument. Either stRecordType or stSearchId should be provided.',
                    notifyOff: 'F'
                });
        }

        var arrReturnSearchResults = new Array();
        var objSavedSearch;

        var maxResults = 1000;

        if (stSearchId != null)
        {
            objSavedSearch = search.load({
                id: stSearchId
            });

            // add search filter if one is passed
            if (arrSearchFilter != null) {
                if (arrSearchFilter[0] instanceof Array || (typeof arrSearchFilter[0] == 'string')) {
                    var arrConsFilterSearch = [];
                    arrConsFilterSearch.push(objSavedSearch.filterExpression);
                    arrConsFilterSearch = arrConsFilterSearch.concat(arrSearchFilter);

                    // objSavedSearch.filterExpression = objSavedSearch.filterExpression.concat(arrSearchFilter);
                    objSavedSearch.filterExpression = arrConsFilterSearch;
                }
                else {
                    objSavedSearch.filters = objSavedSearch.filters.concat(arrSearchFilter);
                }
            }

            // add search column if one is passed
            if (arrSearchColumn != null) {
                objSavedSearch.columns = objSavedSearch.columns.concat(arrSearchColumn);
            }
        }
        else {
            objSavedSearch = search.create(
                {
                    type: stRecordType
                });

            // add search filter if one is passed
            if (arrSearchFilter != null) {
                if (arrSearchFilter[0] instanceof Array || (typeof arrSearchFilter[0] == 'string')) {
                    objSavedSearch.filterExpression = arrSearchFilter;
                }
                else {
                    objSavedSearch.filters = arrSearchFilter;
                }
            }

            // add search column if one is passed
            if (arrSearchColumn != null) {
                objSavedSearch.columns = arrSearchColumn;
            }
        }

        var objResultset = objSavedSearch.run();
        var intSearchIndex = 0;
        var arrResultSlice = null;
        do {
            arrResultSlice = objResultset.getRange(intSearchIndex, intSearchIndex + maxResults);
            if (arrResultSlice == null) {
                break;
            }

            arrReturnSearchResults = arrReturnSearchResults.concat(arrResultSlice);
            intSearchIndex = arrReturnSearchResults.length;
        }
        while (arrResultSlice.length >= maxResults);

        return arrReturnSearchResults;
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    }
});
I think that's it all... I had to split to send it.
b
properly Log Errors for all the summaries
💯 1
Make sure that you properly Set Script Execution Log Levels
id personally remove all the try-catches you have, they are the useless kind only designed to hide errors
b
UPDATE: Solution has been found. There was actually nothing wrong with this script, but there was another script that was deleting VENDOR BILLS based after an edit of another VENDOR BILL and so these were then deleted within seconds of this scrip running. The other script is currently disabled whilst I work out what logic it really should follow. Thanks all for your advice and help.
✅ 1