Add discounts in item line level of a transaction.

Jira Code: SDC-1 Inline Discount System

In order to apply discounts to items individually in a transaction, a custom column can be used. The user can input the discount they wishes to apply to the item in the custom column. Tax is also applied to the disocunt amount. Here discount calculation is restricted to only specific forms using a client script pageinit function. A client script field change function is used to achieve the calculations when the user changes discount. Also, a user event script is used to achieve the after save calculations.

Client Script Pageinit - to set forms
/*
 * File name : JJ PageInit Inline Discount.js
 * 
 * Remove discount line on edit
 *
 * 
 * Script:Client 1.0  
 *
 * Author: Jobin and Jismi IT Services LLP
 * Date : 28 September 2017
 * Algorithm
 On pageInit(edit action)
 Remove discount line
 */

//forms internal id
var CUSTOM_SO_FORM_ID = 100;
var CUSTOM_CS_FORM_ID = 101;
var CUSTOM_CM_FORM_ID = 102;
var CUSTOM_ES_FORM_ID = 103;
var CUSTOM_IN_FORM_ID = 104;
var CUSTOM_RA_FORM_ID = 106;
var CUSTOM_RA2_FORM_ID = 114;
// Discount Item internal Id
var DISCOUNT_ITEM = 23;
function onPageInit() {
	try {
		var customForm = nlapiGetFieldValue('customform');
		if ((customForm == CUSTOM_SO_FORM_ID)
				|| (customForm == CUSTOM_CS_FORM_ID)
				|| (customForm == CUSTOM_CM_FORM_ID)
				|| (customForm == CUSTOM_ES_FORM_ID)
				|| (customForm == CUSTOM_IN_FORM_ID)
				|| (customForm == CUSTOM_RA_FORM_ID)
				|| (customForm == CUSTOM_RA2_FORM_ID)) {

			
			var discountIndex = 0;
			// get index of discount line
			discountIndex = nlapiFindLineItemValue('item', 'item',
					DISCOUNT_ITEM);
			nlapiLogExecution('DEBUG', 'pageInit Error', discountIndex);
			if (discountIndex > 0) {
				nlapiRemoveLineItem('item', discountIndex);

			}
		}
	} catch (e) {
		nlapiLogExecution('DEBUG', 'error' + e);
	}

}
Client script field change - to perform calculations when user changes the calculation.
/*
 * File name : JJ_CS_Inline_Discount_v2.js
 * 
 * Add inline discount feature to the applied record
 * Dependencies :JJ UE Inline Discount
 * 
 * Script:Client 1.0  
 *
 * Author: Jobin and Jismi IT Services LLP
 * Date : 6 September 2017
 *Algoritham

 On Save (Create action)
 Calculate discountAmt and discountTax
 Create entry discount item with price level : custom
 taxAmount : - Discount tax
 amount: - discount amount

On pageInit(edit action)
Remove discount line

Onsave(Edit action)
Do same action in create

on filedchange of entity change discount % and discount tax
on field change of discount% and discount tax update respective values

 * 
 */


// Discount Item internal Id
var DISCOUNT_ITEM = 23;
var DISCOUNT_PRICE_LEVEL = -1;
var DISCOUNT_TAX_CODE = 5;
//forms internal id
var CUSTOM_SO_FORM_ID = 100;
var CUSTOM_CS_FORM_ID = 101;
var CUSTOM_CM_FORM_ID = 102;
var CUSTOM_ES_FORM_ID = 103;
var CUSTOM_IN_FORM_ID = 104;
var CUSTOM_RA_FORM_ID = 106;
var CUSTOM_RA2_FORM_ID = 114;




