Mark all sales order items as special work order

Jira Code: AN-64

A button on the sales order – called “Mark All SWO”. If someone clicks on that button, all items on the SO will be marked as a special work order. You should be able to click just the column in the SO to make a special work order. The script should be available to all roles/users. It should always be in the sales order. Status of the SO should be Pending approval.

User Event

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

/**
 * Script Description: This script is for setting a buttons in the Sales Order record
 */

/*******************************************************************************
 * * AN * *
 * **************************************************************************
 * Date:02/11/18 
 * Script name: AN UE SO Buttons
 * Script id: customscript_an_ue_so_buttons
 * Deployment id: customdeploy_an_ue_so_buttons
 * Applied to: Sales order
 * 

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

define(['N/search','N/url','N/record'],

function(search,url,record) {
   
    /**
     * Function definition to be triggered before record is loaded.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.newRecord - New record
     * @param {string} scriptContext.type - Trigger type
     * @param {Form} scriptContext.form - Current form
     * @Since 2015.2
     */
    function beforeLoad(scriptContext) {
    	try {
    		
    		
    		var CustRec=scriptContext.form;
    		
    		var currRec= scriptContext.newRecord;
    		var status = currRec.getValue({
    			fieldId:'orderstatus'
    		});
    		
    		//Loading Client Script
			CustRec.clientScriptFileId = 10458;
			
    		if(scriptContext.type == 'view'){
    			
    			
    			
    			
    			var recId=scriptContext.newRecord.id;
    			
    			
              	
              //Set Shipping PDF button
    			var shippingPDF=CustRec.addButton({
    				id:'custpage_shipping_pdf_btn',
    				label:'Shipping Tag',
    				functionName:'shippingPDF'
    			});
    			// AJ MOD on 14/05/2019
    			
    			if(status=='A')
    			{ //Set Shipping PDF button
    			var markAll=CustRec.addButton({
    				id:'custpage_mark_all_swo_v',
    				label:'Mark All SWO',
    				functionName:'markAllSwo'
    			});
    			}
    		    
    		}else if(scriptContext.type == 'edit'){
    			if(status=='A')
    			{
    			 //Set Shipping PDF button
    			var markAll=CustRec.addButton({
    				id:'custpage_mark_all_swo',
    				label:'Mark All SWO',
    				functionName:'markAllSwoEdit'
    			});
    			}
    		}
    	
			
		} catch (e) {
			
			log.debug({    
				title: e.name,
                details: e.message
            });
		}

    }
    /**
     * 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=='create'|| scriptContext.type=='edit')
            {
              
           
    		var id = scriptContext.newRecord.id;
    		
    		log.debug("id",id)
    		
    		var toSL = url.resolveScript({
    		    scriptId: 'customscript_an65_jj_sl_print_bol_so',
    		    deploymentId: 'customdeploy_an65_jj_sl_print_bol_so',
    		    params:{
    		    	recId:id
    		    }
    		//    returnExternalUrl: true
    		});
    		
    		//log.debug("toSL",toSL)
    		// to load the rec
    		var curRec=record.load({
    			type:'salesorder',
    			id:id
    		
    		})
    		// to set the value
    		curRec.setValue({
    			fieldId:'custbody_bill_of_landing',
    			value:toSL
    		})
    		curRec.save({ignoreMandatoryFields:true});
               }
    	}catch(e)
    	{
    		log.debug("Err @ afterSubmit submit",e)
    	}

    }
   

    return {
        beforeLoad: beforeLoad,
        afterSubmit:afterSubmit
    };
    
});

Client script

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

/**
 * Script Description: This script defining the function of button   
 */

