Total Units calculation in PO Item line

Jira Code: AN-46
A checkbox will be added in the PO Item Line. On the field change of line item fields, LB/CS or CASES ORDERED, the script will set Total Units to LB/CS. * CASES ORDERED only if the custom checkbox is checked. Even if the LB/CS field is changed manually, the Total Units will be recalculated based on the new values.

Client Script : AN-2 JJ CS PO Button Action

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
* CLIENTNAME:Aurora Naturals
* AN-37
*  Raw Material Tag only for received items
* **************************************************************************
* Date : 02-11-2018
*
* Author: Jobin & Jismi IT Services LLP
* Script Description : This script defining the function of button 
* Date created : 02-11-2018
*
* REVISION HISTORY
*
* Revision 1.0 ${02-11-2018} angel : created
* Revision 1.0 ${20-03-2019} nd : updated
* Revision 1.0 ${04-04-2019} nd :updated for AN-43
* Revision 1.0 ${11-04-2019} nd :updated for AN-46
******************************************************************************/
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 pageInit(scriptContext) {
    	try {
    		console.log("In");
			
		} catch (e) {
			console.log(e.name,e.message);
		}
    }
    //updated on 20-03-2019
    function rowMaterialTag() {
    	try {
    		var recID = currentRecord.get().id;
    		 var parameter = {
    	                intenalId: recID
    	            };
    		 var purchaseorderSearchObj = search.create({
    			   type: "purchaseorder",
    			   filters:
    			   [
    			      ["type","anyof","PurchOrd"], 
    			      "AND", 
    			      ["applyingtransaction.type","anyof","ItemRcpt"], 
    			      "AND", 
    			      ["item.type","noneof","NonInvtPart"], 
    			      "AND", 
    			      ["internalidnumber","equalto",recID]
    			   ],
    			   columns:
    			   [
    			      search.createColumn({
    			         name: "itemid",
    			         join: "item",
    			         label: "Name"
    			      }),
    			      search.createColumn({
    			         name: "inventorynumber",
    			         join: "inventoryDetail",
    			         label: " Number"
    			      })
    			   ]
    			});
    			var searchResultCount = purchaseorderSearchObj.runPaged().count;
    			console.log('searchResultCount',searchResultCount)
    			if(searchResultCount>0){
    				var popup = url.resolveScript({
    	                 scriptId: "customscript_an37_jj_sl_itmlistpopup",
    	                 deploymentId: "customdeploy_an37_jj_sl_itmlistpopup",
    	                 returnExternalUrl: false,
    	                 params: parameter
    	             });
    	             var childwindow = window.open(popup,"","width=1000,height=750");
    			}
    			else{
    				alert('The received items are Non-inventory items')
    			}
    		 
    	} catch (e) {
			console.log(e.name,e.message);
		}
		
	}
    //updated on 20-03-2019
    function print_action(){
    	try{
    		var itemId_array=[];
    		var itemRecId_array=[];
    		console.log("print_action");
    		var record = currentRecord.get();
    		var po_id = record.getValue({
        		fieldId : 'cust_po'
        	});
    		var numLines = record.getLineCount({
      			 sublistId: 'custpage_sublst'
      		 	});
    		for(var j = 0; j < numLines; j++){
   			 var selectFieldValue = record.getSublistValue({
       			 sublistId: 'custpage_sublst',
       			 fieldId: 'custpage_check',
       			 line: j
       		 });
   			if(selectFieldValue == true){
				 var itemId = record.getSublistValue({
       			 sublistId: 'custpage_sublst',
       			 fieldId: 'cust_itemid',
       			 line: j
       		 });
				 itemId_array.push(itemId)
				 var itemRecId = record.getSublistValue({
	       			 sublistId: 'custpage_sublst',
	       			 fieldId: 'cust_itemrecid',
	       			 line: j
	       		 });
				 itemRecId_array.push(itemRecId)
			 }
    		}
    		console.log('itemId_array',itemId_array)
    		console.log('itemRecId_array',itemRecId_array)
    		var itemId_array_encode = encodeURI(itemId_array)
    		var itemRecId_array_encode = encodeURI(itemRecId_array)
            var labelUrl = url.resolveScript({
                scriptId: "customscript_sl_raw_material_tag",
                deploymentId: "customdeploy_sl_raw_material_tag",
                returnExternalUrl: false,
                params:{
    		    	'poId':po_id,
    		    	'itemID':itemId_array_encode,
    		    	'itemRecID':itemRecId_array_encode
    		    }
            });
    		
            var childwindow = window.open(labelUrl);
     
	
    	}catch(error){
    		console.log('error @ print_action',error)
    	}
    }
    /**
     * 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 currRec = scriptContext.currentRecord;
    		var sublistName = scriptContext.sublistId;
    		var fieldName = scriptContext.fieldId;
    		if(sublistName == 'item' && (fieldName == 'custcol_jj_calculate' || fieldName == 'custcol_lb_per_case_po' || fieldName == 'custcol_cases_ordered')){
    				var calc_check = currRec.getCurrentSublistValue({
    					sublistId: 'item',
    					fieldId: 'custcol_jj_calculate'
    				});
    				console.log('calc_check',calc_check)
    				if(calc_check == true){
    					var lb_cs = currRec.getCurrentSublistValue({
                			sublistId: 'item',
                			fieldId: 'custcol_lb_per_case_po'
                		});
        				var cases_order = currRec.getCurrentSublistValue({
                			sublistId: 'item',
                			fieldId: 'custcol_cases_ordered'
                		});
        				console.log('lb_cs',lb_cs)
        				console.log('cases_order',cases_order)
        				if((lb_cs == null||lb_cs == ''||lb_cs == " "||lb_cs == undefined||lb_cs == '-None-'||lb_cs == NaN ||lb_cs == 'NaN') || (cases_order == null||cases_order == ''||cases_order == " "||cases_order == undefined||cases_order == '-None-'||cases_order == NaN ||cases_order == 'NaN')){
        					alert('Please enter a value for Pounds/Case. Or, uncheck the checkbox to multiply cases by pounds for this item.')
        				}else{
        					tot_unit = parseFloat(cases_order)*parseFloat(lb_cs);
        					console.log('tot_unit',tot_unit)
        					currRec.setCurrentSublistValue({
        						sublistId: 'item',
                			    fieldId: 'quantity',
                			    value: tot_unit,
//                			    ignoreFieldChange: true
//                			    fireSlavingSync: true
                			});
        				}
    				}			
    		}

    	}catch(error){
    		console.log('error @ fieldChanged',error)
    	}

    }
    /**
     * Function to be executed after sublist is inserted, removed, or edited.
     *
     * @param {Object} scriptContext
     * @param {Record} scriptContext.currentRecord - Current form record
     * @param {string} scriptContext.sublistId - Sublist name
     *
     * @since 2015.2
     */
    // updated on 04/04/2019 for AN-43
    function sublistChanged(scriptContext) {
    	try{
    		var current_rec = scriptContext.currentRecord;
    		var sublist_name =scriptContext.sublistId;
    		var total_pound =0;
    		if(sublist_name == 'item'){
    			var numLines = current_rec.getLineCount({
    			    sublistId: 'item'
    			});
    			for(var i=0; i<numLines; i++){
        			
        			var item_internalId = current_rec.getSublistValue({
            			sublistId: 'item',
            			fieldId: 'item',
            			line: i
            		});
            		
            		var unit = current_rec.getSublistValue({
            			sublistId: 'item',
            			fieldId: 'quantity',
            			line: i
            		});


            		//search for item 
            		var itemSearchObj = search.create({
            			   type: "item",
            			   filters:
            			   [
            			      ["internalidnumber","equalto",item_internalId]
            			   ],
            			   columns:
            			   [
            			      search.createColumn({
            			         name: "itemid",
            			         sort: search.Sort.ASC,
            			         label: "Name"
            			      }),
            			      search.createColumn({name: "weight", label: "Weight"}),
            			      search.createColumn({name: "weightunit", label: "Weight Units"})
            			   ]
            			});
            			var searchResult = itemSearchObj.run().getRange({
            				start: 0,
            				end: 1
            			});
            			
            				for (var j = 0; j<searchResult.length; j++) {
                				var weight = searchResult[j].getValue({
                					name: "weight"
                				});
                				
                				var weight_unit = searchResult[j].getText({
                					name: "weightunit"
                				});
                				
                				
                				if(weight){
                					//to convert to pounds(lb)
                					if(weight_unit == 'kg'){
                    					weight = parseFloat(weight) * 2.205
                    				}
                    				else if(weight_unit == 'g'){
                    					weight = parseFloat(weight) / 453.592
                    				}
                    				else if(weight_unit == 'oz'){
                    					weight = parseFloat(weight) / 16
                    				}
                					
                					if(total_pound == null ||total_pound == '' ||total_pound == " "||total_pound == undefined  ||total_pound == '-None-'||total_pound == 0 || total_pound == '0' ||total_pound == NaN ||total_pound == 'NaN'){
                						
                						total_pound = parseFloat(weight) * parseFloat(unit)
                					}else{
                						total_pound = parseFloat(total_pound) + (parseFloat(weight)* parseFloat(unit))
                					}
                					
                        			current_rec.setValue({
                        			    fieldId: 'custbody_an48_jj_estpound',
                        			    value: total_pound,
//                        			    ignoreFieldChange: true,
//                        			    fireSlavingSync: true
                        			});
                				}
                			}
    			}
    			 
            			
        	}

    	}catch(e){
    		console.log('error @ sublistChanged',e)
    	}

    }
    
    


    return {
        pageInit: pageInit,
        rowMaterialTag: rowMaterialTag,
        print_action:print_action,
        sublistChanged:sublistChanged,
        fieldChanged:fieldChanged
    };
    
});

Leave a comment

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