Work Order Component Calculation Tool

Jira code: AN-8

Created a Suitelet page which lists all work orders with the status ‘In Process’.  Sublist contains details such as Work Order number, assembly item name, quantity, completed Quantity, and a checkbox. The user can select one WO with a completed quantity. On submitting, components items of that assembly item will be displayed in the page. Also, there is quantity per amount, Total Quantity, Quantity for the Completed Quantity and the difference will be displayed. The user can calculate the component quantity with various Completed Quantity by changing the Completed Quantity field value on the Work Order Component Calculation Page.

Client Script

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

/**
 * 
 */

/*******************************************************************************
 * * AN * *
 * **************************************************************************
 * Date:10/1/19
 * 
 * Author : Jobin and Jismi IT Services LLP
 * Script Description: This script defines actions on component calculator tool suitelet
 * Script name: AN-8 CS Work Order Component Calculator
 * Script id: customscript_an8_cs_wo_comp_calculator
 * Deployment id: customdeploy_an8_cs_wo_comp_calculator
 * 
 ******************************************************************************/

define(['N/currentRecord','N/url'],

function(currentRecord,url) {
    
    /**
     * Function to be executed after page is initialized.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.currentRecord - Current form record
     * @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
     *
     * @since 2015.2
     */
    function pageInit(scriptContext) {
    	try {
    		console.log('in');
    		document.getElementById("tbl_wo_sublist_remove").remove();
    		var currentRec = scriptContext.currentRecord;
    		var comQty = currentRec.getValue({
                fieldId : 'custpage_completed_qty'
            });
    		if(comQty==0){
    			alert('Please enter Completed Quantity');
    		}

		} catch (e) {
			console.log(e.name, e.message);
		}

    }
    
    

    /**
     * Function to be executed when field is changed.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.currentRecord - Current form record
     * @param {string} scriptContext.sublistId - Sublist name
     * @param {string} scriptContext.fieldId - Field name
     * @param {number} scriptContext.lineNum - Line number. Will be undefined if not a sublist or matrix field
     * @param {number} scriptContext.columnNum - Line number. Will be undefined if not a matrix field
     *
     * @since 2015.2
     */
    function fieldChanged(scriptContext) {
    	try {
    		
    		var currentRec = scriptContext.currentRecord;
    		
    		//Restricting multi selection from the Work order Sublist
    		if(scriptContext.sublistId=='wo_sublist' && scriptContext.fieldId == 'custpage_select_wo')
            {
    			
    			var selValue = currentRec.getCurrentSublistValue({
                    sublistId: 'wo_sublist',
                    fieldId: 'custpage_select_wo'
                });

    			if(selValue==true){
    				var currIndex = currentRec.getCurrentSublistIndex({
                	    sublistId: 'wo_sublist'
                	});
    				var linNum = currentRec.getLineCount({
    	                sublistId: 'wo_sublist'
    	            });
    	            //console.log('linNum', linNum);
    				
    	            for (var i = 0; i < linNum; i++) {
    	            	
    	            	var secondSelectFd = currentRec.getSublistValue({
                		    sublistId: 'wo_sublist',
                		    fieldId: 'custpage_select_wo',
                		    line: i
                		});
                		if(secondSelectFd){
                			var currentSublist = currentRec.selectLine({
                			    sublistId: 'wo_sublist',
                			    line: i
                			});
                			currentSublist.setCurrentSublistValue({
                    		    sublistId: 'wo_sublist',
                    		    fieldId: 'custpage_select_wo',
                    		    value : false,
                    		    ignoreFieldChange:true
                    		});
                			currentSublist.commitLine({
                			    sublistId: 'wo_sublist'
                			});
                		}
                		
    	            }
    	            var currentSublist = currentRec.selectLine({
        			    sublistId: 'wo_sublist',
        			    line: currIndex
        			});
    	            currentSublist.setCurrentSublistValue({
            		    sublistId: 'wo_sublist',
            		    fieldId: 'custpage_select_wo',
            		    value : true,
            		    ignoreFieldChange:true
            		});
 				
    			}
            }
    		
    		//Changing the sublist based on the Location and Page index selection
    		if(scriptContext.fieldId == 'custpage_location' || scriptContext.fieldId == 'custpage_pageid')
            {
    			var locationValue = currentRec.getValue({
                    fieldId : 'custpage_location'
                });
    			
    			var pageIndex = currentRec.getValue({
            		fieldId : 'custpage_pageid'
            	});
            
    			if(pageIndex != null && pageIndex != '' && pageIndex != undefined){
        			var pageId = parseInt(pageIndex.split('_')[1]);
    			}
    			else{
    				pageId=0;
    			}
            	
    		
    	        get_url = url.resolveScript({
    	    		scriptId: "customscript_an8_sl_wo_comp_calculator",
    	            deploymentId: "customdeploy_an8_sl_wo_comp_calculator",
    	            returnExternalUrl: true
    	        });	
       		 	
    	        get_url += '&locationValue=' + locationValue + '&pageindex=' + pageId;
    	        if (window.onbeforeunload) {
	                window.onbeforeunload = function() {
	                    null;
	                };
	            }
    	        window.location.href = get_url;
            }
    		
    		//Recalculating based on the Completed quantity field change on the Calculation page
    		if(scriptContext.fieldId == 'custpage_completed_qty'){
    			get_url = url.resolveScript({
    	    		scriptId: "customscript_an8_sl_wo_comp_calculator",
    	            deploymentId: "customdeploy_an8_sl_wo_comp_calculator",
    	            returnExternalUrl: true
    	        });	
    			
    			var woDoc = currentRec.getValue({
                    fieldId : 'custpage_doc_number'
                });
    			
    			var comQty = currentRec.getValue({
                    fieldId : 'custpage_completed_qty'
                });
    			
    			var assItem = currentRec.getValue({
                    fieldId : 'custpage_ass_item'
                });
    			
    			var assQty = currentRec.getValue({
                    fieldId : 'custpage_wo_quantity'
                });
    			
    			get_url += '&CALC=TRUE' + '&woDoc=' + woDoc + '&comQty=' + comQty + '&assItem=' + assItem + '&assQty=' + assQty;
    			if (window.onbeforeunload) {
	                window.onbeforeunload = function() {
	                    null;
	                };
	            }
    			window.location.href = get_url;
    		}
    		
			
		} catch (e) {
			console.log(e.name,e.message);
		}

    }
    
    
    /**
     * Validation function to be executed when field is changed.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.currentRecord - Current form record
     * @param {string} scriptContext.sublistId - Sublist name
     * @param {string} scriptContext.fieldId - Field name
     * @param {number} scriptContext.lineNum - Line number. Will be undefined if not a sublist or matrix field
     * @param {number} scriptContext.columnNum - Line number. Will be undefined if not a matrix field
     *
     * @returns {boolean} Return true if field is valid
     *
     * @since 2015.2
     */
    function validateField(scriptContext) {
    	
    	try {
    		
    		var currentRec = scriptContext.currentRecord;

    		//Given alert if the Completed quantity is greater than Quantity or -ve
    		if(scriptContext.sublistId=='wo_sublist' && scriptContext.fieldId == 'custpage_com_qty')
            {
                var comQty = currentRec.getCurrentSublistValue({
                    sublistId: 'wo_sublist',
                    fieldId: 'custpage_com_qty'
                });
            	var assQty = currentRec.getCurrentSublistValue({
                    sublistId: 'wo_sublist',
                    fieldId: 'custpage_qty'
                });
            	if(comQty>assQty){
            		alert("Completed Quantity should not be greater than Quantity");
            		return false;
            	}
            	
            	if(comQty<0){
            		alert("Completed Quantity should not be a negative");
            		return false;
            	}
            }
    		
    		
    		
    		//Restrict and Given alert if the Completed quantity is greater than Quantity or -ve on calculation page
    		if(scriptContext.fieldId == 'custpage_completed_qty')
            {
    			
    			var comQty = currentRec.getValue({
                    fieldId : 'custpage_completed_qty'
                });
    			var assQty = currentRec.getValue({
                    fieldId : 'custpage_wo_quantity'
                });
  
            	if(comQty>assQty){
            		alert("Completed Quantity should not be greater than Quantity");
            		return false;
            	}      
            	if(comQty<0){
            		alert("Completed Quantity should not be a negative");
            		return false;
            	}
            	
            	if(comQty==null || comQty=='' || comQty==undefined){
            		alert("Completed Quantity should not be a empty");
            		return false;
            	}
            }
    		return true;
			
		} catch (e) {
			console.log(e.name,e.message);
		}

    }
    
    
    /**
     * Validation function to be executed when sublist line is committed.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.currentRecord - Current form record
     * @param {string} scriptContext.sublistId - Sublist name
     *
     * @returns {boolean} Return true if sublist line is valid
     *
     * @since 2015.2
     */
    function validateLine(scriptContext) {
    	try {
    		
    		var currentRec = scriptContext.currentRecord;
    		
    		//Given alert if the ticking a line without WO
    		
                var selValue = currentRec.getCurrentSublistValue({
                    sublistId: 'wo_sublist',
                    fieldId: 'custpage_select_wo'
                });

                var docNo = currentRec.getCurrentSublistValue({
                    sublistId: 'wo_sublist',
                    fieldId: 'custpage_doc_no'
                });

            	if((selValue==true) && (docNo==null ||  docNo=='' ||docNo==undefined)){
            		alert("Please select a valid Work Order");
            		return false;
            	}
            	
            
    		return true;
			
		} catch (e) {
			console.log(e.name,e.message);
		}

    }
    
    
    
    //defining actions in the Calculate button click
	function calculateBtnAction() {
		try {
        var get_url;
        
        get_url = url.resolveScript({
    		scriptId: "customscript_an8_sl_wo_comp_calculator",
            deploymentId: "customdeploy_an8_sl_wo_comp_calculator",
            returnExternalUrl: true
        });	       
            
        var CurrRecord = currentRecord.get();
        
        var linNum = CurrRecord.getLineCount({
            sublistId: 'wo_sublist'
        });
        //console.log('linNum', linNum);
        var woDoc=null, comQty=0;
        
        var selFlag=0;
        
        //Getting the required field and redirecting to the calculation page
        for (var i = 0; i < linNum; i++) {
        	var lineSelectFd = CurrRecord.getSublistValue({
    		    sublistId: 'wo_sublist',
    		    fieldId: 'custpage_select_wo',
    		    line: i
    		});
        	
        	if(lineSelectFd){
        		selFlag=1;
        		var woDoc = CurrRecord.getSublistValue({
        		    sublistId: 'wo_sublist',
        		    fieldId: 'custpage_doc_no',
        		    line: i
        		});
        		
        		var assItem = CurrRecord.getSublistValue({
        		    sublistId: 'wo_sublist',
        		    fieldId: 'custpage_item',
        		    line: i
        		});
        		
        		var assQty = CurrRecord.getSublistValue({
        		    sublistId: 'wo_sublist',
        		    fieldId: 'custpage_qty',
        		    line: i
        		});
        		
        		var comQty = CurrRecord.getSublistValue({
        		    sublistId: 'wo_sublist',
        		    fieldId: 'custpage_com_qty',
        		    line: i
        		});
        		
        		if(comQty==null || comQty=='' || comQty==undefined){
        			comQty=0;
        		}
        		
        		if(comQty>assQty){
            		alert("Completed Quantity should not be greater than Quantity");
            		return false;
            	}
        		
        		 get_url += '&CALC=TRUE' + '&woDoc=' + woDoc + '&comQty=' + comQty + '&assItem=' + assItem + '&assQty=' + assQty;
        	     window.open(get_url,"Component Quantity Calculator",'height=800,width=1000')
        	     
        	}
        }
        
        if(selFlag==0){
        	alert("Please select one Work Order");
    		return false;
        }
        
    	} catch (e) {
    		console.log(e.name,e.message);
    	}
	}
    
	
	//defining actions in the Back button click
	function backBtnAction() {
		try {
		

            if (window.onbeforeunload) {
                window.onbeforeunload = function() {
                    null;
                };
            }
            window.close()
			
		} catch (e) {
			console.log(e.name,e.message);
		}
		
	}


    return {
        pageInit: pageInit,
        calculateBtnAction: calculateBtnAction,
        backBtnAction: backBtnAction,
        fieldChanged: fieldChanged,
        validateField: validateField,
        validateLine: validateLine
    };
    
});