/*******************************************************************************
 * * AN * *
 * **************************************************************************
 * Date:7/11/18 
 * Script name: AN CS SO Btn Action
 * Script id: customscript_an_cs_so_btn_action
 * Deployment id: customdeploy_an_cs_so_btn_action
 * Applied to: Sales order
 * 
 * REVISION HISTORY
*
* Revision 1.0 ${02-11-2018} angel : created
* Revision 1.1 ${24-04-2019} nd : updated for AN-49

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


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

function(currentRecord,record,url,search) {
    
    /**
     * 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 markAllSwoEdit()
	{
		try{
			var soRecId = currentRecord.get().id;
			// to set the lines
			var soRec =currentRecord.get();
			var linesNum = soRec.getLineCount({
				sublistId : 'item'
			});

			for (var i = 0; i < linesNum; i++) {
				
				// to get item type itemtype
				if (soRec.getSublistValue({
					sublistId : 'item',
					fieldId : 'itemtype',
					line : i
				}) == "Assembly") {
					
					console.log('type',soRec.getSublistValue({
						sublistId : 'item',
						fieldId : 'itemtype',
						line : i
					}));
					
					/*soRec.setSublistValue({
						sublistId : 'item',
						fieldId : 'createwo',
						line : i,
						value : true
					})*/
					var lineNum = soRec.selectLine({
					    sublistId: 'item',
					    line: i
					});
					soRec.setCurrentSublistValue({
					    sublistId: 'item',
					    fieldId: 'createwo',
					    value: true,
					    ignoreFieldChange: true
					});
					soRec.commitLine({
					    sublistId: 'item'
					});
				}
			}
			
			
		}catch(e)
		{
			log.debug("Err@Edit button",e)
		}
	}
	
	
	
    /****
     * Fn to add mark all rec
     * 
     */
    function markAllSwo()
    {
    	try{
    		console.log("Inn of view rec")
    		var soRecId = currentRecord.get().id;
    		var soRec = record.load({
				type : 'salesorder',
				id : soRecId,
				isDynamic:true
			});

			var linesNum = soRec.getLineCount({
				sublistId : 'item'
			});

			for (var i = 0; i < linesNum; i++) {
				
				// to get item type itemtype
				if (soRec.getSublistValue({
					sublistId : 'item',
					fieldId : 'itemtype',
					line : i
				}) == "Assembly") {
					
					console.log('type',soRec.getSublistValue({
						sublistId : 'item',
						fieldId : 'itemtype',
						line : i
					}));
					
					/*soRec.setSublistValue({
						sublistId : 'item',
						fieldId : 'createwo',
						line : i,
						value : true
					})*/
					var lineNum = soRec.selectLine({
					    sublistId: 'item',
					    line: i
					});
					soRec.setCurrentSublistValue({
					    sublistId: 'item',
					    fieldId: 'createwo',
					    value: true,
					    ignoreFieldChange: true
					});
					soRec.commitLine({
					    sublistId: 'item'
					});
				}
			}
			 var soRecSOID = soRec.save();
			 location.reload();
			console.log('Create WO',soRecSOID);
    		
    	}catch(e)
    	{
    		console.log("Err@markall",e);
    	}
    }
    

    //Fuction on Shipping Tag button click
    function shippingPDF() {
    	try {
    		//console.log("shippingPDF");
    		var recID = currentRecord.get().id;

            var parameterObj = {
                intenalId: recID
            };
            var recObj = record.load({ type: "salesorder", id: recID });
          
          
            var labelUrl = url.resolveScript({
                scriptId: "customscript_sl_shipping_pdf",
                deploymentId: "customdeploy_sl_shipping_pdf",
                returnExternalUrl: false,
                params: parameterObj
            });
            var childwindow = window.open(labelUrl);
			
		} 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 {
    		console.log("validateLine");

    		//to restrict item if it is not  finished good
    		 if(scriptContext.sublistId=='item'){
    			// console.log("validate item");
                 var itemClass = scriptContext.currentRecord.getCurrentSublistValue({
         	 		fieldId: "class",
         	 		sublistId: 'item'
         	 	 });
                 console.log("itemClass",itemClass);
                 
                 var clsRecordObj = record.load({ type: "classification", id: itemClass});
	             var parentcls=clsRecordObj.getText({
	       			 fieldId: 'parent'
	           	 });
	             console.log("parentcls",parentcls);
	             if( !( (parentcls.startsWith("Finished :")) || (parentcls=="Finished") || (itemClass=='25'))){
	            	 alert("Sorry, you have selected an item that is not a finished good. Please remove the item and try again.");
	            	 return false;
	             }
                 
	             return true;
                
             }
    		
			
		} catch (e) {
			console.log(e.name,e.message);
		}

    }

  //updated on 24-04-19 for AN-49
    /**
     * 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;
    		var sublistName =scriptContext.fieldId;
    		console.log('currentRec',currentRec)
    		console.log('sublistName',sublistName)
    		if(sublistName == 'item'){
    			var itemName = currentRec.getCurrentSublistValue({
        		    sublistId: 'item',
        		    fieldId: 'item'
        		});
        		console.log('itemName',itemName)
        		var lookupInvItems = search.lookupFields({
        		    type: search.Type.ASSEMBLY_ITEM,
        		    id: itemName,
        		    columns: ['custitem_item_number_name_misc', 'custitem_allergens', 'custitem_standard_cost','custitem_routings','custitem_bom']
        		});
        		var bom = lookupInvItems.custitem_bom
        		var routing =  lookupInvItems.custitem_routings
        		var misc = lookupInvItems.custitem_item_number_name_misc
        		var allergen = lookupInvItems.custitem_allergens
        		var stdCost = lookupInvItems.custitem_standard_cost
        		console.log('bom',bom)
        		console.log('routing',routing)
        		console.log('misc',misc)
        		console.log('allergen',allergen)
        		console.log('stdCost',stdCost)
        		var alertChar =null;
        		if(misc == false || allergen==false|| stdCost==false || routing == false || bom==false ){
        			if(misc == false){
        				alertChar = "ITEM NUMBER, NAME, MISC. (PURCHASING)";
//        				alert('These checkboxes must be checked in the Item Setup: "ITEM NUMBER, NAME, MISC. (PURCHASING)". If you have questions please contact the IT Department.')
        			}
        			if(allergen == false){
        				if(alertChar != null){
        					alertChar = alertChar + ", ALLERGENS (QA)";	
        				}else{
        					alertChar= "ALLERGENS (QA)";	
        				}
        				
//        				alert('These checkboxes must be checked in the Item Setup: "ALLERGENS (QA)". If you have questions please contact the IT Department.')
        			}
        			if(stdCost == false){
        				if(alertChar != null){
        				alertChar = alertChar + ", STANDARD COST (IT)";
        				}else{
        					alertChar= "STANDARD COST (IT)";	
        				}
//        				alert('These checkboxes must be checked in the Item Setup: " STANDARD COST (IT)". If you have questions please contact the IT Department.')
        			}
        			if(routing == false){
        				if(alertChar != null){
        					alertChar = alertChar + ", ROUTINGS (PRODUCTION)";	
        				}else{
        					alertChar= "ROUTINGS (PRODUCTION)";	
        				}
        				
//        				alert('These checkboxes must be checked in the Item Setup: "ALLERGENS (QA)". If you have questions please contact the IT Department.')
        			}
        			if(bom == false){
        				if(alertChar != null){
        					alertChar = alertChar + ", BOM (R&D/PURCHASING)";	
        				}else{
        					alertChar= " BOM (R&D/PURCHASING)";	
        				}
        				
//        				alert('These checkboxes must be checked in the Item Setup: "ALLERGENS (QA)". If you have questions please contact the IT Department.')
        			}
        			console.log('alertChar',alertChar)
        			alert('These checkboxes must be checked in the Item Setup:'+alertChar+'. If you have questions please contact the IT Department.')
        			return false;
        		}
        		
    		}
    		return true;
    	}catch(error){
    		console.log('error @ validateField',error)
    	}

    }
    

    return {
       /* pageInit: pageInit,*/
    	validateLine: validateLine,
        validateField:validateField,
        shippingPDF:shippingPDF,
        markAllSwo:markAllSwo,
        markAllSwoEdit:markAllSwoEdit
    };
    
});

Leave a comment

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