Scheduled script to make SO copy

Jira Code: BTN-474

This script will load the custom record. The custom record includes details of sales order internal id, customer id and customer address id. The script will make a copy of the given sales order with the given customer details and remove the record entry from the custom record if it is successful.

define(['N/runtime', 'N/search', 'N/task', 'N/record'],
/**
 * @param {record} record
 */
function(runtime, search, task, record) {
   
    /**
     * Definition of the Scheduled script trigger point.
     *
     * @param {Object} scriptContext
     * @param {string} scriptContext.type - The context in which the script is executed. It is one of the values from the scriptContext.InvocationType enum.
     * @Since 2015.2
     */
    function execute(scriptContext) {

		try {
			// Search Data in saved search
			logme("ScheduledScript", "Scheduled script started");
			//create a search to load the custom record values
			var customSearch = search.create({   
					type : 'customrecord_rb_make_copy_so',
					columns :[{
							name: 'custrecord_rb_cust_id_make_copy'
						},{
							name: 'custrecord_rb_cust_add_id_make_copy'
						},{
							name: 'custrecord_rb_sales_order_id_copy_from'
						}]
				 });          
			var searchResult = customSearch.run().getRange({
				start : 0,
				end : 1000
			});
			var end = 250;
			var searchResult_length = searchResult.length;
			if (searchResult_length < end) {
				end = searchResult_length;
			}
			if (searchResult_length > 0) {
				var record_UPDATED_ARRAY = [];
				var record_upid = [];
				//get the custom record values
				for (var i = 0; i < end; i++) {					
					var SINGLE_SO = searchResult[i];
					var SOID = SINGLE_SO.getValue({name : 'custrecord_rb_sales_order_id_copy_from'});
					var customerId = SINGLE_SO.getValue({name : 'custrecord_rb_cust_id_make_copy'});
					var customerAddress = SINGLE_SO.getValue({name : 'custrecord_rb_cust_add_id_make_copy'});					
					var customerRecord = record.load({
						type : 'customer',
						id : customerId
					});
					var numLines = customerRecord.getLineCount({
						sublistId: 'addressbook'
					});
					var custAdd;
					for(var j=0 ; j<numLines ; j++){
						var custAddress = customerRecord.getSublistValue({
							sublistId : 'addressbook',
							fieldId : 'id',
							line : j
						});						
						if(custAddress == customerAddress){
							
							var subrec = customerRecord.getSublistSubrecord({
				                sublistId: 'addressbook',
				                fieldId: 'addressbookaddress',
				                line: j
				            });							
							custAdd = subrec.getValue({								
								fieldId : 'addrtext'								
							}); 
						}
					}									
					//call the function for making copy of the sales order
					record_upid = makeSoCopy(record, SOID,customerId,custAdd,customerAddress);					
					record_UPDATED_ARRAY.push(record_upid);
					//Check the result from the makeSoCopy function
					if(record_upid){
						if(isNaN(record_upid)){
							//if error occured, save the error details in custom record entry
							var customrecord = record.load({
								type : 'customrecord_rb_make_copy_so',
								id : searchResult[i].id
							});
							var customrid = customrecord.getValue({
								fieldId : 'custrecord_rb_cust_id_make_copy'
							});
							
							// get the message from the error occured and set it to the custom record entry
							var message = record_upid.message;
							
							customrecord.setValue({
								fieldId : 'custrecord_rb_copy_status_make_copy',
								value : message
							});
							//save the record
							customrecord.save({
								enableSourcing : true,
								ignoreMandatoryFields : true
							});	
						}
						//if copying is successful remove the record entry form the custom record
						else{
							var deleteRecord = record.delete({  //deletes the custom record after updating the lead.
							       type: 'customrecord_rb_make_copy_so',
							       id: searchResult[i].id
							    });
						}
					}				
				}
				logme("searchResult_length " + searchResult_length + "_end " + end, "record_UPDATED_ARRAY " + record_UPDATED_ARRAY);
			}
			else{
				logme('No Result','No result');
			}
			if (searchResult_length > 250) {
				rescheduleScriptandReturn(task);
			}
		} catch (e) {
			logme("firstTry", getError(e));
		}
		var remainingUsage = runtime.getCurrentScript().getRemainingUsage();
		if (remainingUsage < 100) {
			logme("remainingUsage", remainingUsage);
		}	
    }
    /*******************************************************************************
     * This function will create copy of the sales order
     * 
     * @param record
     * @param SOID
     * @param customerId
     * @param customerAddress
     * @returns recordArray
     * 
     */
    function makeSoCopy(record, SOID,customerId,custAdd,customerAddress) {
    	try {		
    		//make  copy of the SO		
    			var objRecord = record.copy({
    			    type: record.Type.SALES_ORDER,
    			    id: SOID,
    			    isDynamic: true
    			});
    			// set customer value
    			objRecord.setValue({
    				fieldId : 'entity',
    				value : customerId
    			});
    			// set payment method to null 
    			objRecord.setValue({
    				fieldId : 'paymentmethod',
    				value : ''
    			});
    			// set memo to null 
    			objRecord.setValue({
    				fieldId : 'memo',
    				value : ''
    			});
    			//set po to null
    			objRecord.setValue({
    				fieldId : 'otherrefnum',
    				value : ''
    			});
    			//custbody_btn_319_created_po field to F
    			objRecord.setValue({
    				fieldId : 'custbody_btn_319_created_po',
    				value : false
    			});
    			// set the sales order shipping address
    			objRecord.setValue({
    				fieldId : 'shipaddress',
    				value : custAdd
    			});
    			// set the sales order SHIP TO SELECT
    			objRecord.setValue({
    				fieldId : 'shipaddresslist',
    				value : customerAddress
    			});
    			
    			var fieldLookUp = search.lookupFields({
    			    type: record.Type.SALES_ORDER,
    			    id: SOID,
    			    columns: ['shipmethod']
    			});		
    			// set the sales order shipping method
    			objRecord.setValue({
    				fieldId : 'shipmethod',
    				value : fieldLookUp.shipmethod[0].value
    			});
    			var recordId = objRecord.save({
    				enableSourcing : true,
    				ignoreMandatoryFields : true
    			});	
    		
    		
    		return recordId;
    	} catch (e) {
    		logme("Error@closeline", getError(e));
    		return e;
    	}
    }

    return {
        execute: execute,
        makeSoCopy: makeSoCopy
    };    
});
/*******************************************************************************
 * return error
 * 
 * @param e
 * @returns
 * 
 * Created on 09-Aug-2017 by rosemol
 */
function getError(e) {
	var stErrMsg = '';
	if (e.getDetails != undefined) {
		stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>'
				+ e.getStackTrace();
	} else {
		stErrMsg = '_' + e.toString();
	}
	return stErrMsg;
}

/*******************************************************************************
 * Log these data
 * 
 * @param title
 * @param details
 * @returns
 * 
 * Created on 09-Aug-2017 by rosemol
 */
function logme(title, details) {
	log.debug({
		title : title,
		details : details
	});
}
/*******************************************************************************
 * Try to reschedule script
 * 
 * @param task
 * 
 * Created on 07-Jul-2017 by rosemol
 */
function rescheduleScriptandReturn(task) {
	try {
		var mrTask = task.create({
			taskType : task.TaskType.SCHEDULED_SCRIPT,
			scriptId : "customscript_btn474_ss_copy_so",
			deploymentId : "customdeploy_btn474_ss_copy_so",
			params : {
				doSomething : true
			}
		});
		var scriptTaskId = mrTask.submit();
		logme("rescheduleScriptandReturn_scriptTaskId", scriptTaskId);
	} catch (e) {
		logme("Err@reschedulescript", getError(e));
	}
}

Leave a comment

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