Vendor payments using portfolio method

Jira code: MBS-4

To complete the vendor payment using the cheques and drafts using the portfolio method. The customer also can make the payments to its Vendors using DRAFTS that are taken as payment cannot be used in Vendor payments. CHEQUEs that are taken as payment can be used in Vendor payments. Also, Customer can create its own CHEQUEs/DRAFTs to make a payment to its Vendors. Whether the company is writing its own CHEQUEs/DRAFTs or use Customer CHEQUEs it should close the Vendor bills by selecting or auto applying. Similarly, the company should make the payment to the Vendor in bulk whether the number of CHEQUEs/DRAFTs is 1 or n.

Suitelet script

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * Moneta Business Solutions
 * MBS-4 | Vendor Payment
 * **************************************************************************
 * Date : ${date}
 * 
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : This generates a Form for Vendor Payment
 * Date Created : 14-Jan-2019
 *
 * REVISION HISTORY
 * 
 * 
 ******************************************************************************/
define(['N/https', 'N/record', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/file', 'N/url', 'N/log'],
    function (https, record, runtime, search, serverWidget, file, url, log) {
        //To check whether a value exists in parameter
        function checkForParameter(parameter, parameterName) {
            if (parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== "false" && parameter != "" && parameter != " ") {
                return true;
            } else {
                if (parameterName)
                    log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                return false;
            }
        }

        //To assign a default value if the it is empty
        function assignDefaultValue(value, defaultValue) {
            if (checkForParameter(value))
                return value;
            else
                return defaultValue;
        }

        //To reject predefined set of values
        function rejectThisValues(value) {
            var rejectObj = {
                null: true,
                undefined: true,
                NaN: true,
                0: true,
                false: true,
                '': true
            };
            return rejectObj[value] ? false : true;
        }

        //Common Try-Catch function
        function tryCatch(myfunction, key) {
            return function () {
                try {
                    return myfunction.apply(this, arguments);
                } catch (e) {
                    log.error("error in  main." + key, e);
                    // log.error("error in  main." + key, e);
                    return false;
                }
            };
        }

        //Apply Styles 
        var formatText = {
            allignContent: function (value, alignValue, noValue) {
                alignValue = assignDefaultValue(alignValue, 'center');
                noValue = assignDefaultValue(noValue, '-');
                return '<p align="' + alignValue + '">' + assignDefaultValue(value, noValue) + '</p>';
            },
            applyStyle: function (param) {
                var str = '<span style="';
                if (param.FONT_WEIGHT)
                    str += 'font-weight:' + param.FONT_WEIGHT + ';';
                if (param.FONT_COLOR)
                    str += 'color:' + param.FONT_COLOR + ';';
                if (param.FONT_SIZE)
                    str += 'font-size:' + param.FONT_SIZE + ';';
                if (param.FONT_STYLE)
                    str += 'font-style:' + param.FONT_STYLE + ';';
                if (param.FONT_FAMILY)
                    str += 'font-family:' + param.FONT_FAMILY + ';';
                str += '"> ' + param.value + ' </span>';
                return str;
            }
        };
        for (var key in formatText) {
            if (typeof formatText[key] === 'function') {
                formatText[key] = tryCatch(formatText[key], 'formatText.' + key);
            }
        }


        var main = {
            formatSavedSearch: function (savedSearchObj, pageIndexField, pageIndex) {
                //To format search result
                //Creating Column Names
                var columns = savedSearchObj.columns;
                var columnsData = {};
                columns.forEach(function (result, counter) {
                    // columnsData['custpage_col_' + counter] = result;
                    columnsData[(columnsData[result.name]) ? (result.name + '_' + counter) : (result.name)] = result;
                });
                //Paginating Results
                var searchPageRanges;
                try {
                    searchPageRanges = savedSearchObj.runPaged({
                        pageSize: 10
                    });
                } catch (err) {
                    return {
                        status: true,
                        columns: columnsData,
                        result: []
                    };
                }
                
                
                if (searchPageRanges.pageRanges.length < 1)
                    return {
                        status: true,
                        columns: columnsData,
                        result: []
                    };

                for (var i = 0, j = searchPageRanges.pageRanges.length; i < j; i++) {
                    pageIndexField.addSelectOption({
                        value: i,
                        text: i + 1 + ' of ' + j + ' Pages'
                    });
                }
                //Fetching Row Data
                var rowData = [];
                searchPageRanges.fetch({
                    index: pageIndex
                }).data.forEach(function (result) {
                    rowData.push(result);
                });

                return {
                    status: true,
                    columns: columnsData,
                    result: rowData
                };
            },
            chequeDraftSearch: function (pageIndexField, pageIndex, currencySelected) {
                //To search Custom record customrecord_jj_checkordraft
                var filterArray = [
                    ["isinactive", "is", "F"],
                    "AND",
                   ["custrecord_jj_check_amount", "greaterthan", "0.00"],
                   "AND",
                    ["custrecord_jj_check_type", "anyof", "1"], //Type	is Cheque
                    "AND",
                    ["custrecord_jj_check_status", "anyof", "1"], //Status of Check	is any of 'In the Portfolio'
                ]
                if (checkForParameter(currencySelected))
                    filterArray.push("AND", ["custrecord_jj_check_currency", "anyof", currencySelected]);
               
                var customrecord_jj_checkordraftSearchObj = search.create({
                    type: "customrecord_jj_checkordraft",
                    filters: filterArray,
                    columns: [
                        
                        search.createColumn({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_type",
                            label: "Type"
                        }),
                        search.createColumn({
                            name: "name",
                            label: "Name"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_bankall",
                            label: "Bank All"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_branch",
                            label: "Branch"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_checknumber",
                            label: "Cheque Number"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_currency",
                            label: "Currency"
                        }),
                     // AJ MODIFIED
                        search.createColumn({
                            name: "custrecord_jj_balance_amt",
                            label: "Remaining Amount in Cheque"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_amount",
                            label: "Amount"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_due_date",
                            label: "Due Date"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_placeofcheck",
                            label: "Place of Cheque"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_isownerdifferent",
                            label: "Is the owner different"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_originalowner",
                            label: "Orginal Check Owner"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_owner",
                            label: "Owner"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_parentportfolio",
                            label: "Parent record(Portfolio)"
                        }),
                        search.createColumn({
                            name: "name",
                            join: "CUSTRECORD_JJ_CHECK_PARENTPORTFOLIO",
                            label: "Name"
                        }),
                       
                        search.createColumn({
                            name: "custrecord_jj_check_status",
                            label: "Status of Check"
                        }),
                        search.createColumn({
                            name: "custrecord_jj_check_vendorbill",
                            label: "Vendor Bill"
                        })
                    ]
                });
                var searchResultCount = customrecord_jj_checkordraftSearchObj.runPaged().count;
                return main.formatSavedSearch(customrecord_jj_checkordraftSearchObj, pageIndexField, pageIndex);
            },
            vendorBillSearch: function (CURRENCY, VENDOR) {
                //To search Vendor Bill
                var responseArray = [];
                var filterArray = [
                    ["type", "anyof", "VendBill"], //Type	is Bill
                    "AND",
                    ["status", "anyof", "VendBill:A"], //Status	is Bill:Open
                    "AND",
                    ["mainline", "is", "T"], //Main Line	is true
                    "AND",
                    ["number", "isnotempty", ""], //Document Number	is not empty
                    "AND",
                    ["numbertext", "isnotempty", ""] //Document Number/ID	is not empty
                ]
                if (checkForParameter(CURRENCY))
                    filterArray.push("AND", ["currency", "anyof", CURRENCY]);
                if (checkForParameter(VENDOR))
                    filterArray.push("AND", ["name", "anyof", VENDOR]);

                var vendorbillSearchObj = search.create({
                    type: "vendorbill",
                    filters: filterArray,
                    columns: [
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.DESC,
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "tranid",
                            label: "Document Number"
                        }),
                        search.createColumn({
                            name: "entity",
                            label: "Name"
                        }),
                        search.createColumn({
                            name: "amount",
                            label: "Amount"
                        }),
                        search.createColumn({
                            name: "creditamount",
                            label: "Amount (Credit)"
                        }),
                        search.createColumn({
                            name: "debitamount",
                            label: "Amount (Debit)"
                        })
                    ]
                }).run().each(function (result) {
                    responseArray.push({
                        value: result.getValue({
                            name: "internalid",
                            label: "Internal ID"
                        }),
                        text: result.getValue({
                            name: "tranid",
                            label: "Document Number"
                        })
                    });
                   
                    return true;
                });
                return responseArray;
            },
            generateForm: function (context) {
                //To Initialize form
                
                var pageIndex = assignDefaultValue(context.request.parameters.pageindexfield, 0);
                var currencySelected = context.request.parameters.currencyfield;
                var vendorSelected = context.request.parameters.vendorfield;
                var form = serverWidget.createForm({
                    title: 'Vendor Payment'
                });
                var fieldGroup = form.addFieldGroup({
                    id: '_groupfilter',
                    label: 'Filter Result'
                });
                fieldGroup.isSingleColumn = true;
                form.addButton({
                    id: 'custbtn_displayresult',
                    label: 'Display',
                    functionName: 'displayResult',
                    container: '_groupfilter'
                });
                var currencyField = form.addField({
                    id: 'currencyfield',
                    type: serverWidget.FieldType.SELECT,
                    label: 'Currency',
                    source: 'currency',
                    container: '_groupfilter'
                }).updateLayoutType({
                    layoutType: serverWidget.FieldLayoutType.STARTROW
                });
                currencyField.isMandatory = true;
                if (checkForParameter(currencySelected))
                    currencyField.defaultValue = currencySelected;

                var vendorField = form.addField({
                    id: 'vendorfield',
                    type: serverWidget.FieldType.SELECT,
                    label: 'Vendor',
                    source: 'vendor',
                    container: '_groupfilter'
                }).updateLayoutType({
                    layoutType: serverWidget.FieldLayoutType.ENDROW
                });
                vendorField.isMandatory = false;
                           
                
                if (checkForParameter(vendorSelected))
                    vendorField.defaultValue = vendorSelected;

                var pageIndexField = form.addField({
                    id: 'pageindexfield',
                    type: serverWidget.FieldType.SELECT,
                    container: '_groupfilter',
                    label: 'Page Index'
                }).updateLayoutType({
                    layoutType: serverWidget.FieldLayoutType.STARTROW
                });
                pageIndexField.defaultValue = pageIndex;
                var runSearchObj = main.chequeDraftSearch(pageIndexField, pageIndex, currencySelected);
                if (checkForParameter(runSearchObj)) {
                    if (checkForParameter(runSearchObj.status)) {
                        //Trigger Vendor Payment
                        if (checkForParameter(currencySelected))
                            form.addButton({
                                id: 'custbtn_create_payment',
                                label: 'Create Payment',
                                functionName: 'initiatePayment'
                            });
                        var checkSublist = form.addSublist({
                            id: 'custpage_checksublist',
                            type: serverWidget.SublistType.LIST,
                            label: 'Check List'
                        });
                     
                        
                        if (checkForParameter(currencySelected)) {
                            //To show Vendor Bill as Select Field
                            var vendorBillListField = checkSublist.addField({
                                id: 'custpage_col_vendorbillselect',
                                type: serverWidget.FieldType.SELECT,
                                label: 'Vendor Bill'
                            });
                            vendorBillListField.addSelectOption({
                                value: "null",
                                text: "- NONE -"
                            });
                            var amntField = checkSublist.addField({
                                id: 'custpage_cheque_amount',
                                type: serverWidget.FieldType.CURRENCY,
                                label: 'Amount'
                                });
                           
                            amntField.updateDisplayType({
                             	 displayType: serverWidget.FieldDisplayType.ENTRY
                              });

                            //AJ 
                            var amntVendor = checkSublist.addField({
                                id: 'custpage_vendor_amount',
                                type: serverWidget.FieldType.CURRENCY,
                                label: 'Bill Due Amount'
                                });
                            amntVendor.updateDisplayType({
                            	 displayType: serverWidget.FieldDisplayType.ENTRY
                             });
                            vendorBillList = main.vendorBillSearch(currencySelected, vendorSelected);
                            vendorBillList.forEach(function (billObj) {
                                vendorBillListField.addSelectOption({
                                    value: billObj.value,
                                    text: billObj.text
                                });
                            });
                            vendorBillListField.defaultValue = "null";
                        }
                        //dynamically define the column list based on the saved search definition 
                        var columns = runSearchObj.columns;
                       
                        for (var key in columns) {
                            if (columns[key].label != 'nodisplay') {
                                checkSublist.addField({
                                    id: key,
                                    label: columns[key].label,
                                    type: serverWidget.FieldType.TEXT
                                });
                            }
                        }

                        var fieldValue;
                        
                        runSearchObj.result.forEach(function (eachRow, index) {
                            for (var key in columns) {
                                if (columns[key].label != 'nodisplay') {
                                    fieldValue = (eachRow.getText(columns[key])) ? eachRow.getText(columns[key]) : eachRow.getValue(columns[key]);
                                    checkSublist.setSublistValue({
                                        id: key,
                                        value: assignDefaultValue(fieldValue, " - "),
                                        line: index
                                    });
                                }
                            }
                        });
                    }
                }

                form.clientScriptFileId = 4406;
                return form;
            },
            onRequest: function (context) {
                if (context.request.method === 'GET') {
                    context.response.writePage(main.generateForm(context));
                }
            }
        };

        for (var key in main) {
            if (typeof main[key] === 'function') {
                main[key] = tryCatch(main[key], key);
            }
        }


        return main;

    });