function fieldChanged(type, name, linenum) {
	var customForm = nlapiGetFieldValue('customform');
    if((customForm == CUSTOM_SO_FORM_ID) || (customForm == CUSTOM_CS_FORM_ID) || (customForm == CUSTOM_CM_FORM_ID) || (customForm == CUSTOM_ES_FORM_ID) || (customForm == CUSTOM_IN_FORM_ID) || (customForm == CUSTOM_RA_FORM_ID)|| (customForm == CUSTOM_RA2_FORM_ID)) 
    	{
    	
    try {

//        if (name == 'entity') {
//            var count = nlapiGetLineItemCount('item');
//            if (count > 0) {
//                reviceCalculation();
//            }
//        }

        if (type == 'item' && name == 'custcol_disc_percentage') {
            var discPercentage = nlapiGetCurrentLineItemValue('item', 'custcol_disc_percentage');
            console.log("discPercentage",discPercentage)
            var amount = nlapiGetCurrentLineItemValue('item', 'amount');
            var discountedamount = amount;
            if (discPercentage != null && discPercentage != ''&& discPercentage!=0 && amount != '') {
                discAmt = (parseFloat(amount) * (parseFloat(discPercentage))) / 100;
                console.log("discAmt",discAmt)
            }
           else{
           	discAmt = 0;
           }
            
            discountedamount = parseFloat(amount) - parseFloat(discAmt);
            nlapiSetCurrentLineItemValue('item', 'custcol_jj_discount_amount', discAmt, false, false);
            nlapiSetCurrentLineItemValue('item', 'custcol_jj_total2', discountedamount, false, false);
        }
        if (type == 'item' && name == 'custcol_jj_discount_amount') {
            var discountAmount = nlapiGetCurrentLineItemValue('item', 'custcol_jj_discount_amount');
            var amount = nlapiGetCurrentLineItemValue('item', 'amount');
            var percent = parseFloat(discountAmount) * 100 / parseFloat(amount);
            percent = Math.round(percent);
            var discountedamount = parseFloat(amount) - parseFloat(discountAmount);
            nlapiSetCurrentLineItemValue('item', 'custcol_disc_percentage', percent, false, false);
            nlapiSetCurrentLineItemValue('item', 'custcol_jj_total2', discountedamount, false, false);

        }
        if (type == 'item' && (name == 'quantity' || name == 'amount'|| name == 'rate' )) {

            var discPercentage = nlapiGetCurrentLineItemValue('item', 'custcol_disc_percentage');
            if (discPercentage == '') {
//                var entityId = nlapiGetFieldValue('entity');
//                if (entityId && entityId != null) {
//                    discPercentage = nlapiLookupField('customer', entityId, 'custentity_disc_percentage');
//
//                }
            	discPercentage=0;
                
            }

            var amount = nlapiGetCurrentLineItemValue('item', 'amount');
            var discountedamount = amount;
            if (discPercentage != null && discPercentage != ''&& discPercentage!=0 && amount != '') {
                discAmt = (parseFloat(amount) * (parseFloat(discPercentage))) / 100;

            }
            else{
               	discAmt = 0;
               	
               }
            if(amount == ''){
            	amount=0;
            }
             discountedamount = parseFloat(amount) - parseFloat(discAmt);
            nlapiSetCurrentLineItemValue('item', 'custcol_jj_total2', discountedamount, false, false);
            nlapiSetCurrentLineItemValue('item', 'custcol_disc_percentage', discPercentage, false, false);
            nlapiSetCurrentLineItemValue('item', 'custcol_jj_discount_amount', discAmt, false, false);

        }
        if(type =='item' && name =='tax1amt'){
    		var amount = nlapiGetCurrentLineItemValue('item', 'amount');
    		var taxamount = nlapiGetCurrentLineItemValue('item', 'tax1amt');
    		var taxrate1  = parseFloat(taxamount) * 100/ parseFloat(amount);
    		taxpercent = Math.round(taxrate1 );
    		nlapiSetCurrentLineItemValue('item','taxrate1',taxpercent,false,false);	
    	}
        if(type =='item' && name =='price'){
        	var pricedisplay  = nlapiGetCurrentLineItemValue('item', 'price');
        	if(pricedisplay=='-1'){
        		//nlapiSetCurrentLineItemValue('item', 'custcol_disc_percentage', 0, false, false);
                nlapiSetCurrentLineItemValue('item', 'custcol_jj_discount_amount', 0, false, false);
                //reviceCalculation();
        	}
        	
        }


    } catch (e) {
        nlapiLogExecution('DEBUG', 'fieldChanged error' + e);
    }
   }
    return true;
}