Suitelet

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

/**
 * Script Description: This script is for component calculator tool  for Work Orders
 */

/*******************************************************************************
 * * AN * *
 * **************************************************************************
 * Date:10/1/19
 * Script name: AN-8 SL Work Order Component Calculator
 * Script id: customscript_an8_sl_wo_comp_calculator
 * Deployment id: customdeploy_an8_sl_wo_comp_calculator
 * Author : Jobin and Jismi IT Services LLP

 ******************************************************************************/

define(['N/record','N/search','N/ui/serverWidget'],

function(record,search,serverWidget) {
	
	var PAGE_SIZE=10;
   
    /**
     * Definition of the Suitelet script trigger point.
     *
     * @param {Object} context
     * @param {ServerRequest} context.request - Encapsulation of the incoming request
     * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
     * @Since 2015.2
     */
    function onRequest(context) {
    	
    	try {
    		
    		var form=null;
    		
    		 var CALC = assignDefaultValue(context.request.parameters.CALC, 'FALSE');
             var woDoc = assignDefaultValue(context.request.parameters.woDoc, null);
             var comQty = assignDefaultValue(context.request.parameters.comQty, null);
             var assItem = assignDefaultValue(context.request.parameters.assItem, null);
             var assQty = assignDefaultValue(context.request.parameters.assQty, null);
             var assLocation = assignDefaultValue(context.request.parameters.locationValue, 4);
             var pageId = assignDefaultValue(context.request.parameters.pageindex, 0);

            //Calulation page 
    		if(CALC=="TRUE"){
    			log.debug('in CALC');
    			
    			//initialize form and setting the Fields
                form = serverWidget.createForm({
                    title: 'Work Order Component Calculation Page'
                });
                form.clientScriptFileId = 11960;
                
                var woNumfd = form.addField({
                    id: 'custpage_doc_number',
                    type: serverWidget.FieldType.TEXT,
                    label: 'Work Order #'
                });
                woNumfd.defaultValue = woDoc;
                woNumfd.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	 		});
                
                var assItemfd = form.addField({
                    id: 'custpage_ass_item',
                    type: serverWidget.FieldType.TEXT,
                    label: 'Assembly Item'
                });
                assItemfd.defaultValue = assItem;
                assItemfd.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	 		});
                
                var woQuantityfd = form.addField({
                    id: 'custpage_wo_quantity',
                    type: serverWidget.FieldType.FLOAT,
                    label: 'Work Order Quantity'
                });
                woQuantityfd.defaultValue = assQty;
                woQuantityfd.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	 		});
                
                var completedQtyfd = form.addField({
                	id: 'custpage_completed_qty',
        			type: serverWidget.FieldType.FLOAT,
        			label: 'Completed Quantity'
        		});
                completedQtyfd.defaultValue = comQty;
                
                form.addButton({
                    id : 'back_btn',
                    label : 'Back',
                    functionName: 'backBtnAction'
                });
                
    			 var sublist = form.addSublist({
                     id : 'custpage_component_dtls',
                     type : serverWidget.SublistType.STATICLIST,
                     label : 'Component Details'
                 });
                 
                 sublist.addField({
                     id: 'custpage_an_woc_items',
                     type: serverWidget.FieldType.TEXT,
                     label: 'Item'
                 });
                 sublist.addField({
                     id: 'custpage_an_woc_qty_per',
                     type: serverWidget.FieldType.FLOAT,
                     label: 'Quantity Per'
                 });
                 sublist.addField({
                     id: 'custpage_an_woc_estimated_qty',
                     type: serverWidget.FieldType.FLOAT,
                     label: 'Estimated Quantity'
                 });
                 sublist.addField({
                     id: 'custpage_an_woc_com_item_qty',
                     type: serverWidget.FieldType.FLOAT,
                     label: 'Quantity for Completed Item'
                 });
                 sublist.addField({
                     id: 'custpage_an_woc_remain_item_qty',
                     type: serverWidget.FieldType.FLOAT,
                     label: 'Quantity for Remaining Item'
                 });
                 
                 
                 //Searching for the Component Items of a Assembly Item
                 var assemblyitemSearchObj = search.create({
                	   type: "assemblyitem",
                	   filters:
                	   [
                	      ["type","anyof","Assembly"], 
                	      "AND", 
                	      ["name","is",assItem]
                	   ],
                	   columns:
                	   [
                	      search.createColumn({name: "memberitem", label: "Member Item"}),
                	      search.createColumn({name: "memberquantity", label: "Member Quantity"})
                	   ]
                	});
                	var searchResultCount = assemblyitemSearchObj.runPaged().count;
                	
                	
                	var start = 0;
        			var end = 1000;
                 	
        			//Getting and setting the search result in to the Sublist
                    for (var i = 0; i < Math.ceil(searchResultCount / 1000); i++) 
        			{ 
        				result = assemblyitemSearchObj.run().getRange({
        					start: start,
        					end: end
        				});

        				var len=result.length;
        				for (var j = 0; j < len; j++) {
        			
        					var ass_Item= result[j].getText({
            				    name: 'memberitem'
            				});
        					
        					var qtyPer= result[j].getValue({
            				    name: 'memberquantity'
            				});
        					qtyPer=parseFloat(qtyPer).toFixed(5);
        					comQty=parseFloat(comQty).toFixed(5);
        					assQty=parseFloat(assQty).toFixed(5);
        		
        					//set values to sublist
        					sublist.setSublistValue({
        						id : "custpage_an_woc_items",
        						line : j,
        						value : ass_Item
        					});
        					
        					sublist.setSublistValue({
                        	    id : 'custpage_an_woc_qty_per',
                        	    line : j,
                        	    value : parseFloat(qtyPer).toFixed(5)
                        	});
                        	
                        	var estQty = (qtyPer*assQty).toFixed(5);
                        	
                        	sublist.setSublistValue({
                        	    id : 'custpage_an_woc_estimated_qty',
                        	    line : j,
                        	    value : parseFloat(estQty).toFixed(5)
                        	});
                        	
                        	var val=qtyPer*comQty;
                    		
                        	sublist.setSublistValue({
                        	    id : 'custpage_an_woc_com_item_qty',
                        	    line : j,
                        	    value : parseFloat(val).toFixed(5)
                        	});
                        	
                        	sublist.setSublistValue({
                        	    id : 'custpage_an_woc_remain_item_qty',
                        	    line : j,
                        	    value : (estQty-val).toFixed(5)
                        	});
        					

        				}

        				start = end;
        				end = end + 1000;

        			}
                 	

    		}
    		
    		//Entry Page of Calculator 
    		else{
    			log.debug('Out CALC');
    			
    			//initialize form and setting the fields
                form = serverWidget.createForm({
                    title: 'Work Order Component Calculator'
                });
                form.clientScriptFileId = 11960;
                
                var locationfd = form.addField({
                    id: 'custpage_location',
                    type: serverWidget.FieldType.SELECT,
                    label: 'Location',
                    source: 'location'
                });
                locationfd.defaultValue = assLocation;
                

                //add Pagination Fields
                var selectOptions = form.addField({
                    id: 'custpage_pageid',
                    type: serverWidget.FieldType.SELECT,
                    label: 'Page Index'
                });

                
                form.addButton({
                    id : 'calculate_btn',
                    label : 'Calculate',
                    functionName: 'calculateBtnAction'
                });
                
                var sublist = form.addSublist({
                	id : 'wo_sublist',
                    type : serverWidget.SublistType.INLINEEDITOR,
                    label : 'Work Orders'
                });
                
                sublist.addField({
        			id: 'custpage_select_wo',
        			type: serverWidget.FieldType.CHECKBOX,
        			label: 'Select'
        		});
                	
                var doc_no = sublist.addField({
                	id: 'custpage_doc_no',
        			type: serverWidget.FieldType.TEXT,
        			label: 'Document Number'
        		});
                doc_no.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	  			
    	 		});
                
                var ass_Item = sublist.addField({
                	id: 'custpage_item',
        			type: serverWidget.FieldType.TEXT,
        			label: 'Assembly Item'
        		});
                ass_Item.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	  			
    	 		});
                
                var qty = sublist.addField({
                	id: 'custpage_qty',
        			type: serverWidget.FieldType.FLOAT,
        			label: 'Quantity'
        		});
                qty.updateDisplayType({
    				 displayType : serverWidget.FieldDisplayType.DISABLED
    	 		});

                var com_qty = sublist.addField({
                	id: 'custpage_com_qty',
        			type: serverWidget.FieldType.FLOAT,
        			label: 'Completed Quantity'
        		});
               
                
                // Run search and determine page count
         		 var retrieveSearch = runSearch(PAGE_SIZE,assLocation);
         		 
         		//getting the total count
                var len=retrieveSearch.count;

                var pageCount = parseFloat(retrieveSearch.count / PAGE_SIZE);
               

                // Set pageId to correct value if out of index
                if (!pageId || pageId == '' || pageId < 0)
                  pageId = 0;
                else if (pageId >= pageCount)
                  pageId = pageCount - 1;
                
                
                var recordLength=len;
                if (recordLength < 10) {
                	PAGE_SIZE = recordLength;
                }
                if(recordLength==0)
                {
                	PAGE_SIZE = 1;
                }
                
            
                //setting the page index
                for (var i = 0; i < pageCount; i++) {

                  
                if (i == pageId) {
                       if(parseInt(pageCount)==i)
                        {
                        selectOptions.addSelectOption({
                        value : 'pageid_' + i,
                        text : ((i * PAGE_SIZE) + 1) + ' - '
                              + recordLength,
                        isSelected : true
                        });

                        }
                        else
                        {
                        selectOptions.addSelectOption({
                        value : 'pageid_' + i,
                        text : ((i * PAGE_SIZE) + 1) + ' - '
                              + ((i + 1) * PAGE_SIZE),
                        isSelected : true
                        });
                        }
                  } else {
               	   	 if(parseInt(pageCount)==i)
                        {
               	     selectOptions.addSelectOption({
                        value : 'pageid_' + i,
                        text : ((i * PAGE_SIZE) + 1) + ' - '
                              + recordLength
               	     });
                        }
                  else
                  		{
                      	selectOptions.addSelectOption({
                       value : 'pageid_' + i,
                       text : ((i * PAGE_SIZE) + 1) + ' - '
                              + ((i + 1) * PAGE_SIZE)
                      	});
                  		}
                  }
               }
           
       
               if (pageId >= 0 && pageCount != 0) {
   
            	   // Get subset of data to be shown on page
                   var addResults = fetchSearchResult(retrieveSearch, pageId);

                   var j=0;
                   
                   // Set data returned to columns
                   addResults.forEach(function (result) {
                	   
                	   //set values to sublist
   						sublist.setSublistValue({
   							id : "custpage_doc_no",
   							line : j,
   							value : result.tranid
   						});
   					
   						sublist.setSublistValue({
   							id : "custpage_item",
   							line : j,
   							value : result.ass_Item
   						});
   					
   						sublist.setSublistValue({
   							id : "custpage_qty",
   							line : j,
   							value : result.qty
   						});
   						
   						j++;
   						
                   });
            	   
            	   
               }
              
                
    		}

    		context.response.writePage(form);
    		
		} catch (e) {
			log.debug({    
				title: e.name,
				details: e.message
			});
		}

    }

    return {
        onRequest: onRequest
    };
    
    
    
    //creating the search for the Work orders to shown in the entry page
    function runSearch(searchPageSize,assLocation) {
    	try {
			
    		var workorderSearchObj = search.create({
          	   type: "workorder",
          	   filters:
          	   [
          	      ["type","anyof","WorkOrd"], 
          	      "AND", 
          	      ["status","anyof","WorkOrd:D"], 
          	      "AND", 
          	      ["location","anyof",assLocation], 
          	      "AND", 
          	      ["mainline","is","T"]
          	   ],
          	   columns:
          	   [
          	      search.createColumn({name: "transactionnumber", label: "Transaction Number"}),
          	      search.createColumn({name: "tranid", sort: search.Sort.ASC, label: "Document Number"}),
          	      search.createColumn({name: "quantity", label: "Quantity"}),
          	      search.createColumn({name: "item", label: "Item"})
          	      

          	   ]
          	});
    		
    		return workorderSearchObj.runPaged({
                pageSize : searchPageSize
            });
    		
		} catch (e) {
			log.debug({    
				title: e.name,
				details: e.message
			});
		}
    }
    
    
    
   //getting data based on the range 
	function fetchSearchResult(pagedData, pageIndex) {
	
		try{
			
			var searchPage = pagedData.fetch({
                index : pageIndex
            });
			
			var results = new Array();
			 
			 //fetching values from saved search results
			searchPage.data.forEach(function (result) {  
				 
				 var tranid = assignDefaultValue(result.getValue({
 				    name: 'tranid'
 				}),null);
					
				var ass_Item= assignDefaultValue(result.getText({
 				    name: 'item'
 				}),null);
					
				var qty= assignDefaultValue(result.getValue({
 				    name: 'quantity'
 				}),null);
				
				results.push({
	                "tranid" : tranid,
	                "ass_Item" : ass_Item,
	                "qty" : qty
	            });
				 
			 });
			 
			 return results;
		
		} catch (e) {
			log.debug({    
				title: e.name,
				details: e.message
			});
		}
    }

    
    
    //To check whether a value exists in parameter
    function checkForParameter(parameter, parameterName) {
        if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && 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;
    }
    
});

Leave a comment

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