//Polyfill for Object.assign()
//refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
if (typeof Object.assign != 'function') {
    // Must be writable: true, enumerable: false, configurable: true
    Object.defineProperty(Object, "assign", {
        value: function assign(target, varArgs) { // .length of function is 2
            'use strict';
            if (target == null) { // TypeError if undefined or null
                throw new TypeError('Cannot convert undefined or null to object');
            }
            var to = Object(target);
            for (var index = 1; index < arguments.length; index++) {
                var nextSource = arguments[index];
                if (nextSource != null) { // Skip over if undefined or null
                    for (var nextKey in nextSource) {
                        // Avoid bugs when hasOwnProperty is shadowed
                        if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                            to[nextKey] = nextSource[nextKey];
                        }
                    }
                }
            }
            return to;
        },
        writable: true,
        configurable: true
    });
}

Client script

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * Moneta Business Solutions
 * MBS-4 | Vendor Payment
 * **************************************************************************
 * Date : ${date}
 * 
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : This handles the client side functions for the Vendor Payment Form
 * Date Created : 14-Jan-2019
 *
 * REVISION HISTORY
 * Revision 1.0 ${08/01/2019} manu : created
 * Revision 1.1 ${18/01/2019} aj : modified
 * 
 ******************************************************************************/
define(['N/https', 'N/currentRecord', 'N/url', 'N/ui/message','N/record','N/search'], 
		function (https, currentRecord, url, message,record,search) {

    //To check whether a value exists in parameter
    function checkForParameter(parameter, parameterName) {
        if (parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== "false" && parameter != "" && parameter != " ") {
            return true;
        } else {
            if (parameterName)
                console.log('Empty Value found for parameter' + parameterName);
            return false;
        }
    }

    //To assign a default value if the it is empty
    function assignDefaultValue(value, defaultValue) {
        if (checkForParameter(value))
            return value;
        else
            return defaultValue;
    }

    // for getting parameter by name .................
    function getParameterByName(name, url) {
        if (!url)
            url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex
            .exec(url);
        if (!results)
            return null;
        if (!results[2])
            return ' ';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    var main = {
        checkForParameter: checkForParameter,
        assignDefaultValue: assignDefaultValue,
        getParameterByName: getParameterByName,
        loadLibrary: function (url, type, isAsync) {
            if (checkForParameter(url) && checkForParameter(type)) {
                isAsync = (isAsync) ? true : false;
                var head, script;
                if (type == 'js') {
                    head = document.getElementsByTagName('head')[0] || document.documentElement;
                    script = document.createElement("script");
                    script.src = url;
                    script.type = "text/javascript";
                    script.async = isAsync;
                    head.appendChild(script);
                } else if (type == 'css') {
                    head = document.getElementsByTagName('head')[0] || document.documentElement;
                    script = document.createElement("link");
                    script.href = url;
                    script.rel = "stylesheet";
                    script.async = isAsync;
                    head.appendChild(script);
                }
            }
        },
        pageInit: function (scriptContext) {
            if (window.onbeforeunload) {
                window.onbeforeunload = function () {};
            }
            var scriptUrl = {
                'BootstrapCSS': {
                    type: 'css',
                    url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
                },
                'jQueryJS': {
                    type: 'js',
                    url: 'https://code.jquery.com/jquery-3.3.1.min.js'
                },
                'BootstrapJS': {
                    type: 'js',
                    url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'
                },
                'jQueryConfirmCSS': {
                    type: 'css',
                    url: 'https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css'
                },
                'jQueryConfirmJS': {
                    type: 'js',
                    url: 'https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js'
                }
            };
            var waitTill;
            for (var key in scriptUrl) {
                try {
                    waitTill = main.loadLibrary(scriptUrl[key].url, scriptUrl[key].type, false);
                } catch (errr) {
                    console.error(errr);
                    continue;
                }
            }
        },
        initiatePayment: function () {
        	
            var currRec = currentRecord.get();
            var customerSublistLines = currRec.getLineCount({
                sublistId: "custpage_checksublist"
            });
           
            if (customerSublistLines > 0) {
                var mappedBillArray = [];
                var selectedBill;
                for (var index = 0; index < customerSublistLines; index++) {
                    selectedBill = currRec.getSublistValue({
                        sublistId: 'custpage_checksublist',
                        fieldId: 'custpage_col_vendorbillselect',
                        line: index
                    });
                   
                    if (checkForParameter(selectedBill)) {
                        mappedBillArray.push({
                            vendorBill: selectedBill,
                            checkID: currRec.getSublistValue({
                                sublistId: 'custpage_checksublist',
                                fieldId: 'internalid',
                                line: index
                            }),
                            balanceAmount:currRec.getSublistValue({
                                sublistId: 'custpage_checksublist',
                                fieldId: 'custpage_cheque_amount',
                                line: index
                            }),
                            totalAmount:currRec.getSublistValue({
                                sublistId: 'custpage_checksublist',
                                fieldId: 'custrecord_jj_check_amount',
                                line: index
                            }),
                            Bill:currRec.getSublistText({
                                sublistId: 'custpage_checksublist',
                                fieldId: 'custpage_col_vendorbillselect',
                                line: index
                            }),
                        });
                    }
                    
                }

                console.table(mappedBillArray);
                if (mappedBillArray.length > 0) {
                	for(var i=0;i<mappedBillArray.length;i++)
                		{
                		try
                		{
                			
                		//AJ MODIFIED
                		// to transform to Vendor payment
                		var payment= record.transform({
                    		fromType:record.Type.VENDOR_BILL,
                    		fromId: mappedBillArray[i]['vendorBill'],
                    		toType:record.Type.VENDOR_PAYMENT,
                    		isDynamic:true
                    		
                    	});
                		// to get the lineNum of apply sublist
                		var numLines = payment.getLineCount({
                		    sublistId: 'apply'
                		});
                		
                		if(numLines>0)
                			{

                			for(var j=0;j<numLines;j++)
                				{
                				// to get the Cheque id'
                				var chequeInPayment = payment.getSublistValue({
                                    sublistId: 'apply',
                                       fieldId: 'refnum',
                                       line:j
                                       
                               });
                				
                				// to set Cheque ID in Payment record
                        		payment.setValue({
                        			fieldId:'custbody_mbs4_cheque_id',
                        			value:mappedBillArray[i]['checkID'] //vendorBill
                        		});
                				console.log("chequeInPayment="+chequeInPayment+"vendorBill="+mappedBillArray[i]['Bill'])
                				if(chequeInPayment==mappedBillArray[i]['Bill'])
                					{
                				
                        		
                        		var lineNum = payment.selectLine({
                        		    sublistId: 'apply',
                        		    line: j
                        		});
                        		payment.setCurrentSublistValue({
                                    sublistId: 'apply',
                                       fieldId: 'apply',
                                       value: true,
                                       ignoreFieldChange:false
                                       
                               });
                        		payment.setCurrentSublistValue({
                                    sublistId: 'apply',
                                       fieldId: 'amount',
                                       value:parseFloat(mappedBillArray[i]['balanceAmount']),
                                       ignoreFieldChange:false
                                       
                               });

                        		payment.commitLine({
                        			sublistId:'apply'
                        		});
                        		
                					}
                				else{
                					var lineNum = payment.selectLine({
                            		    sublistId: 'apply',
                            		    line: j
                            		});
                            		payment.setCurrentSublistValue({
                                        sublistId: 'apply',
                                           fieldId: 'apply',
                                           value: false,
                                           ignoreFieldChange:false
                                           
                                   });
                            		payment.commitLine({
                            			sublistId:'apply'
                            		});
                            		
                            	
                				}
                				}
                    		
                			}
                		
                		
                		// to get the amount
                		var paymentAmount =payment.getValue({
                			fieldId:'total'
                		});
                		var recordId = payment.save({
                            enableSourcing: true,
                            ignoreMandatoryFields: true
                        });
                		
                			message.create({
                                title: "Success",
                                message: "Payment record is created successfully",
                                type: message.Type.CONFIRMATION
                            }).show({
                                duration: 3500
                            });
                			 window.location.reload();
                		}catch(e)
                				{
                			console.log(e);
                				message.create({
                                    title: "Failed",
                                    message: "Payment record cannot be created for"+mappedBillArray[i]['checkID']+"<br>"+e.message,
                                    type: message.Type.CONFIRMATION
                                }).show({
                                    duration: 5500
                                });
                				}
                		//to get the balance amt
                		var currentBalance ;
                		
                		// to check if the Status is In portfolio
                		var statusOfCheck = search.lookupFields({
    						type : 'customrecord_jj_checkordraft',
    						id : mappedBillArray[i]['checkID'],
    						columns : [ 'custrecord_jj_check_status','custrecord_jj_balance_amt' ]
    					});

    					var status = statusOfCheck.custrecord_jj_check_status[0].value;
    					
    					currentBalance=statusOfCheck.custrecord_jj_balance_amt;
    					
    					var newBalance =parseFloat(currentBalance)-parseFloat(paymentAmount);
                		
                		var statusNew ;
                			if(newBalance<=0)
                			{
                				statusNew=8;
                			}
                			else
                				statusNew=1;
    					
    					//console.log("statusOfCheck=",status)
    					if(status==1)
    						{
    						//to submit the Vendor payment ID to Cheque custom record
                    		var checkId = record.submitFields({
                    		    type: 'customrecord_jj_checkordraft',
                    		    id:mappedBillArray[i]['checkID'] ,
                    		    values: {
                    		        'custrecord_jj_check_vendorbill': recordId,
                    		        'custrecord_jj_balance_amt':newBalance,
                    		        'custrecord_jj_check_status':statusNew
                    		    },
                    		    options: {
                    		        enableSourcing: false,
                    		        ignoreMandatoryFields : true
                    		    }
                    		});
                    		console.log("checkId=",checkId)
                        	
    						}
                		
                		}
                	

                } else {
                    message.create({
                        title: "No Bill is selected",
                        message: "Please Select at least one Bill",
                        type: message.Type.INFORMATION
                    }).show({
                        duration: 3500
                    });
                }
            }
            
        },
        displayResult: function () {
            var get_url = url.resolveScript({
                scriptId: "customscript_mbs4_jj_sl_vendorpaymentfor",
                deploymentId: "customdeploy_mbs4_jj_sl_vendorpaymentfor",
                returnExternalUrl: false
            });
            var record = currentRecord.get();
            var currencySelected = record.getValue({
                fieldId: 'currencyfield'
            });
          
            if(currencySelected==null||currencySelected==""||currencySelected==" "||currencySelected==' '||currencySelected==undefined||currencySelected=='')
            	{ 
            	  console.log("currencySelected",currencySelected);
            	message.create({
                    title: "No Currency  is selected",
                    message: "Please Select one Currency",
                    type: message.Type.INFORMATION
                }).show({
                    duration: 4500
                });
            	
            	}
            else
            	{
            var vendorSelected = record.getValue({
                fieldId: 'vendorfield'
            });
            var pageIndex = assignDefaultValue(record.getValue({
                fieldId: 'pageindexfield'
            }), 0);
            get_url += '&currencyfield=' + currencySelected + '&vendorfield=' + vendorSelected + '&pageindexfield=' + pageIndex;
            window.location.href = get_url;
            return true;
            	}
        },
        runPromise: function (skipWaitPromise) {
            skipWaitPromise.then(function (scriptContext) {
                return main.displayResult();
            }).catch(function (error) {
                console.log('error ' + error);
            });
        },
        fieldChanged: function (scriptContext) {
            var fieldIdObj = {
                'pageindexfield': 'pageindexfield'
            };
            if (checkForParameter(fieldIdObj[scriptContext.fieldId])) {
                var skipWaitPromise = new Promise(function (resolve, reject) {
                    resolve(scriptContext);
                });
                setTimeout(function () {
                    main.runPromise(skipWaitPromise);
                }, 10);
            }
            return true;
        },
      
    
        fieldChanged: function (scriptContext) {
        	if( scriptContext.sublistId=='custpage_checksublist')
        		{
    	
        		var currentRec = scriptContext.currentRecord;

        		
        		var totalAmount= currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custrecord_jj_balance_amt',
            		line:scriptContext.line
            	});
        		//console.log('totalAmount',totalAmount)
        		
        		var checkID= currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'internalid',
            		line:scriptContext.line
            	});
        		
        	if( scriptContext.fieldId=='custpage_col_vendorbillselect' || scriptContext.fieldId=='custrecord_jj_balance_amt' )
        		{
        		
        		
        		// to get the remaining amt of the selected Bill
        		var billID = currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custpage_col_vendorbillselect',
            		line:scriptContext.line
            	});
                  var balanceAmt;
        		if(billID=='null' || billID==null ||billID==undefined|| billID=="")
                  {
                    balanceAmt =0;
                  }
                  
        		else
                  {
			    var vendorbillSearchObj = search.create({
			   type: "vendorbill",
			   filters:
			   [
			      ["type","anyof","VendBill"], 
			      "AND", 
			      ["internalidnumber","equalto",billID], 
			      "AND", 
			      ["mainline","is","T"]
			   ],
			   columns:
			   [
			      search.createColumn({name: "internalid", label: "Internal ID"}),
			      search.createColumn({name: "fxamount", label: "Amount (Foreign Currency)"}),
			      search.createColumn({name: "fxamountremaining", label: "Amount Remaining (Foreign Currency)"})
			   ]
			});
			var searchResultCount = vendorbillSearchObj.runPaged().count;
			
			if(searchResultCount>0)
				{
				 var searchResult = vendorbillSearchObj.run().getRange({
						start: 0,
						end: 1
					});
	        	 
	        	
	        		 var balanceAmt = searchResult[0].getValue({
	    				 name: "fxamountremaining"
	    				});
				}
			        		
                  }

        		// to set the Amount field
        		
        		currentRec.selectLine({
        			sublistId:'custpage_checksublist',
        			line:scriptContext.line
        		});
        		var chequeAmt =  currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custrecord_jj_balance_amt',
            		line:scriptContext.line
            	});
        		
        		
        		currentRec.setCurrentSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custpage_vendor_amount',
            		value:balanceAmt
            	});
        		
        		if(parseFloat(balanceAmt)>parseFloat(chequeAmt))
        			{
        			currentRec.setCurrentSublistValue({
                		sublistId: 'custpage_checksublist',
                		fieldId: 'custpage_cheque_amount',
                		value:chequeAmt
                	});
        			}
        		else
        			{
        			currentRec.setCurrentSublistValue({
                		sublistId: 'custpage_checksublist',
                		fieldId: 'custpage_cheque_amount',
                		value:balanceAmt
                	});
        			}
        		
        		
        		currentRec.commitLine({
        			sublistId:'custpage_checksublist'
        		});
        		
        		
        		}
        	
        		}
        },
        validateField: function (scriptContext) {
        
        	 if( scriptContext.sublistId=='custpage_checksublist' && scriptContext.fieldId=='custpage_cheque_amount')
        		{
        		 
        			var currentRec = scriptContext.currentRecord;
        			console.log('scriptContext.',scriptContext);
            		
            		var totalAmount= currentRec.getSublistValue({
                		sublistId: 'custpage_checksublist',
                		fieldId: 'custrecord_jj_balance_amt',
                		line:scriptContext.line
                	});
            		console.log('totalAmount',totalAmount)
            
            		
            		var billID = currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custpage_col_vendorbillselect',
            		line:scriptContext.line
            		});
        		
        		
			    var vendorbillSearchObj = search.create({
			   type: "vendorbill",
			   filters:
			   [
			      ["type","anyof","VendBill"], 
			      "AND", 
			      ["internalidnumber","equalto",billID], 
			      "AND", 
			      ["mainline","is","T"]
			   ],
			   columns:
			   [
			      search.createColumn({name: "internalid", label: "Internal ID"}),
			      search.createColumn({name: "fxamount", label: "Amount (Foreign Currency)"}),
			      search.createColumn({name: "fxamountremaining", label: "Amount Remaining (Foreign Currency)"})
			   ]
			});
			var searchResultCount = vendorbillSearchObj.runPaged().count;
			
			if(searchResultCount>0)
				{
				 var searchResult = vendorbillSearchObj.run().getRange({
						start: 0,
						end: 1
					});
	        	 
	        	
	        		 var balanceAmt = searchResult[0].getValue({
	    				 name: "fxamountremaining"
	    				});
				}
            		
            		
            		
            		
            	
			
        		 var amount = currentRec.getSublistValue({
            		sublistId: 'custpage_checksublist',
            		fieldId: 'custrecord_jj_balance_amt',
            		line:scriptContext.line
            	});
        		 
        		if(parseFloat(balanceAmt)>parseFloat(totalAmount))
        			{
        			
        			alert("You can't enter an amount greater than cheque amount" );
        			
        			return false;
        			}
        		else
        			return true;
        		}
        	 else
        		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) {
                console.log("error in  main." + key, e);
                return false;
            }
        };
    }


    return main;
});