User event script- to perform after save calculations

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
define(['N/record','N/search','N/ui/serverWidget','N/file'],

function(record,search,serverWidget,file) {
   
	  /**
     * 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{
    		
    		
    		//forms internal id
        	var CUSTOM_SO_FORM_ID = 100;
        	var CUSTOM_CS_FORM_ID = 101;
        	var CUSTOM_CM_FORM_ID = 102;
        	var CUSTOM_ES_FORM_ID = 103;
        	var CUSTOM_IN_FORM_ID = 104;
        	var CUSTOM_RA_FORM_ID = 106;
        	var CUSTOM_RA2_FORM_ID = 114;
        	// Discount Item internal Id
        	var DISCOUNT_ITEM = 23;
        	if (scriptContext.type == 'view')
        	{
        		log.debug({
        			title:'view'
        		});
        		var html = '<script src="https://system.eu2.netsuite.com/core/media/media.nl?id=931&c=4880645&h=fbe8bfae60b12d59f8a8&_xt=.js"></script><SCRIPT language="JavaScript" type="text/javascript">';
        		html +="document.arrive('#item_splits', function() { var DISCOUNT_ITEM_NAME = 'Inline Discount'; var tbl = document.getElementById('item_splits'); console.log('Removed'+tbl); var rows = tbl.getElementsByTagName('tr'); for (var row = rows.length-1; row> 1; row--) { var itemName = rows[row].cells[0].innerText;\n if(itemName == DISCOUNT_ITEM_NAME){ rows[row].style.display ='none';return; }} });";
        		html += '</SCRIPT>';
        		//var inline = form.addField('custpage_alertmode', 'inlinehtml', '',null,null); 
        		var inline=scriptContext.form.addField({
        		    id : 'custpage_alertmode',
        		    type : serverWidget.FieldType.INLINEHTML,
        		    label : 'text'
        		});
        		inline.defaultValue = html;
        		
        	}
        	
    	}
    	catch (e) {
			log.debug({
    			title:'error@b4load',
    			details:e
    		});
		}
    	
    }


    
    /**
     * 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) {
    	log.debug({title:'aftersubmit'});
    	//Discount Item internal Id
        var DISCOUNT_ITEM = 23;
        var DISCOUNT_PRICE_LEVEL = -1;
        var DISCOUNT_TAX_CODE = 5;

        //forms internal id
        var CUSTOM_SO_FORM_ID = 100;
        var CUSTOM_CS_FORM_ID = 101;
        var CUSTOM_CM_FORM_ID = 102;
        var CUSTOM_ES_FORM_ID = 103;
        var CUSTOM_IN_FORM_ID = 104;
        var CUSTOM_RA_FORM_ID = 106;
        var CUSTOM_RA2_FORM_ID = 114;
        
        try{
        	 var customForm = scriptContext.newRecord.getValue({
     			fieldId:'customform'
     		});
             if((customForm == CUSTOM_SO_FORM_ID) || (customForm == CUSTOM_CS_FORM_ID) || (customForm == CUSTOM_CM_FORM_ID) || (customForm == CUSTOM_ES_FORM_ID) || (customForm == CUSTOM_IN_FORM_ID) || (customForm == CUSTOM_RA_FORM_ID)|| (customForm == CUSTOM_RA2_FORM_ID)) 
             	{
             	try{
             		var record_type=scriptContext.newRecord.type;
             		var record_id=scriptContext.newRecord.id;
             		
             		switch (record_type) {   
                     case 'invoice':
                     	var currentrec = record.load({
             			    type: record.Type.INVOICE, 
             			    id: record_id,
             			    isDynamic: true,
             			});
                         break;
                     case 'salesorder':
                     	var currentrec = record.load({
             			    type: record.Type.SALES_ORDER, 
             			    id: record_id,
             			    isDynamic: true,
             			});
                     	 break;
                     case 'creditmemo':
                      	var currentrec = record.load({
              			    type: record.Type.CREDIT_MEMO, 
              			    id: record_id,
              			    isDynamic: true,
              			});
                         break;
                     case 'returnauthorization':
                       	var currentrec = record.load({
               			    type: record.Type.RETURN_AUTHORIZATION, 
               			    id: record_id,
               			    isDynamic: true,
               			});
                          break;
                     case 'estimate':
                        	var currentrec = record.load({
                			    type: record.Type.ESTIMATE, 
                			    id: record_id,
                			    isDynamic: true,
                			});
                           break;
                   
                     }		
                
             		
             // set discounted amount to all items
             		var count = currentrec.getLineCount({
         	            sublistId: 'item'
         	        });
                     for (var i = 0; i < count; i++) {
                     	var lineNum = currentrec.selectLine({
                      	    sublistId: 'item',
                      	    line: i
                      	}); 
                     	 var item_name = currentrec.getCurrentSublistValue({
         		            	sublistId: 'item',
         		                fieldId: 'itemtype'
                              });
                     	
                         var item_type=currentrec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'item'
                    });
               
    	        if((item_name!='EndGroup')&&(item_name!='Group')&&(item_type!=23)){
                         	 var discPercentage =  currentrec.getCurrentSublistValue({
          		            	sublistId: 'item',
          		                fieldId: 'custcol_disc_percentage'
                                  });
                         	 var amount = currentrec.getCurrentSublistValue({
          		            	sublistId: 'item',
          		                fieldId: 'amount'
                                  });
                         var discountedamount = amount;
                         if (discPercentage != null && discPercentage != ''&& discPercentage!=0 && amount != '') {
                             discAmt = (parseFloat(amount) * (parseFloat(discPercentage))) / 100;

                         }else{
                            	discAmt = 0;
                         	
                         }
                 
                         discountedamount = amount - discAmt;
                         currentrec.setCurrentSublistValue({
                 		    sublistId: 'item',
                 		    fieldId: 'custcol_jj_total2',
                 		    value: discountedamount,
                 		    ignoreFieldChange: true
                 		});
         	            
         	            currentrec.setCurrentSublistValue({
                 		    sublistId: 'item',
                 		    fieldId: 'custcol_jj_discount_amount',
                 		    value: discAmt,
                 		    ignoreFieldChange: true
                 		});
         	            
         	           
         	            currentrec.commitLine({
                 		    sublistId: 'item'
                 		});
                       }
                     }
             	}
                  catch(e){
         	   		
         	   		log.debug({
               		    title: 'error@try1', 
               		    details: e.message
               		    });
         	   	}
             	
             	
         	try {
                 var newObj = {};
                 var taxsummaryarray = new Array();
                 var count = currentrec.getLineCount({
     	            sublistId: 'item'
     	        });
                var item_name=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'itemtype',
                    line: 0
                    });
                
                 newObj.vatcode = currentrec.getSublistValue({
                     sublistId: 'item',
                     fieldId: 'taxcode_display',
                     line: 0
                     });

                 newObj.rate =  currentrec.getSublistValue({
         			sublistId: 'item',
         			fieldId: 'taxrate1',
         			line: 0
         			});

                 newObj.netamount =  currentrec.getSublistValue({
         			sublistId: 'item',
         			fieldId: 'amount',
         			line: 0
         			});
                 
                 newObj.totaltax = currentrec.getSublistValue({
         			sublistId: 'item',
         			fieldId: 'tax1amt',
         			line: 0
         			});
                 
                 newObj.discountedAmount =currentrec.getSublistValue({
         			sublistId: 'item',
         			fieldId: 'custcol_jj_total2',
         			line: 0
         			});
                 
                   if (parseFloat(newObj.discountedAmount) > 0) {
         			
         		}else{
         			newObj.discountedAmount = 0;
         		}
                   
                 if ((newObj.rate != null) && (newObj.rate != '') && (newObj.discountedAmount != '' || newObj.discountedAmount==0)) {
                 	
                         newObj.discountedAmtTax = ((parseFloat(newObj.discountedAmount) * (parseInt(newObj.rate))) / 100).toFixed(2);
                         

                   }
                 
                      
                 if(item_name!='Group'){
                    taxsummaryarray.push(newObj);
                }
                   
                log.debug("taxsummaryarray1",taxsummaryarray);
        
                 for (var index = 1; index < count; index++) {
                     taxsummaryarray = createTaxsummary(taxsummaryarray, index,currentrec);
                 }
                 log.debug("taxsummaryarray2",taxsummaryarray);
                 // find new tax summary if discount item is present
                 var discount_item=currentrec.getValue({
         			fieldId:'discountitem'
         		});
                 if((discount_item!='')&&(discount_item!=null)&&(discount_item!=undefined)){
                 	var discount_item_rate=currentrec.getValue({
             			fieldId:'discountrate'
             		});
                 	 var discount_item_taxcode1 = search.lookupFields({
     	        		    type: search.Type.ITEM,
     	        		    id: discount_item,
     	        		    columns: ['salestaxcode']
     	        		});
                    
     	            var discount_item_taxcode=discount_item_taxcode1.salestaxcode[0].text;
                   log.debug("discount_item_taxcode",discount_item_taxcode);
                     for (var i = 0; i < taxsummaryarray.length; i++) {
                     var taxObject = new Object();
                     taxObject = taxsummaryarray[i];
                      
                     var taxcode=taxObject.vatcode.split(":");
                     taxcode=taxcode[1];
                        
                     //taxcode=JSON.stringify(taxcode);
                    
                     if(taxcode==discount_item_taxcode){
                     	
                     	var new_discount=(parseFloat(taxObject.discountedAmount)*parseFloat(discount_item_rate))/100;
                     	new_discount=new_discount.toFixed(2);
                     	var new_discount1=parseFloat(new_discount)+parseFloat(taxObject.discountedAmount);
                     	
                     	var new_taxamt=(parseFloat(new_discount)*parseFloat(taxObject.rate))/100;
                     	new_taxamt=new_taxamt.toFixed(2);
                     	var new_taxamt1=parseFloat(new_taxamt)+parseFloat(taxObject.discountedAmtTax);
                     	new_taxamt1=parseFloat(new_taxamt1);
                     	
                     	var taxsummary_index=i;
                     	
                     }
                     
                  }
                 }
                 
                 var taxsummaryStr = "";
                 for (var i = 0; i < taxsummaryarray.length; i++) {
                     var taxObj = new Object();
                     taxObj = taxsummaryarray[i];
                     if ((i != 0) && (i != taxsummaryarray.length)) {
                         taxsummaryStr = taxsummaryStr + "**";
                     }
                     
                     if(taxObj.vatcode!=''){
                     	if(i==taxsummary_index){
                     		
                     		taxsummaryStr = taxsummaryStr + taxObj.vatcode + ',' + taxObj.rate + ',€' + new_discount1 + ',€' + new_taxamt1;
                     	}
                     	else{
                     		 taxsummaryStr = taxsummaryStr + taxObj.vatcode + ',' + taxObj.rate + ',€' + taxObj.discountedAmount + ',€' + taxObj.discountedAmtTax;
                     	}
                 
                     }
                     else{
                     	taxsummaryStr=taxsummaryStr +"tax";
                     }
                 }
                 currentrec.setValue({
             	    fieldId: 'custbody_jj_tax_summary',
             	    value: taxsummaryStr,
             	    ignoreFieldChange: true
             	});
             }  
         	catch (e) {
     	    	log.debug({
           		    title: 'error@try2', 
           		    details: e.message
           		    });
     	    }
             var calcObj = retriveDiscountSumObject(currentrec);
             log.debug({
        		    title: 'calcObj', 
        		    details: JSON.stringify(calcObj)
        		    });
             try{
             	  var discount_item= currentrec.getValue({
           			fieldId:'discountitem'
           		});
                   // find and set discount total if discount item is present
                   if((discount_item!='')&&(discount_item!=null)&&(discount_item!=undefined)){
                   	var discount_item_rate=currentrec.getValue({
               			fieldId:'discountrate'
               		});
                   	var item_count = currentrec.getLineCount({
           	            sublistId: 'item'
           	        });
                   
                   	var totalamount=0.00;
                   	for (var i = 0; i < item_count; i++) {
                 
                    var item_name=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'itemtype',
                    line: i
                    });
                 
    	    	    var item_type=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'item',
                    line: i
                    });
               
    	       
    	         if((item_name!='EndGroup')&&(item_name!='Group')&&(item_type!=23)){
                   		var totalamount1=currentrec.getSublistValue({
                   			sublistId: 'item',
                   			fieldId: 'custcol_jj_total2',
                   			line: i
                   			});
                   		totalamount1=parseFloat(totalamount1);
                   		totalamount+=totalamount1;
                   	}
                    }
                   	var discount_item_total=(parseFloat(totalamount)* parseFloat(discount_item_rate))/100;
                   	discount_item_total=discount_item_total.toFixed(2);
                   	var total_discount=parseFloat(discount_item_total)+parseFloat(calcObj.discountSum);
                   	    total_discount=Math.abs(total_discount);
                   	// find new subtotal after discount
                   	var new_subtotal=(parseFloat(calcObj.actualSubtotal)- parseFloat(total_discount)).toFixed(2);
                   	currentrec.setValue({
                   	    fieldId: 'custbody_jj_subtotal_after_discount',
                   	    value: new_subtotal,
                   	    ignoreFieldChange: true
                   	});
                   	
                   	currentrec.setValue({
                   	    fieldId: 'custbody_jj_discount_total',
                   	    value: -total_discount,
                   	    ignoreFieldChange: true
                   	});
                   	
                   	
                   	
                   	
                   }
                   else{
                   	calcObj.discountSum=Math.abs(calcObj.discountSum);
                   	// find new subtotal after discount
                   	var new_subtotal=(parseFloat(calcObj.actualSubtotal)-parseFloat(calcObj.discountSum)).toFixed(2);
                   	
                   	currentrec.setValue({
                   	    fieldId: 'custbody_jj_subtotal_after_discount',
                   	    value: new_subtotal,
                   	    ignoreFieldChange: true
                   	});
                   	
                   	currentrec.setValue({
                   	    fieldId: 'custbody_jj_discount_total',
                   	    value: -calcObj.discountSum,
                   	    ignoreFieldChange: true
                   	});
           	    
                   }
                   log.debug("calcObj.actualSubtotal1",calcObj.actualSubtotal);
                   currentrec.setValue({
               	    fieldId: 'custbody_jj_actual_subtotal',
               	    value: calcObj.actualSubtotal,
               	    ignoreFieldChange: true
               	});
                 	if(calcObj.discountSum>0){
                 		 var countt = currentrec.getLineCount({
               	            sublistId: 'item'
               	        });
                 		 var lineNum1 = currentrec.selectNewLine({
                       	    sublistId: 'item'
                       	});
                 		 var createdfrom=currentrec.getValue({
                 			 fieldId:'createdfrom'
                 		 });
                       	    log.debug('createdfrom',createdfrom);
                       	 var discountIndex = currentrec.findSublistLineWithValue({
         				    sublistId: 'item',
         				    fieldId: 'item',
         				    value: 23
         				});
                       	log.debug('discountIndex',discountIndex);
                       	if((createdfrom=='')||(discountIndex<0)){
                       		log.debug('discount line');
                       	 // set the item and location values on the currently selected line
                       		currentrec.setCurrentSublistValue({
                       		    sublistId: 'item',
                       		    fieldId: 'item',
                       		    value: DISCOUNT_ITEM,
                       		    ignoreFieldChange: true
                       		});
                       	 var inlinediscount_item_taxcode1 = search.lookupFields({
      	        		    type: search.Type.ITEM,
      	        		    id: 23,
      	        		    columns: ['salestaxcode']
      	        		});
      	                 var inlinediscount_item_taxcode=inlinediscount_item_taxcode1.salestaxcode[0].value;
                       	    log.debug('inlinediscount_item_taxcode',inlinediscount_item_taxcode);
                       	    currentrec.setCurrentSublistValue({
                       		    sublistId: 'item',
                       		    fieldId: 'taxcode',
                       		    value: inlinediscount_item_taxcode,
                       		    ignoreFieldChange: true
                       		});
                       	    currentrec.setCurrentSublistValue({
                       		    sublistId: 'item',
                       		    fieldId: 'price',
                       		    value: DISCOUNT_PRICE_LEVEL,
                       		    ignoreFieldChange: true
                       		});
                       	    currentrec.setCurrentSublistValue({
                       		    sublistId: 'item',
                       		    fieldId: 'amount',
                       		    value: -calcObj.discountSum,
                       		    ignoreFieldChange: true
                       		});
                       	    currentrec.setCurrentSublistValue({
                       		    sublistId: 'item',
                       		    fieldId: 'tax1amt',
                       		    value: - parseFloat(calcObj.discountTaxSum),
                       		    ignoreFieldChange: true
                       		});
                       	    //commit the line to the database
                          	    currentrec.commitLine({
                          		    sublistId: 'item'
                          		});
                       	}
                       	   
               }
                 	var recordId = currentrec.save({
         			    enableSourcing: false,
         			    ignoreMandatoryFields: true
         			});
               //avoid the standard NetSuite warning message when navigating away
//                   if (window.onbeforeunload) {
//                       window.onbeforeunload = function() {
//                           null;
//                       };
//                   };
             }
             catch (e) {
     	    	log.debug({
           		    title: 'error@try3', 
           		    details: e.message
           		    });
     	    }
           
         }
             
        }
        catch(e){
	   		
	   		log.debug({
      		    title: 'error@try', 
      		    details: e.message
      		    });
	   	}
       
        
    }
    /***
     * Create tax summary here
     * @param taxsummaryarray
     * @param count
     * @returns
     */
    function createTaxsummary(taxsummaryarray, index,currentrec) {

        try {
            var item_name=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'itemtype',
                    line: index
                    });
            if((item_name!='EndGroup')&&(item_name!='Group')){
                var vatcode = currentrec.getSublistValue({
                sublistId: 'item',
                fieldId: 'taxcode_display',
                line: index
                });
            
            var netamount = currentrec.getSublistValue({
                sublistId: 'item',
                fieldId: 'amount',
                line: index
                });
            
            var totaltax = currentrec.getSublistValue({
                sublistId: 'item',
                fieldId: 'tax1amt',
                line: index
                });
            
            var rate =  currentrec.getSublistValue({
                sublistId: 'item',
                fieldId: 'taxrate1',
                line: index
                });
           
            var discountedAmount =currentrec.getSublistValue({
                sublistId: 'item',
                fieldId: 'custcol_jj_total2',
                line: index
                });
            
            
            if((netamount=='')||(netamount==null)){
            	netamount=0;
            }
            if((totaltax=='')||(totaltax==null)){
            	totaltax=0;
            }
           
            if (parseFloat(discountedAmount) > 0) {
    			
    		}else{
    			discountedAmount = 0;
    		}
           
            var discountedAmtTax = 0;
            if ((rate != null) && (rate != '') && (discountedAmount != '')) {
                    discountedAmtTax = (parseFloat(discountedAmount) * (parseInt(rate))) / 100;

                }

            var flag=0;
            for (var taxIndex = 0; taxIndex < taxsummaryarray.length; taxIndex++) { 
                var vatObject = taxsummaryarray[taxIndex];
               
                if (vatcode == vatObject.vatcode)
                	{
                	vatObject.netamount = (parseFloat(vatObject.netamount) + parseFloat(netamount)).toFixed(2);
                    vatObject.totaltax = (parseFloat(vatObject.totaltax) + parseFloat(totaltax)).toFixed(2);
                    vatObject.discountedAmount = (parseFloat(vatObject.discountedAmount) + parseFloat(discountedAmount)).toFixed(2);
                    vatObject.discountedAmtTax = (parseFloat(vatObject.discountedAmtTax) + parseFloat(discountedAmtTax)).toFixed(2);
                    taxsummaryarray[taxIndex] = vatObject;
                	 flag=1;
                	}
          
            }
           if(flag==0)
            {
        	   var newObj = new Object();
               newObj.vatcode = vatcode;
               newObj.rate = rate;
               newObj.netamount = parseFloat(netamount).toFixed(2);
               newObj.totaltax = parseFloat(totaltax).toFixed(2);
               newObj.discountedAmount = parseFloat(discountedAmount).toFixed(2);
               newObj.discountedAmtTax = parseFloat(discountedAmtTax).toFixed(2);
               taxsummaryarray.push(newObj);
           }
            }
            
          //console.log(taxsummaryarray);
           return taxsummaryarray;
           
        } catch (e) {
           
            log.debug({
      		    title: 'error@createtaxsummary', 
      		    details: e.message
      		    });
        }

    }
    
    /***find disoucnt sum***/
    
    function retriveDiscountSumObject(currentrec) {
    	try{
    		var calcObj = new Object();
    	    var discountSum = 0;
    	    var discountTaxSum = 0;
    	    var actualSubtotal = 0;
    	   
    	    var count = currentrec.getLineCount({
	            sublistId: 'item'
	        });
    	    for (var i = 0; i < count; i++) {
    	    	var item_name=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'itemtype',
                    line: i
                    });
                 log.debug("item_name",item_name);
    	    	var item_type=currentrec.getSublistValue({
                    sublistId: 'item',
                    fieldId: 'item',
                    line: i
                    });
               
    	        if((item_name!='EndGroup')&&(item_name!='Group')&&(item_type!=23)){
    	    		var amount1=currentrec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        line: i
                        });
    	    		log.debug("amount1",amount1);
    	    		if((amount1=='')||(amount1==null)){
    	        		amount1=0;
    	        	}
    	        	actualSubtotal = parseFloat(actualSubtotal) + parseFloat(amount1);
    	        	 var taxRate = currentrec.getSublistValue({
                         sublistId: 'item',
                         fieldId: 'taxrate1',
                         line: i
                         });
    	        	 
    	        	 if((taxRate=='')||(taxRate==null)){
    	        		 taxRate=0;
    	         	}
    	        	  taxRate=parseFloat(taxRate);
    	        	 
    	           
    	            var discountAmount = currentrec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_jj_discount_amount',
                        line: i
                        });
    	            
    	            if((discountAmount=='')||(discountAmount==null)){
    	            	discountAmount=0;
    	        	}
    	            discountAmount=parseFloat(discountAmount);
    	            
    	            var discTaxAmt = parseFloat((taxRate * discountAmount) / 100).toFixed(2);
    	            discountTaxSum = parseFloat(discountTaxSum) + parseFloat(discTaxAmt);
    	            discountSum = parseFloat(discountSum) + parseFloat(discountAmount);
    	    	}
    	    	

    	    }
    	    calcObj.discountSum = parseFloat(discountSum).toFixed(2);
    	    calcObj.discountTaxSum = parseFloat(discountTaxSum).toFixed(2);
    	    calcObj.actualSubtotal = parseFloat(actualSubtotal).toFixed(2);
    	    return calcObj;
    	}
    	catch(e){
    		 
    		 log.debug({
       		    title: 'error@retriveDiscountSumObject', 
       		    details: e.message
       		    });
    	}
    }
    
    return {
    	beforeLoad:beforeLoad,
        afterSubmit: afterSubmit,
        retriveDiscountSumObject:retriveDiscountSumObject,
        createTaxsummary:createTaxsummary
        //beforeSubmit:beforeSubmit
    };
    
});


Leave a comment

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