User event to update payment record

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * Moneta Business Solutions
 * MBS-4 | Vendor Payment
 * **************************************************************************
 * Date : ${18/01/2019}
 * 
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : This triggers when a Vendor Payment is deleted
 * Date Created : 17-Jan-2019
 *
 * REVISION HISTORY
 * 
 * Revision 1.0 ${18/01/2019} aj : created
 * 
 ******************************************************************************/
define(['N/record', 'N/search'],
/**
 * @param {record} record
 * @param {search} search
 */
function(record, search) {
   
   

    /**
     * Function definition to be triggered before record is loaded.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.newRecord - New record
     * @param {Record} scriptContext.oldRecord - Old record
     * @param {string} scriptContext.type - Trigger type
     * @Since 2015.2
     */
    function afterSubmit(scriptContext) {
    	try
    	{
    		if(scriptContext.type=='delete')
    			{
    			// to get current record
        		var currentRecord = scriptContext.newRecord;
        		var amount =currentRecord.getValue({
        			fieldId:'total'
        		});
        		
        		// to get the Check
        		var chequeID = currentRecord.getValue({
        			fieldId:'custbody_mbs4_cheque_id'
        		});
        	
        		
        		if(chequeID)
        			{
        			
        			//to get the balance amount of check
        		var chequeRec = record.load({
        			type:'customrecord_jj_checkordraft',
        			id:chequeID
        		});
        		// to get the balance amount
        		var balanceamT = chequeRec.getValue({
        			fieldId:'custrecord_jj_balance_amt'
        		});
        		
        		// to set the balance amount
        		chequeRec.setValue({
        			fieldId:'custrecord_jj_balance_amt',
        			value:(parseFloat(balanceamT)+parseFloat(amount)).toFixed(2)
        		});
        		
        		//set In portfolio
        		chequeRec.setValue({
        			fieldId:'custrecord_jj_check_status',
        			value:1
        		});
        		chequeRec.save({
        			ignoreMandatoryFields:true
        			});
    			}
    			}
    		
    		
    		
    	}catch(e)
    	{
    		//log.debug("Err@ FN afterSubmit",e.message);
    		log.error("Err@ onAction FN ",e.message);
    		//console.log("Err@ FN =",e.message);
    	}

    }

    return {
       
        afterSubmit: afterSubmit
    };
    
});

Leave a comment

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