/**
 * @author : Akhilesh Sikarwar 
 * @Version : 1.0
 * Date : 02/06/13
 */
package ibase.webitm.ejb.fin.adv;


//import ibase.edi.client.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;

import java.util.Properties;
import org.omg.CORBA.ORB;
import java.util.*;
import javax.ejb.*;
import ibase.system.config.*;


//import javax.ejb.Stateless;
import javax.naming.InitialContext;

import org.apache.poi.hssf.record.formula.functions.Today;
//@Stateless
public class CalculateCommission
{


	public String CalCommission(String invoiceId , String callModule , String tranId ,String postCrn ,String postJv ,String xtraParams, Connection conn ) throws Exception
	{
		String commCalc = "";
		String errString = "";
		String sql = "";
		String sql1 = "";
		String refSer = "";
		String invno = "";
		String invFound = "";

		double checkAmt = 0.0;
		double checkAdjAmt = 0.0;


		int facter = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;

		FinCommon finCommon = null;
		finCommon = new  FinCommon();
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();


		try {
			commCalc = finCommon.getFinparams("999999", "COMM_CALC", conn);
			if(!("I".equalsIgnoreCase(commCalc)) || !("R".equalsIgnoreCase(commCalc)) || !("N".equalsIgnoreCase(commCalc))|| !("P".equalsIgnoreCase(commCalc)))

			{
				errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
				return errString;
			}
			else
			{
				if("I".equalsIgnoreCase(callModule))
				{
					if("I".equalsIgnoreCase(commCalc))

					{	
						facter = 1;
						//ls_errcode = gbf_comm_credit_note(as_invoiceid,lc_factor,as_post_crn,as_call_module)
					}
					else if("R".equalsIgnoreCase(commCalc))
					{
						//ls_errcode = gbf_comm_journal(as_invoiceid,as_post_jv,as_call_module)
					}
					else if("P".equalsIgnoreCase(commCalc))
					{
						//ls_errcode = gbf_prov_comm_credit_note(as_invoiceid,lc_factor,as_post_crn,as_call_module)
					}
				}
				else if("R".equalsIgnoreCase(callModule)) 
				{
					if("P".equalsIgnoreCase(commCalc))

					{
						// called from receipt
						sql = "select rcpdet.ref_ser, rcpdet.ref_no, ( rcpdet.rcp_amt - ( rcpdet.tax_amt * rcpdet.rcp_amt / rcpdet.net_amt ) ) / (inv_amt - invoice.disc_amt)" +
								"from rcpdet, invoice where rcpdet.ref_no = invoice.invoice_id and tran_id = ?" +
								" and ( ref_ser = 'S-INV' || ref_ser like 'R-IBC%'  )";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, tranId);
						rs = pstmt.executeQuery();
						while(rs.next())

						{
							refSer = rs.getString(1);
							invno = rs.getString(2);
							facter = rs.getInt(3);

							invFound = "N";
							for(int cnt = 1 ;invno.length() > 0;cnt++)
							{
								if(invno.equalsIgnoreCase(invFound));
								invFound = "Y";
								break;
							}
							// create debit note for invoice = ls_invno and factor = lc_factor

							sql1 = "select case when rcp_amt is null then 0 else rcp_amt end from rcpdet" +
									"where tran_id = ? and ref_ser = ? and ref_no  = ?";

							pstmt1 = conn.prepareStatement(sql1);
							pstmt1.setString(1, tranId);
							pstmt1.setString(2, refSer);
							pstmt1.setString(3, invno);
							rs1 = pstmt1.executeQuery();
							while(rs1.next())

							{
								checkAmt = rs1.getDouble(1);

							}
							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;	

							sql1 = " Select (TOT_AMT - ADJ_AMT) from receivables  where tran_ser = ? and ref_no = ?";
							pstmt1 = conn.prepareStatement(sql1);
							pstmt1.setString(1, refSer);
							pstmt1.setString(2, invno);
							rs1= pstmt1.executeQuery();
							while(rs1.next())

							{
								checkAdjAmt = rs1.getDouble(1);
							}

							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;	

							if(Math.round(checkAdjAmt) ==0)
							{
								errString = commDebitNote(invno, facter, postCrn, callModule,xtraParams, conn);
								return errString;

							}



						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;	

					}
					if("R".equalsIgnoreCase(commCalc) || "P".equalsIgnoreCase(commCalc) && (errString == null || errString.trim().length() == 0))
					{
						sql = "select rcpdet.ref_ser, rcpdet.ref_no, ( rcpdet.rcp_amt - ( rcpdet.tax_amt * rcpdet.rcp_amt / rcpdet.net_amt ) ) / (inv_amt - invoice.disc_amt)" +
								"from rcpdet, invoice where rcpdet.ref_no = invoice.invoice_id and tran_id = ?" +
								" and ( ref_ser = 'S-INV' 	OR ref_ser like 'R-IBC%'  )";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, tranId);
						rs = pstmt.executeQuery();
						while(rs.next())

						{
							refSer = rs.getString(1);
							invno = rs.getString(2);
							facter = rs.getInt(3);


							sql1 = "Select case when rcp_amt is null then 0 else rcp_amt end from rcpdet where tran_id = ?" +
									" and ref_ser = ? and  ref_no  = ?";
							pstmt1 = conn.prepareStatement(sql1);
							pstmt1.setString(1, tranId);
							pstmt1.setString(2, refSer);
							pstmt1.setString(3, tranId);
							rs1 = pstmt1.executeQuery();
							while(rs1.next())

							{
								checkAmt = rs1.getDouble(1);
							}
							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;	

							sql1 = "Select (TOT_AMT - ADJ_AMT)  from receivables where tran_ser = ? and 	ref_no = ?" ;
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1, refSer);
							pstmt1.setString(2, tranId);
							rs1 = pstmt1.executeQuery();
							while(rs1.next())

							{
								checkAdjAmt = rs1.getDouble(1);
							}

							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;	

							if(Math.round(checkAdjAmt) == 0)
							{
								errString = commCrditNote(invoiceId, facter, postCrn, callModule,xtraParams, conn);
								return errString;
							}

						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;	

					}
				}
				else if("SR".equalsIgnoreCase(callModule) && "P".equalsIgnoreCase(commCalc))
				{
					sql = " Select sum((case when tot_amt is null then 0 else tot_amt end) - (case when adj_amt is null then 0 else adj_amt end)) from receivables " +
							"where (tran_ser = 'S-INV' or tran_ser like 'R-IBC%') and  ref_no = ?";

					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranId);
					rs = pstmt.executeQuery();
					while(rs.next())

					{
						checkAdjAmt = rs.getDouble(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;	

					if(Math.round(checkAdjAmt)> 0)
					{

						errString = commDebitNote(tranId, facter, postCrn, callModule ,xtraParams, conn);
						return errString;

					}

				}

			}

		} catch (ITMException e) {
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}

		return errString;
	}


	private String commDebitNote(String invno, int factor, String post,String calledFrom,String xtraParams, Connection conn) throws Exception

	{	

		String commCalc = "";
		String errString = "";
		String keyString = "";
		String sql = "";
		String refSer = "";
		String acctcodeExp = "";
		String cctrcodeExp = "";
		String invFound = "";
		String sretId = "";
		String sreCurrCode = "";
		String sreSiteCode = "";
		String tranIdCrn = "";
		String invoiceNo = "";
		String acctCodeCf = "";
		String cctrCodeCf = "";
		String saleOrder = "";
		String commPerc = "";
		String commPerc1 = "";
		String commperc2 = "";
		String commHdr = "";
		String crTerm  = "";
		String taxClass  = "";
		String taxChap = "";
		String invoiceId = "";
		String refLineNo = "";
		String itemSer = "";
		String currCode = "";
		String finEntity = "";
		String siteCode = "";
		String salesPers = "";
		String dlvTerm = "";
		String sorderNo = "";
		String currCodeSp = "";
		//String exchRateSp = ""; 
		String commPercOn = "";		 
		//String commPerc = "";
		String oldSp = "";
		String currcdSpOld = "";
		String acctCode = "";
		String cctrCodeAp = "";
		String insReqd  = "";
		String frtReqd  = "";
		String refser = "";
		String siteCodeCd = "";
		String currCodeBase = "";
		String tranId = "";
		String idDate = "";
		String tranType = "";
		String oldsp = "";
		String currcodeSp ="";
		String fchgType = "";
		String acctcodeDeduct = "";
		String cctrcodeDeduct = "";
		String transer = "DRNINV";
		String	trnofld = "tran_id";
		String remarks = "Agst Receipt No ";
		String rcpRefser = "";
		String autoTranId = "";
		String curr = "";
		String site = "";
		String invibcagen = "";
		String sundryCode = "";
		String sundryType = "";
		String acct = "";
		String cctr = "";
		String siteCodePay = "";
		String linkType = "";
		String acctCodePay = "";
		String cctrCodePay = "";
		String acctCodeRcp = "";
		String cctrCodeRcp = "";
		String ibcaId = "";
		String itemCode = "";
		String commFrt = "";
		String commInsu = "";
		String finent = "";
		String taxEnv = "";
		String arg2 = "";
		String arg1 = "";
		String finEntityFr = "";
		String refType = "";
		String finEntityTo = "";
		String xmlString = "";
		StringBuffer xmlBuff = null;
		String loginEmpCode = "";
		double commAmt = 0.0;
		double ordAmt = 0.0;
		double insuAmt = 0.0;
		double invAmt = 0.0;
		double frtAmt = 0.0; 
		double exchRate = 0.0;
		double rcpAmount = 0.0;
		double checkAmt = 0.0;
		double checkAdjAmt = 0.0;
		double sretNetAmt = 0.0;
		double sretExchRate = 0.0;
		double netAmt = 0.0;
		double adjAmt = 0.0 ;
		double sretPerc = 0.0;
		double jvExchrate = 0.0;
		double crntExchrate = 0.0;
		double exchRateSp = 0.0;
		double rcpExchRateTot = 0.0;
		double lineNoInv  = 0.0;
		double invLineNo = 0.0;
		double invNetamt = 0.0 ;
		double amount = 0.0;
		double drcrAmt = 0.0;
		double taxAmt  = 0.0;
		double exchRateDiffTot = 0.0 ;
		double exchRateDiff = 0.0 ;
		double totNetAmt = 0.0;
		double netSAmt = 0.0;
		double expAmt = 0.0;
		double finChg = 0.0;
		double drcrmt = 0.0;
		double amountBc = 0.0; 
		double exch = 0.0;
		double amtInv = 0.0;
		double rateStduom = 0.0;
		double invDisc = 0.0;
		double discount = 0.0;

		PreparedStatement pstmt = null;
		ResultSet rs = null;

		SimpleDateFormat sdf  = null;
		GenericUtility genericUtility = null;

		ValidatorEJB validatorEJB = null;
		validatorEJB = new ValidatorEJB();
		java.util.Date  tranDate = null;
		java.util.Date  effDate = null;
		java.util.Date  dueDate =null;
		java.util.Date date = new java.util.Date();
		java.util.Date chgDate = new java.util.Date();
		java.util.Date taxDate = chgDate;


		loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");

		int facter = 0;
		int totalrow = 0;
		int crdays = 0;
		int count = 0;
		int day = 0;
		int slineNo = 0;
		int lineNo = 0;

		FinCommon finCommon = null;
		finCommon = new  FinCommon();
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		HashMap commMap = new HashMap();
		ArrayList commtList = new ArrayList();


		try {


			sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());

			sql = " select key_string from transetup where upper(tran_window) = 'W_DRCRINV'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())		
			{
				keyString = rs.getString(1);
			}
			else
			{
				sql = " select key_string from transetup where upper(tran_window) = 'GENERAL'";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					keyString = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			// get the a/c code for commission expense a/c
			if("I".equalsIgnoreCase(calledFrom) || "SR".equalsIgnoreCase(calledFrom))
			{
				acctcodeExp = finCommon.getFinparams("999999", "COMM_EXP_ACCT", conn);
				if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
				{
					errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
					return errString;

				}else

				{
					cctrcodeExp = finCommon.getFinparams("999999", "COMM_EXP_CCTR", conn);
					if("NULLFOUND".equalsIgnoreCase(cctrcodeExp))
					{
						errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
						return errString;

					}
				}
			}
			else
			{
				acctcodeExp = finCommon.getFinparams("999999", "SAL_COM_PROV_REV_ACT", conn);
				if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
				{
					errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
					return errString;

				}
				cctrcodeExp = finCommon.getFinparams("999999", "SAL_COM_PROV_REV_CTR", conn);
				if("NULLFOUND".equalsIgnoreCase(cctrcodeExp))
				{
					errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
					return errString;

				}
				else if(cctrcodeExp == null) cctrcodeExp = "";		

			}

			commCalc = finCommon.getFinparams("999999", "COMM_CALC", conn);
			if(("SR".equalsIgnoreCase(calledFrom)) && ("P".equalsIgnoreCase(commCalc)))
			{
				sretId = invno;
				invno = "";

				sql = "select invoice_id, net_amt, curr_code, exch_rate, site_code, tran_id__crn" +
						"from sreturn where tran_id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, sretId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					invno = rs.getString("invoice_id");
					sretNetAmt = rs.getDouble("net_amt");
					sreCurrCode = rs.getString("curr_code");
					sretExchRate = rs.getDouble("exch_rate");
					sreSiteCode = rs.getString("site_code");
					tranIdCrn = rs.getString("tran_id__crn");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(invno==  null || invno.trim().length() == 0)
				{
					return errString;
				}

				sql = "select net_amt from invoice  where invoice_id= ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, invno);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					netAmt = rs.getDouble("net_amt");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(tranIdCrn != null && tranIdCrn.trim().length() > 0)
				{
					sql = "select amount  from drcr_rcp where tran_id= ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranIdCrn);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						rcpAmount = rs.getDouble("amount");
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					sretNetAmt = rcpAmount;
				}

			}
			//  get acct_code for currency fluctuation 
			invoiceNo = invno;
			sql = "select acct_code__cf, cctr_code__cf from bank where bank_code =(Select bank_code from site where" +
					" site_code = (select site_code from invoice where invoice_id = ?))";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, invoiceNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				acctCodeCf = rs.getString("acct_code__cf");
				cctrCodeCf = rs.getString("cctr_code__cf");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql = "select sale_order from invoice where invoice_id = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, invoiceNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				saleOrder = rs.getString("sale_order");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql = "select comm_perc, comm_perc_1, comm_perc_2 from	sorder  where sale_order = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, saleOrder);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				commPerc = rs.getString("comm_perc");
				commPerc1 = rs.getString("comm_perc_1");
				commperc2 = rs.getString("comm_perc_2");
			}

			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			commHdr = "N";
			if((commPerc != null && commPerc.trim().length() > 0)|| (commPerc1 != null && commPerc1.trim().length() > 0) || (commperc2 != null && commperc2.trim().length() > 0))
			{
				commHdr = "Y";
			}
			if("Y".equalsIgnoreCase(commHdr))
			{
				sql = "select invoice_id, ref_line_no, inv_amt, frt_amt, item_ser, tran_date, eff_date, curr_code, exch_rate, fin_entity, site_code," +
						" sales_pers,comm_perc__on,comm_perc,dlv_term, ord_amt, insu_amt,sorder_no, curr_code_sp, exch_rate_sp,comm_amt from (" +
						" select DISTINCT a.invoice_id, 1 as ref_line_no, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt," +
						" a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date,a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity," +
						" a.site_code site_code,d.sales_pers sales_pers,(case when (case when d.comm_perc__on is null then ' ' else d.comm_perc__on end) = ' ' " +
						" then c.comm_perc_on_1 else d.comm_perc__on end) comm_perc__on, (case when (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end)  = 0 " +
						" then (case when d.comm_perc is null then 0 else d.comm_perc end) else (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt, (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm) insu_amt,d.sale_order sorder_no, d.curr_code__comm curr_code_sp, " +
						" d.exch_rate__comm exch_rate_sp, (case when (case when b.sales_pers_comm_1 is null then 0 else b.sales_pers_comm_1 end) = 0 " +
						" then a.sales_pers_comm_1 else b.sales_pers_comm_1 end) comm_amt from invoice a, invdet b, sorddet c, sorder d 	where a.invoice_id = b.invoice_id  " +
						" and b.sord_no = c.sale_order and b.sord_line_no = c.line_no  and c.sale_order = d.sale_order  and a.invoice_id = ? and " +
						" (case when d.sales_pers is null then ' ' else d.sales_pers end) <> ' ' UNION ALL select DISTINCT a.invoice_id, 2 as ref_line_no, a.inv_amt inv_amt," +
						"  a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code,  a.exch_rate exch_rate," +
						"  a.fin_entity fin_entity, a.site_code site_code, d.sales_pers__1 sales_pers, (case when (case when d.comm_perc_on_1 is null then ' ' else d.comm_perc_on_1 end) = ' ' " +
						" then c.comm_perc_on_2 else d.comm_perc_on_1 end) comm_perc__on, (case when (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) = 0 then " +
						" (case when d.comm_perc_1 is null then 0 else d.comm_perc_1 end) else (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt, (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_1) insu_amt, d.sale_order sorder_no, d.curr_code__comm_1 curr_code_sp, " +
						" d.exch_rate__comm_1 exch_rate_sp,(case when (case when b.sales_pers_comm_2 is null then 0 else b.sales_pers_comm_2 end) = 0 " +
						" then a.sales_pers_comm_2 else b.sales_pers_comm_2 end) comm_amt from invoice a,invdet b, sorddet c, sorder d 	where a.invoice_id = b.invoice_id " +
						" and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no and c.sale_order = d.sale_order  and a.invoice_id = ?  " +
						" and (case when d.sales_pers__1 is null then ' ' else d.sales_pers__1 end) <> ' ' UNION ALL SELECT DISTINCT a.invoice_id, 3 as ref_line_no, " +
						" a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code," +
						" a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code, d.sales_pers__2 sales_pers, (case when (case when d.comm_perc_on_2 is null then ' ' else d.comm_perc_on_2 end) = ' ' " +
						" then c.comm_perc_on_3 else d.comm_perc_on_2 end) comm_perc__on, (case when (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) = 0 then " +
						" (case when d.comm_perc_2 is null then 0 else d.comm_perc_2 end) else (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) end) comm_perc, d.dlv_term dlv_term, d.ord_amt ord_amt, " +
						" (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_2) insu_amt , d.sale_order sorder_no, d.curr_code__comm_2 curr_code_sp, d.exch_rate__comm_2 exch_rate_sp," +
						" (case when (case when b.sales_pers_comm_3 is null then 0 else b.sales_pers_comm_3 end) = 0 then a.sales_pers_comm_3 else b.sales_pers_comm_3 end) comm_amt " +
						" from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order  " +
						" and a.invoice_id = ? and (case when d.sales_pers__2 is null then ' ' else d.sales_pers__2 end) <> ' ' ) commtab  where " +
						"((case when sales_pers is null then ' ' else sales_pers end) <> ' ')  and	((case when comm_perc__on is null then ' ' else comm_perc__on end) <> ' ') " +
						" and comm_amt > 0 order by invoice_id, sales_pers, comm_perc__on";

				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, invoiceNo);
				pstmt.setString(2, invoiceNo);
				pstmt.setString(3, invoiceNo);

				rs = pstmt.executeQuery();
				while(rs.next())
				{
					commMap.put("invoice_id",rs.getString("invoice_id"));
					commMap.put("ref_line_no" ,rs.getString("ref_line_no"));
					commMap.put("inv_amt" ,rs.getDouble("inv_amt"));
					commMap.put("frt_amt" ,rs.getDouble("frt_amt"));
					commMap.put("item_ser" ,rs.getString("item_ser"));
					commMap.put("tran_date" ,rs.getDate("tran_date"));
					commMap.put("eff_date " ,rs.getDate("eff_date"));
					commMap.put("curr_code" ,rs.getString("curr_code"));
					commMap.put("exch_rate" , rs.getDouble("exch_rate"));
					commMap.put("fin_entity" , rs.getString("fin_entity"));		
					commMap.put("site_code" , rs.getString("site_code"));	
					commMap.put("sales_pers" , rs.getString("sales_pers"));
					commMap.put("comm_perc__on" , rs.getString("comm_perc__on"));
					commMap.put("comm_perc" , commPerc = rs.getString("comm_perc"));
					commMap.put("dlv_term" , rs.getString("dlv_term"));					
					commMap.put("ord_amt" , rs.getDouble("ord_amt"));
					commMap.put("insu_amt" , rs.getDouble("insu_amt"));
					commMap.put("sorder_no" , rs.getString("sorder_no"));
					commMap.put("curr_code_sp" , rs.getString("curr_code_sp"));
					commMap.put("exch_rate_sp" , rs.getDouble("exch_rate_sp"));

					commtList.add(commMap);

				}

			}
			else
			{
				sql = "select ref_line_no , invoice_id, inv_amt, frt_amt, item_ser, tran_date, eff_date, curr_code, exch_rate, fin_entity, site_code, line_no__inv, item_code, net_amt, " +
						" quantity__stduom, rate__stduom, inv_disc, comm_frt, comm_insu, amt_inv, sales_pers, comm_perc__on, comm_perc, dlv_term, ord_amt, insu_amt, sorder_no, " +
						" sline_no, curr_code_sp, exch_rate_sp, comm_amt from ( select 1 as ref_line_no,a.invoice_id, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt," +
						" a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code,  " +
						" b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom, b.discount inv_disc,(case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) " +
						" / a.inv_amt * a.frt_amt end) comm_frt, (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) / d.ord_amt * d.ins_amt end) comm_insu, " +
						" b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv,b.sord_line_no sline_no, d.sales_pers sales_pers,(case when (case when d.comm_perc__on is null then ' ' " +
						" else d.comm_perc__on end) = ' ' then c.comm_perc_on_1 else d.comm_perc__on end) comm_perc__on, (case when (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end)" +
						"  = 0 then (case when d.comm_perc is null then 0 else d.comm_perc end) else (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt,d.ins_amt * d.exch_rate__ins / d.exch_rate__comm insu_amt, d.sale_order sorder_no, d.curr_code__comm curr_code_sp, d.exch_rate__comm exch_rate_sp, " +
						" (case when b.sales_pers_comm_1 is null then 0 else b.sales_pers_comm_1 end)  comm_amt from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id  " +
						" and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order and a.invoice_id = ? and (case when d.sales_pers is null then ' ' else d.sales_pers end) <> ' '	" +
						" union all select 2 as ref_line_no, a.invoice_id, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, 	a.tran_date tran_date," +
						"  a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code,b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom," +
						" b.discount inv_disc, (case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) / a.inv_amt * a.frt_amt end) comm_frt, " +
						" (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)  / d.ord_amt * d.ins_amt end) comm_insu, 	b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv," +
						"  b.sord_line_no sline_no, d.sales_pers__1 sales_pers, (case when (case when d.comm_perc_on_1 is null then ' ' else d.comm_perc_on_1 end) = ' ' then c.comm_perc_on_2 else d.comm_perc_on_1 end) " +
						" comm_perc__on, (case when (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) = 0 then (case when d.comm_perc_1 is null then 0 else d.comm_perc_1 end) else " +
						" (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) end) comm_perc,d.dlv_term dlv_term, d.ord_amt ord_amt, d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_1 insu_amt," +
						" d.sale_order sorder_no,d.curr_code__comm_1 curr_code_sp, d.exch_rate__comm_1 exch_rate_sp, (case when b.sales_pers_comm_2 is null then 0 else b.sales_pers_comm_2 end) comm_amt " +
						"  from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order  	" +
						" and a.invoice_id = ? and (case when d.sales_pers__1 is null then ' ' else d.sales_pers__1 end) <> ' '	union all select 3 as ref_line_no, a.invoice_id, a.inv_amt inv_amt,  " +
						" a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt , a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, " +
						" a.site_code site_code, b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom, b.discount inv_disc, 	(case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)" +
						" / a.inv_amt * a.frt_amt end) comm_frt, (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)  / d.ord_amt * d.ins_amt end) comm_insu,  " +
						"  b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv, b.sord_line_no sline_no, d.sales_pers__2 sales_pers, (case when (case when d.comm_perc_on_2 is null then ' ' else d.comm_perc_on_2 end) = ' ' " +
						" then c.comm_perc_on_3 else d.comm_perc_on_2 end) comm_perc__on, (case when (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) = 0 then (case when d.comm_perc_2 is null then 0 else d.comm_perc_2 end) else " +
						" (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) end) comm_perc, d.dlv_term dlv_term, d.ord_amt ord_amt,d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_2 insu_amt , d.sale_order sorder_no, " +
						" d.curr_code__comm_2 curr_code_sp, d.exch_rate__comm_2 exch_rate_sp, (case when b.sales_pers_comm_3 is null then 0 else b.sales_pers_comm_3 end)  comm_amt from invoice a, invdet b, sorddet c, sorder d " +
						" where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order and b.sord_line_no = c.line_no and c.sale_order = d.sale_order  and a.invoice_id = ? and (case when d.sales_pers__2 is null then ' ' else d.sales_pers__2 end) <> ' ' ) " +
						" commtab  where ((case when sales_pers is null then ' ' else sales_pers end) <> ' ')  	and	((case when comm_perc__on is null then ' ' else comm_perc__on end) <> ' ') and comm_amt > 0 order by invoice_id, sales_pers, comm_perc__on ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, invoiceNo);
				pstmt.setString(2, invoiceNo);
				pstmt.setString(3, invoiceNo);

				rs = pstmt.executeQuery();
				if(rs.next())
				{
					commMap.put("invoice_id" , rs.getString("invoice_id"));
					commMap.put("ref_line_no" , rs.getString("ref_line_no"));
					commMap.put("inv_amt" ,rs.getDouble("inv_amt"));
					commMap.put("frt_amt" , rs.getDouble("frt_amt"));
					commMap.put("item_ser" , rs.getString("item_ser"));
					commMap.put("tran_date" , rs.getDate("tran_date"));
					commMap.put("eff_date" , rs.getDate("eff_date"));
					commMap.put("curr_code" , rs.getString("curr_code"));
					commMap.put("exch_rate" , rs.getDouble("exch_rate"));
					commMap.put("fin_entity" , rs.getString("fin_entity"));		
					commMap.put("site_code" , rs.getString("site_code"));				
					commMap.put("line_no__inv" , rs.getInt("line_no__inv"));
					commMap.put("item_code" , rs.getString("item_code"));
					commMap.put("net_amt" , rs.getInt("net_amt"));
					commMap.put("quantity__stduom" , rs.getInt("net_amt"));
					commMap.put("rate__stduom" , rs.getInt("rate__stduom"));
					commMap.put("inv_disc" , rs.getInt("inv_disc"));
					commMap.put("comm_frt" , rs.getString("comm_frt"));
					commMap.put("comm_insu" , rs.getString("comm_insu"));
					commMap.put("amt_inv" , rs.getInt("amt_inv"));
					commMap.put("sales_pers" , rs.getString("sales_pers"));
					commMap.put("comm_perc__on" , rs.getString("comm_perc__on"));
					commMap.put("comm_perc" , rs.getString("comm_perc"));
					commMap.put("dlv_term" , rs.getString("dlv_term"));					
					commMap.put("ord_amt" , rs.getDouble("ord_amt"));
					commMap.put("insu_amt" ,rs.getDouble("insu_amt"));
					commMap.put("sorder_no" , rs.getString("sorder_no"));
					commMap.put("sline_no " , rs.getInt("sline_no"));
					commMap.put("curr_code_sp" ,rs.getString("curr_code_sp"));
					commMap.put("exch_rate_sp" ,  rs.getDouble("exch_rate_sp"));
					commMap.put("comm_amt" , rs.getDouble("comm_amt"));

					commtList.add(commMap);

				}

			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if(errString.trim().length() > 0)
			{
				//ll_totrow = lds_comm.retrieve(as_invno)
				if("SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(calledFrom) && totalrow > 0)
				{
					sql = "Select sum(tot_amt - adj_amt) from receivables where	ref_no = ?" ;
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, invno);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						adjAmt  = rs.getDouble(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					if(Math.round(adjAmt) == 0)
					{
						errString = itmDBAccessEJB.getErrorString("","VTADJAMTSP ","","",conn);
						return errString;
					}
				}

				for(int cnt =1 ;commtList.size() > cnt ;cnt++)
				{
					commMap = new HashMap();
					commMap = (HashMap) commtList.get(cnt);

					refLineNo 	= (String) commMap.get("ref_line_no");
					invoiceId	= (String) commMap.get("invoice_id");
					invAmt		= (Double) commMap.get("inv_amt");
					frtAmt		= (Double) commMap.get("frt_amt");
					itemSer		= (String) commMap.get("item_ser");
					tranDate	= (Date)   commMap.get("tran_date");
					effDate		= (Date)   commMap.get("eff_date") ;
					currCode	= (String) commMap.get("curr_code");
					exchRate	= (Double) commMap.get("exch_rate");
					finent		= (String) commMap.get("fin_entity");
					siteCode	= (String) commMap.get("site_code");

					if("Y".equalsIgnoreCase(commHdr))
					{
						lineNoInv = 1;
						itemCode = "";
					}
					else
					{
						lineNoInv	= (Double) commMap.get("line_no__inv");
						itemCode	= (String) commMap.get("item_code");
					}
					salesPers 	= (String) commMap.get("sales_pers");
					commPercOn	= (String) commMap.get("comm_perc__on");
					commPerc	= (String) commMap.get("comm_perc");
					ordAmt		= (Double) commMap.get("ord_amt");
					insuAmt		= (Double) commMap.get("insu_amt");
					sorderNo	= (String) commMap.get("sorder_no");
					currCodeSp	=  (String) commMap.get("curr_code_sp") ;
					exchRateSp	= (Double) commMap.get("exch_rate_sp");

					if(oldSp.equalsIgnoreCase(salesPers) || currcdSpOld.equalsIgnoreCase(currCodeSp))
					{
						oldSp = salesPers;
						currcdSpOld = currCodeSp;

						sql = "select cr_term , tax_class, tax_chap , tax_env  from sales_pers 	where sales_pers = ?";		
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, salesPers);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							crTerm  = rs.getString("cr_term");
							taxClass  = rs.getString("tax_class");
							taxChap  = rs.getString("tax_chap");
						}
						else
						{
							errString = itmDBAccessEJB.getErrorString("","VTSLPERS1 ","","",conn);
							return errString;
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						sql = " select cr_days  from crterm where cr_term = ?";	
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, crTerm);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							crdays  = rs.getInt("cr_term");
						}
						else
						{
							errString = itmDBAccessEJB.getErrorString("","VTCRTERM1 ","","",conn);
							return errString;

						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						acctCode = finCommon.getFinparams("999999", "SALES_COMM_PROV_ACCT", conn);
						if("NULLFOUND".equalsIgnoreCase(acctCode))
						{
							errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
							return errString;
						}


						sql = "select  cctr_code__ap  from sales_pers where sales_pers = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, salesPers);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							cctrCodeAp  = rs.getString(1);
						}
						else
						{
							sql = "select  cctr_code__sal  from invoice where invoice_id = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, invno);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cctrCodeAp  = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;


						sql = "select ins_reqd, frt_reqd  from delivery_term where dlv_term = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, dlvTerm);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							insReqd  = rs.getString(1);
							frtReqd  = rs.getString(2);
						}
						else
						{
							errString = itmDBAccessEJB.getErrorString("","VTDLV1 ","","",conn);
							return errString;
						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;


						jvExchrate = 0;

						sql = "select exch_rate  from journal where ref_ser = 'S-INV' and ref_no = ? and ref_line_no = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, invno);
						pstmt.setString(2, refLineNo);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							exchRate  = rs.getDouble(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if("SR".equalsIgnoreCase(calledFrom) ||"P".equalsIgnoreCase(commCalc))
						{
							sql = "select exch_rate from	drcr_inv 	where tran_ser = 'CRNINV'	and	drcr_flag = 'C'" +
									"and	sundry_code = ? and	invoice_id = ? and	curr_code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, salesPers);
							pstmt.setString(2, invoiceId);
							pstmt.setString(3, currCodeSp);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								exchRate  = rs.getDouble(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

						}
						if("SR".equalsIgnoreCase(calledFrom))
						{
							siteCode = sreSiteCode;
						}

						if(!"SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(commCalc))
						{
							rcpRefser = "R-IBCA";
							sql = "Select distinct h.site_code from receipt h, rcpdet d where h.tran_id = d.tran_id" +
									"and d.ref_ser = ? and d.ref_no = ? and " +
									"(case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, rcpRefser);
							pstmt.setString(2, invoiceNo);
							rs = pstmt.executeQuery();
							while(rs.next())
							{
								siteCodeCd  = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;


						}else
						{
							rcpRefser = "S-INV";


							//Add by vilas for picking exchrate from JV 		
							//insert into header

							xmlBuff = null;	
							xmlBuff = new StringBuffer();
							xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
							xmlBuff.append("<DocumentRoot>");
							xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
							xmlBuff.append("<group0>");
							xmlBuff.append("<description>").append("Group0 description").append("</description>");
							xmlBuff.append("<Header0>");
							xmlBuff.append("<objName><![CDATA[").append("sorder_insert").append("]]></objName>");        //sorder modify to sorder_insert by kunal on 14/12/12 
							xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
							xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
							xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
							xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
							xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
							xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
							xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
							xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
							xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
							xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
							xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
							xmlBuff.append("<description>").append("Header0 members").append("</description>");
							xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"sorder_insert\" objContext=\"1\">");  //sorder modify to sorder_insert by kunal on 14/12/12
							xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
							xmlBuff.append("<tran_id/>");

							xmlBuff.append("<tran_date><![CDATA["+ sdf.format(new java.util.Date()).toString() +"]]></tran_date>");
							xmlBuff.append("<site_code><![CDATA["+ siteCode +"]]></site_code>");
							xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
							xmlBuff.append("<fin_entity><![CDATA["+ finent +"]]></fin_entity>");
							xmlBuff.append("<sundry_type><![CDATA["+ "P" +"]]></sundry_type>");
							xmlBuff.append("<sundry_code><![CDATA["+ sdf.format(salesPers).toString() +"]]></sundry_code>");
							xmlBuff.append("<item_ser><![CDATA["+ itemSer +"]]></item_ser>");
							xmlBuff.append("<acct_code><![CDATA["+ acctCode +"]]></acct_code>");
							xmlBuff.append("<cctr_code><![CDATA["+ cctrCodeAp +"]]></cctr_code>");
							xmlBuff.append("<eff_date><![CDATA["+ sdf.format(new java.util.Date()).toString() +"]]></eff_date>");
							xmlBuff.append("<curr_code><![CDATA["+ currCodeSp +"]]></curr_code>");


						}

						if(!calledFrom.equalsIgnoreCase("SR"))
						{
							sql = "select curr_code from finent f, site s where f.fin_entity = s.fin_entity  and	s.site_code  = ?" ;
							pstmt.setString(1, siteCode);
							rs = pstmt.executeQuery();
							while(rs.next())
							{
								currCodeBase  = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							sql = "Select distinct h.tran_id from  receipt h, rcpdet d where h.tran_id = d.tran_id " +
									"and d.ref_ser = ? and	d.ref_no = ? and  (case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, rcpRefser);
							pstmt.setString(2, invoiceNo);
							rs = pstmt.executeQuery();
							while(rs.next())
							{
								tranId= rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if(!"P".equalsIgnoreCase(commCalc))
							{
								if(!currCode.equalsIgnoreCase(currCodeSp))
								{
									crntExchrate = finCommon.getDailyExchRateSellBuy(currCodeSp, currCodeBase, siteCode, idDate, "S", conn);

								}else
								{
									sql = " Select h.exch_rate from receipt h, rcpdet d where h.tran_id = d.tran_id and	d.ref_ser = ?" +
											" and	d.ref_no = ? and (case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'" +
											"order by h.tran_date, h.tran_id desc";
									pstmt = conn.prepareStatement(sql);
									pstmt.setString(1, rcpRefser);
									pstmt.setString(2, invoiceNo);
									rs = pstmt.executeQuery();
									while(rs.next())
									{
										exchRate= rs.getDouble(1);
									}
									rs.close();
									rs = null;
									pstmt.close();
									pstmt = null;

									if( crntExchrate > 0 )
									{
										exchRateSp = crntExchrate;
									}
									else
									{
										crntExchrate = exchRateSp;
									}	

								}
							}
							else
							{
								remarks = "Agst Sales Return No"+ sretId+"";
							}
							xmlBuff.append("<exch_rate><![CDATA["+ crntExchrate +"]]></exch_rate>");
							if ("SR".equalsIgnoreCase(calledFrom) || "P".equalsIgnoreCase(calledFrom))
							{
								jvExchrate = crntExchrate;

							}else
							{
								if( jvExchrate >0)
								{
									jvExchrate = crntExchrate;
								}
							}

							rcpExchRateTot = 0.0;
							count = 0;

							tranType = finCommon.getFinparams("999999", "SALES_COMM_TRAN_TYPE", conn);
							if("NULLFOUND".equalsIgnoreCase(tranType))
							{
								errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
								return errString;
							}

							//lds_drcr_inv_hdr.setitem(ll_hdr_row,"tran_type",ls_tran_type)	//
							xmlBuff.append("<tran_type><![CDATA["+ tranType +"]]></tran_type>");
							// 05-12-02 Arif to set the remarks
							xmlBuff.append("<drcr_flag><![CDATA["+ "C" +"]]></drcr_flag>");
							xmlBuff.append("<emp_code__aprv><![CDATA["+ loginEmpCode +"]]></emp_code__aprv>");
							xmlBuff.append("<tran_type><![CDATA["+ "FOR" +"]]></tran_type>");
							xmlBuff.append("<cr_term><![CDATA["+ crTerm +"]]></cr_term>");
							xmlBuff.append("<tran_ser><![CDATA["+ transer +"]]></tran_ser>");
							xmlBuff.append("<due_date><![CDATA["+ remarks +"]]></due_date>");
							xmlBuff.append("<acct_code__cf><![CDATA["+ acctCodeCf +"]]></acct_code__cf>");
							xmlBuff.append("<cctr_code__cf><![CDATA["+ cctrCodeCf +"]]></cctr_code__cf>");
							xmlBuff.append("</Detail1>");



							TransIDGenerator tg = new TransIDGenerator("", "SYSTEM", CommonConstants.DB_NAME);
							tranId = tg.generateTranSeqID("CRNINV", "tran_id", keyString, conn);

							//ls_auto_tran_id = gf_gen_key_nvo(lds_drcr_inv_hdr,'CRNINV', ls_trnofld, ls_keystr)
						}		

					}
					if(errString == null || errString.trim().length() ==0)
					{
						xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"sorder_insert\" objContext=\"2\">");  //sorder modify to sorder_insert by kunal
						xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
						xmlBuff.append("<tran_id><![CDATA["+ tranId +"]]></tran_id>");
						xmlBuff.append("<line_no><![CDATA["+ lineNo +"]]></line_no>");
						xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
						xmlBuff.append("<line_no__inv><![CDATA["+ lineNoInv +"]]></line_no__inv>");
						xmlBuff.append("<item_code><![CDATA["+ itemCode +"]]></item_code>");
						xmlBuff.append("<tax_class><![CDATA["+ taxClass +"]]></tax_class>");
						xmlBuff.append("<tax_chap><![CDATA["+ taxChap +"]]></tax_chap>");
						xmlBuff.append("<tax_env><![CDATA["+ taxEnv +"]]></tax_env>");
						xmlBuff.append("<acct_code><![CDATA["+ acctcodeExp +"]]></acct_code>");
						xmlBuff.append("<cctr_code><![CDATA["+ cctrcodeExp +"]]></cctr_code>");
						xmlBuff.append("<exch_rate__inv><![CDATA["+ jvExchrate +"]]></exch_rate__inv>");
						xmlBuff.append("</Detail2>");	
						xmlBuff.append("</Header0>");
						xmlBuff.append("</group0>");
						xmlBuff.append("</DocumentRoot>");
						xmlString = xmlBuff.toString();
						System.out.println("...............just before savdata()");
						siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

						errString = saveData(siteCode,xmlString,conn);
						System.out.println("@@@@@2: retString:"+errString);


						if(lineNoInv == 0)

						{
							invLineNo = lineNoInv;

						}

						if("SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(commCalc))
						{
							sql = "select net_amt from drcr_inv, drcr_invdet  where drcr_inv.tran_id = drcr_invdet.tran_id and " +
									"drcr_inv.invoice_id = ? and drcr_inv.sundry_code = ? " +
									"and drcr_inv.curr_code = ? and drcr_flag = 'C' " +
									"and (case when line_no__inv is null then 0 else line_no__inv end) = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,invoiceId );
							pstmt.setString(2, salesPers);
							pstmt.setString(3, currCodeSp);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								netAmt = rs.getDouble(1);
							}

							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;


						}
						else
						{
							sql = "select sum(case when drcr_flag = 'C' then net_amt else -net_amt end)  from drcr_inv, drcr_invdet " +
									"where drcr_inv.tran_id = drcr_invdet.tran_id and drcr_inv.invoice_id = ?	and drcr_inv.sundry_code = ?" +
									" and drcr_inv.curr_code = ? and (case when line_no__inv is null then 0 else line_no__inv end) = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,invoiceId );
							pstmt.setString(2, salesPers);
							pstmt.setString(3, currCodeSp);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								netAmt = rs.getDouble(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

						}
						if("SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(commCalc))
						{
							if(invNetamt > 0)
							{
								if(sreCurrCode.equalsIgnoreCase(currCode))
								{
									sretPerc = (sretNetAmt*100)/invNetamt;
								}
								else
								{
									sretPerc = (sretNetAmt* sretExchRate *100)/ invNetamt* exchRate;
								}
								netAmt = netAmt * sretPerc / 100;
								xmlBuff.append("<drcr_amt><![CDATA["+ drcrAmt +"]]></drcr_amt>");
							}


							arg2 = null;
							arg1 = "drcr_amt";

							//lc_tax_amt = gf_calc_tax_ds(lds_drcr_inv_det,lds_taxtran,'DRNINV',ls_auto_tran_id,ld_tax_date,ls_arg1,ls_arg2,0 ,ls_currcode)
							if(taxAmt != 0)
							{

							}
							else
							{

								drcrAmt = drcrAmt -taxAmt;
								xmlBuff.append("<drcr_amt><![CDATA["+ drcrAmt +"]]></drcr_amt>");
							}



							xmlBuff.append("<tax_amt><![CDATA["+ taxAmt +"]]></tax_amt>");

							amount = drcrAmt; 
							netAmt = drcrAmt + taxAmt ;

							xmlBuff.append("<net_amt><![CDATA["+ netAmt +"]]></net_amt>");

							exchRateDiff = (amount * crntExchrate) - (amount * jvExchrate) ;
							exchRateDiffTot = exchRateDiffTot + exchRateDiff;

							xmlBuff.append("<diff_amt_exch><![CDATA["+ exchRateDiffTot +"]]></diff_amt_exch>");

							totNetAmt = totNetAmt + netSAmt;

							xmlBuff.append("<amount><![CDATA["+ exchRateDiffTot +"]]></amount>");
							xmlBuff.append("<amount__bc><![CDATA["+ totNetAmt*crntExchrate +"]]></amount__bc>");


							oldsp = salesPers;
							currcdSpOld = currcodeSp ;


							sql = "select due_datefrom invoice where invoice_id = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, invoiceNo);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								dueDate = rs.getDate(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							day = daysBetween(dueDate, date);


							if(day >0 )
							{
								sql = "select fin_chg,fchg_type  from 	crtermfc  " +
										"where (min_day <= ? and max_day >= ? ) and  cr_term = ?";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, crTerm);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									finChg = rs.getDouble(1);
									fchgType = rs.getString(1);
								}
								else
								{
									if("P".equalsIgnoreCase(fchgType))
									{
										expAmt = drcrmt * (finChg/100);
										drcrmt = drcrmt - finChg;
									}
									else
									{
										expAmt = finChg/100;
										drcrmt = drcrmt - finChg;
									}
									xmlBuff.append("<amount><![CDATA["+ totNetAmt +"]]></amount>");
									xmlBuff.append("<amount__bc><![CDATA["+ (totNetAmt-expAmt) +"]]></amount__bc>");

									acctcodeDeduct = finCommon.getFinparams("999999", "DEDUCT_COMM_ACCT", conn);
									if("NULLFOUND".equalsIgnoreCase(acctcodeDeduct)|| acctcodeDeduct == null || acctcodeDeduct.trim().length() == 0)
									{
										acctcodeDeduct = acctcodeExp;
										cctrcodeDeduct = cctrcodeExp;
									}
									else
									{
										cctrcodeDeduct = finCommon.getFinparams("999999", "DEDUCT_COMM_CCTR", conn);
										if("NULLFOUND".equalsIgnoreCase(cctrcodeDeduct)|| cctrcodeDeduct == null || cctrcodeDeduct.trim().length() == 0)
										{
											cctrcodeDeduct = cctrcodeExp;
										}



									}
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;

								xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"sorder_insert\" objContext=\"2\">");  //sorder modify to sorder_insert by kunal
								xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
								xmlBuff.append("<tran_id/>");
								xmlBuff.append("<line_no><![CDATA["+ lineNo++ +"]]></line_no>");
								xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
								xmlBuff.append("<line_no__inv><![CDATA["+ lineNoInv +"]]></line_no__inv>");
								xmlBuff.append("<item_code><![CDATA["+ itemCode +"]]></item_code>");
								xmlBuff.append("<tax_class><![CDATA["+ taxClass +"]]></tax_class>");
								xmlBuff.append("<tax_chap><![CDATA["+ taxChap +"]]></tax_chap>");
								xmlBuff.append("<tax_env><![CDATA["+ taxEnv +"]]></tax_env>");
								xmlBuff.append("<acct_code><![CDATA["+ acctcodeDeduct +"]]></acct_code>");
								xmlBuff.append("<cctr_code><![CDATA["+ cctrcodeDeduct +"]]></cctr_code>");

								xmlBuff.append("<net_amt><![CDATA["+ expAmt * -1 +"]]></net_amt>");
								xmlBuff.append("<drcr_amt><![CDATA["+ (expAmt * -1) * (exchRate/crntExchrate) +"]]></drcr_amt>");

								xmlBuff.append("<exch_rate__inv><![CDATA["+ jvExchrate +"]]></exch_rate__inv>");
								xmlBuff.append("</Detail2>");	
								xmlBuff.append("</Header0>");
								xmlBuff.append("</group0>");
								xmlBuff.append("</DocumentRoot>");

								xmlString = xmlBuff.toString();
								System.out.println("...............just before savdata()");
								siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

								errString = saveData(siteCode,xmlString,conn);
								System.out.println("@@@@@2: retString:"+errString);
								return errString;
								
								
							}

						}

					}
				}


				if(errString == null || errString.trim().length() ==0   /* && lds_drcr_inv_hdr.rowcount() > 0*/)
				{

					//ls_hdr = lds_drcr_inv_hdr.describe('datawindow.data')
					//ls_det = lds_drcr_inv_det.describe('datawindow.data')
					//funtion update debit note.
					errString = updateCreditNote(commMap,commMap ,xtraParams,post ,conn);
					return errString;
				}

				if(errString == null || errString.trim().length() ==0 &&  "Y".equalsIgnoreCase(post))
				{
					if("SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(commCalc))
					{

						TransIDGenerator tg = new TransIDGenerator("", "SYSTEM", CommonConstants.DB_NAME);
						autoTranId = tg.generateTranSeqID("CRNINV", "tran_id", keyString, conn);

						//ls_auto_tran_id = lds_drcr_inv_hdr.getitemstring(ll_cnt,'tran_id')
						sql = "select tran_date		,	curr_code	,	exch_rate	,	sundry_code		,	sundry_type	  ,	acct_code		," +
								" cctr_code		,  due_date		,  cr_term 		,  site_code 	   ,	invoice_id	  , 	fin_entity" +
								"from   drcr_inv where  tran_id = ? ";

						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, autoTranId);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							tranDate = rs.getDate("tran_date");
							curr = rs.getString("curr_code");
							exch = rs.getDouble("exch_rate");
							sundryCode = rs.getString("sundry_code");
							sundryType = rs.getString("sundry_type");
							acct = rs.getString("acct_code");
							cctr = rs.getString("cctr_code");
							dueDate = rs.getDate("due_date");
							crTerm = rs.getString("cr_term");
							site = rs.getString("site_code");
							invoiceId = rs.getString("invoice_id");
							finEntity = rs.getString("fin_entity");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;


						sql = "select tot_amt from misc_payables where ref_no = ?  and tran_ser = 'DRNINV'";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, autoTranId);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							amount = rs.getDouble("tot_amt");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						sql = "update misc_payables set hold_amt = amount where ref_no = ? and tran_ser = 'DRNINV'";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, autoTranId);
						pstmt.executeUpdate();


						invibcagen 	= finCommon.getFinparams("999999", "INV_IBCA_GEN", conn);
						if("NULLFOUND".equalsIgnoreCase(invibcagen))
						{
							invibcagen = "Y";
						}
						if("Y".equalsIgnoreCase(invibcagen))
						{
							salesPers = sundryCode;
						}

						sql = "select site_code__pay  from sales_pers where sales_pers = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, salesPers);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							siteCodePay = rs.getString("site_code__pay");
						}					
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(siteCodePay== null || siteCodePay.trim().length() == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","VTSPSITPAY ","","",conn);
							return errString;
						}
						if(siteCodePay != site)
						{

							sql = "	select key_string from transetup  where upper(tran_window) = 'W_PAY_IBCA' ";
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								keyString = rs.getString("key_string");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;


						}

						sql = "select fin_entity  from site where site_code = ?" ;
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, siteCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							finEntityFr = rs.getString("fin_entity");
						}
						else
						{
							errString = itmDBAccessEJB.getErrorString("","VMSITE ","","",conn);
							return errString;
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;


						sql = "select fin_entity from site where site_code = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, siteCodePay);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							finEntityTo = rs.getString("fin_entity");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;



						sql = "select link_type, acct_code__pay, cctr_code__pay, acct_code__rcp, cctr_code__rcp" +
								" from ibca_pay_ctrl where site_code__from 	= ? and site_code__to = ?" ;
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, siteCode);
						pstmt.setString(2, siteCodePay);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							linkType = rs.getString("link_type");
							acctCodePay = rs.getString("acct_code__pay");
							cctrCodePay = rs.getString("cctr_code__pay");
							acctCodeRcp = rs.getString("acct_code__rcp");
							cctrCodeRcp = rs.getString("cctr_code__rcp");

						}
						else
						{
							errString = itmDBAccessEJB.getErrorString("","VTIBCA5 ","","",conn);
							return errString;
						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;



						xmlString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
								"\r\n</header><Detail1><item_ser></item_ser>"+
								"\r\n<site_code>"+siteCode+"</site_code>\r\n<tran_date>"+sdf.format(new java.util.Date(tranDate.getTime()))+"</tran_date></Detail1></Root>";

						//TransIDGenerator tg = new TransIDGenerator("", "SYSTEM", CommonConstants.DB_NAME);
						ibcaId = tg.generateTranSeqID("P-IBCA", "tran_id", keyString, conn);

						if("ERROR".equalsIgnoreCase(ibcaId))
						{
							errString = itmDBAccessEJB.getErrorString("","VTIBCA5 ","","",conn);
							return errString;
						}


						remarks = "IBCA transfer of sales pers"+ sundryCode.trim();

						amountBc = amount * exch;
						if(amountBc != 0)

							// create the ibca
							sql = "INSERT INTO pay_ibca(tran_id, tran_date, eff_date, site_code__from, fin_entity__from, site_code__to, fin_entity__to, amount," +
									" curr_code, exch_rate, confirmed, acct_code__ifr, cctr_code__ifr, acct_code__ito, cctr_code__ito, " +
									" amount__bc, tran_type, tran_ser, link_type, remarks, sundry_type, sundry_code)" +
									" VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, ibcaId);
						pstmt.setDate(2, new java.sql.Date(tranDate.getDate()));
						pstmt.setDate(3, new java.sql.Date(tranDate.getDate()));
						pstmt.setString(4, site);
						pstmt.setString(5, finEntityFr);
						pstmt.setString(6, siteCodePay);
						pstmt.setString(7, finEntityTo);
						pstmt.setDouble(8, amount);

						pstmt.setString(9, curr);
						pstmt.setDouble(10, exch);
						pstmt.setString(11, "N");
						pstmt.setString(12, acctCodePay);
						pstmt.setString(13, cctrCodePay);
						pstmt.setString(14, acctCodeRcp);
						pstmt.setString(15, cctrCodeRcp);
						pstmt.setDate(16, new java.sql.Date(date.getDate()));
						pstmt.setDouble(17, amountBc);
						pstmt.setString(18, tranType);
						pstmt.setString(19, "I");
						pstmt.setString(20, linkType);
						pstmt.setString(21, remarks);
						pstmt.setString(22, sundryType);
						pstmt.setString(23, sundryCode);
						pstmt.executeUpdate();

						sql = "INSERT INTO pay_ibca_det (tran_id, ref_ser, ref_no, ref_date, curr_code, exch_rate, acct_code, cctr_code, due_date, tot_amt, discount, tax_amt," +
								"bank_code, ref_type, cr_term, ref_ser__org, sundry_type, sundry_code ) VALUES (?, ?, ?, ? ,?,? ,?, ?, ?, ?, ?, ? , ? , ?, ? , ? , ?, ?, ?, ? )";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, ibcaId);
						pstmt.setString(2, "CRNINV");
						pstmt.setString(5, autoTranId);
						pstmt.setDate(2, new java.sql.Date(tranDate.getDate()));
						pstmt.setString(9, curr);
						pstmt.setDouble(10, exch);
						pstmt.setString(11, acct);
						pstmt.setString(12, cctr);
						pstmt.setDate(13, new java.sql.Date(dueDate.getDate()));
						pstmt.setDouble(14, amount);
						pstmt.setDouble(15,discount );
						pstmt.setDouble(16, taxAmt);
						pstmt.setString(17,"" );
						pstmt.setString(18,refType );
						pstmt.setString(19,crTerm );
						pstmt.setString(20,"DRNINV" );
						pstmt.setString(21,sundryType );
						pstmt.setString(22,sundryCode );
						pstmt.executeUpdate();
						;

						// call posting for ibca

						errString =gbfRetrievePibca(ibcaId,ibcaId,1,site,xtraParams,conn);

						if(errString != null && errString.trim().length() > 0)
						{
							return errString;
						}

					}
				}
				sql = "update misc_payables set hold_amt = ? where ref_no = ?  and tran_ser = 'P-IBCA'";
				pstmt.setDouble(1, amount);
				pstmt.setString(2,autoTranId);
				pstmt.executeUpdate();


				// Added by fatema - 26/04/2007 - DI7CHT0010 - Db-Cr Note Adjustment
				if(errString == null || errString.trim().length() == 0)
				{
					//for ll_cnt = 1 to lds_drcr_inv_hdr.rowcount()
					errString = gbfCreateCrdrAdj(autoTranId,calledFrom, conn);
				}

			}


		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}

		return errString;

	}


	private String gbfRetrievePibca(String asFrom, String asTo, int aiCommit , String site, String  xtraParams,Connection conn) throws ITMException {

		String errCode = "",keyFld = "" , expHdr = "",expDet = "", winName = "", ledgPostconf= "" , ledgPostConf = "",
				sql = "" , sql1 = "" ,winname ="";
		String currCode[],custCode[],acctCode[],cctrCode[];

		HashMap tranId = new HashMap();
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		HashMap HdrMap = null;
		HashMap DetMap = null;
		ArrayList DetList = new ArrayList();
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		int cntrHdr = 0,cntr = 0,insertedRow = 0,rows = 0;

		java.util.Date tranDate = null, today;
		try
		{
			sql = "select   tran_date,eff_date,site_code__from, fin_entity__from, site_code__to,fin_entity__to,amount,  " +
					"curr_code,confirmed,conf_date,emp_code__aprv,acct_code__ifr,cctr_code__ifr,acct_code__ito,cctr_code__ito," +
					"amount__bc,tran_type,tran_ser,tran_id__iss,exch_rate,link_type from PAY_IBCA where tran_id = ?";


			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,asFrom);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				HdrMap = new HashMap();
				HdrMap.put("tran_date",rs.getDate("tran_date"));
				HdrMap.put("tran_id",rs.getString("tran_id"));

				HdrMap.put("eff_date",rs.getString("eff_date"));
				HdrMap.put("site_code__from",rs.getString("site_code__from"));
				HdrMap.put("fin_entity__from",rs.getString("fin_entity__from"));
				HdrMap.put("site_code__to",rs.getString("site_code__to"));
				HdrMap.put("fin_entity__to",rs.getString("fin_entity__to"));
				HdrMap.put("amount",rs.getDate("amount"));
				HdrMap.put("curr_code",rs.getString("curr_code"));
				HdrMap.put("confirmed",rs.getDouble("confirmed"));
				HdrMap.put("conf_date",rs.getDouble("conf_date"));
				HdrMap.put("emp_code__aprv",rs.getString("emp_code__aprv"));
				HdrMap.put("acct_code__ifr",rs.getDouble("acct_code__ifr"));
				HdrMap.put("cctr_code__ifr",rs.getString("cctr_code__ifr"));
				HdrMap.put("acct_code__ito",rs.getString("acct_code__ito"));
				HdrMap.put("cctr_code__ito",rs.getString("cctr_code__ito")==null?"":rs.getString("cctr_code__ito"));

				HdrMap.put("amount__bc",rs.getString("amount__bc"));
				HdrMap.put("tran_type",rs.getString("tran_type"));
				HdrMap.put("tran_ser",rs.getString("tran_ser"));
				HdrMap.put("tran_id__iss",rs.getString("tran_id__iss"));
				HdrMap.put("exch_rate",rs.getDouble("exch_rate"));
				HdrMap.put("link_type",rs.getString("link_type"));

				System.out.println(" Header Map..........");
				System.out.println(HdrMap.toString());
			}
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;



			//RcpDetMap = new HashMap();
			sql = " select  tran_id,ref_ser, ref_no, ref_date,curr_code,acct_code,cctr_code,due_date,tot_amt,  discount, " +
					" tax_amt,auto_pay,bank_code,ref_type,cr_term,bill_no,bill_date,sundry_type,sundry_code,pay_mode," +
					"exch_rate,entry_batch_no,purc_order,supp_bill_amt,adv_amt,tds_amt from PAY_IBCA_DET where tran_id = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,asFrom);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				DetMap = new HashMap();
				DetMap.put("tran_id", rs.getString("tran_id"));
				DetMap.put("ref_ser", rs.getString("ref_ser"));
				DetMap.put("ref_no", rs.getString("ref_no"));
				DetMap.put("ref_date", rs.getString("ref_date"));
				DetMap.put("curr_code", rs.getString("curr_code"));
				DetMap.put("acct_code", rs.getDouble("acct_code"));
				DetMap.put("cctr_code", rs.getDouble("cctr_code"));
				DetMap.put("due_date", rs.getDouble("due_date"));
				DetMap.put("tot_amt", rs.getString("tot_amt"));
				DetMap.put("discount", rs.getDouble("discount"));
				DetMap.put("tax_amt", rs.getDouble("tax_amt"));
				DetMap.put("auto_pay", rs.getDouble("auto_pay"));
				DetMap.put("bank_code", rs.getString("bank_code"));
				DetMap.put("ref_type", rs.getDouble("ref_type"));
				DetMap.put("cr_term", rs.getDouble("cr_term"));
				DetMap.put("bill_no", rs.getDouble("bill_no"));
				DetMap.put("bill_date", rs.getString("bill_date"));
				DetMap.put("sundry_type", rs.getDouble("sundry_type"));
				DetMap.put("sundry_code", rs.getDouble("sundry_code"));		
				DetMap.put("pay_mode", rs.getDouble("pay_mode"));
				DetMap.put("exch_rate", rs.getString("exch_rate"));
				DetMap.put("entry_batch_no", rs.getDouble("entry_batch_no"));
				DetMap.put("purc_order", rs.getDouble("purc_order"));		
				DetMap.put("supp_bill_amt", rs.getDouble("supp_bill_amt"));
				DetMap.put("adv_amt", rs.getString("adv_amt"));
				DetMap.put("tds_amt", rs.getDouble("tds_amt"));


				DetList.add(DetMap);

				System.out.println(" DetMap  Map..........");
				System.out.println(DetMap.toString());

			}    



			sql = "select tran_id from pay_ibca  where tran_id 	>= ? and tran_id <= ? and 	site_code__from = ? and upper(confirmed) <> 'Y'";
			pstmt = conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				tranId.put("tran_id",rs.getString(1));                                 


				if ("db2".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql1 = "SELECT tran_id FROM pay_ibca  WHERE tran_id = ? for update ";
				}

				else if ( "mssql".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql1 = "SELECT tran_id FROM pay_ibca (updlock) WHERE tran_id = ? " ;
				}
				else
				{
					sql1 =" SELECT tran_id , tran_date FROM pay_ibca WHERE tran_id =  ? for update nowait" ;
				}
				pstmt1 = conn.prepareStatement(sql1);
				pstmt.setString(1,asFrom);
				rs1 = pstmt1.executeQuery();
				if(rs1.next())
				{
					keyFld = rs1.getString("tran_id") == null ? " ":rs1.getString("tran_id");
					tranDate = rs1.getDate("tran_date");
				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;


				today 		=  new java.util.Date();
				winname = "W_RCP_IBCA";

				sql = "select ledg_post_conf from transetup where upper(tran_window) = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,"W_PAY_IBCA");
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					ledgPostConf = rs.getString(1);
				}
				else
				{
					errCode = itmDBAccessEJB.getErrorString("","VTSEQ ","","",conn);

				}

				if("Y".equalsIgnoreCase(ledgPostConf))
				{
					if(tranDate.compareTo(today) == 0)
					{
						tranDate = today;
					}
					tranDate = today;
					sql = " update rcp_ibca set tran_date = ? where tran_id   = ?" ;
					pstmt.setString(1,(String)tranId.get("tran_id"));
					pstmt.setString(2,asFrom);
					pstmt.executeUpdate();		

				}


			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			errCode = gbfPostPibca(HdrMap,DetList,aiCommit,xtraParams,conn);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}

		return errCode;
	}



	private String gbfPostPibca(HashMap HdrMap, ArrayList DetList, int aiCommit ,String xtraParams, Connection conn) throws ITMException {



		String errCode = "",keyFld = "" , expHdr = "",expDet = "", winName = "", ledgPostconf= "" , ledgPostConf,
				sql = "" ,winname ="" ,loginEmpCode = "";
		String currCode[],custCode[],acctCode[],cctrCode[];
		String tranSer = "" ,linkType = "";

		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		String tranId = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		int cntrHdr = 0,cntr = 0,insertedRow = 0,rows = 0, ediOption = 0;
		ValidatorEJB validatorEJB = null;
		validatorEJB = new ValidatorEJB();


		java.util.Date tranDate, today;
		today =new java.util.Date();

		try
		{
			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");

			sql = "select edi_option from transetup where tran_window = 'w_pay_ibca'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				ediOption  = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			tranSer = (String) HdrMap.get("tran_ser");

			if("I".equalsIgnoreCase(tranSer))
			{
				errCode = gbfPostPibcaHdrIss(HdrMap,xtraParams,conn);
				if(errCode == null || errCode.trim().length() == 0)

				{
					errCode = gbfPostPibcaDetIss(HdrMap,DetList,xtraParams,conn);

					if(errCode == null || errCode.trim().length() == 0)

					{ 
						if("E".equalsIgnoreCase(linkType))
						{
							sql = "update receipt set confirmed = 'Y', conf_date = ?,emp_code__aprv = ? where tran_id = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
							pstmt.setString(2, loginEmpCode);
							pstmt.setString(3, (String)HdrMap.get("tran_Id"));
							int updateCoount = pstmt.executeUpdate();
							System.out.println("no of row update = "+updateCoount);

							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if(updateCoount > 0)
							{
								errCode = itmDBAccessEJB.getErrorString("","VTCICONF3 ","","",conn);
								return errCode;
							}
						}
					}

				}
			}

			if("R".equalsIgnoreCase(tranSer))
			{

				errCode = gbfPostPibcaHdrRcp(HdrMap,xtraParams,conn);
				if(errCode == null || errCode.trim().length() == 0)

				{
					errCode = gbfPostPibcaDetRcp(HdrMap,DetList, xtraParams ,conn);

					if(errCode == null || errCode.trim().length() == 0)

					{ 
						if("E".equals(linkType) || ediOption > 0)
						{
							sql = "update receipt set confirmed = 'Y', conf_date = ?,emp_code__aprv = ? where tran_id = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
							pstmt.setString(2, loginEmpCode);
							pstmt.setString(3, (String)HdrMap.get("tran_Id"));
							int updateCoount = pstmt.executeUpdate();
							System.out.println("no of row update = "+updateCoount);

							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if(updateCoount > 0)
							{
								errCode = itmDBAccessEJB.getErrorString("","VTCICONF3 ","","",conn);
								return errCode;
							}
						}
					}

				}
			}

			if(errCode == null || errCode.trim().length() == 0)
			{ 

				sql = "update pay_ibca set confirmed = ?, conf_date = ?, emp_code__aprv = ? where tran_id = ?" ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, "Y");
				pstmt.setDate(2,new java.sql.Date(today.getDate()));
				pstmt.setString(3, loginEmpCode);
				pstmt.setString(4, (String)HdrMap.get("tran_Id"));
				pstmt.executeUpdate();

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


			}

		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errCode ;

	}


	private  String gbfPostPibcaDetRcp(HashMap HdrMap , ArrayList DetList ,String xtraParams,  Connection conn) throws ITMException
	{


		System.out.println("gbfPostPibcaDetRcp called..............");
		String errString = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		String acctCode = "";
		String cctrCode = ""; 
		String recoAcctCode = "";
		String recoCctrCode = "";
		String taxAcctCode = "";
		String taxCctrCode = "";
		String acctCode1 = "";
		String cctrCode1 = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String contactCode = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String tranType = "";
		String empCode = "";
		String refNO = "";
		String rcpMode = "";
		String batchNo = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String sql = "";
		String hcurrCode = "";
		String errorType = "";
		String payslip = "";
		String partyDocRef = "";
		String refSer = "";
		String refNo = "";
		String salesPers = "";
		String status = "";
		String lineNoPef = "";
		String tranId = "";
		int count = 0;
		int lineNo = 0;
		double exchRate = 0.0;
		double hexchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double taxAmount = 0.0;
		double recoAmount = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double advAmt = 0.0;
		double adjAmt = 0.0;
		double advAdj = 0.0;
		double recoverAmt = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		Date billDate = null;
		Date dueDate = null;


		HashMap DetMap = null;
		//HashMap RcpDetMap = null;
		HashMap miscPayMap = null;
		//HashMap EpcAdjMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap detListMap = null;
		HashMap recofiltMap = null;
		HashMap recodataMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		DistCommon distCommon = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();
		try
		{
			finCommon = new  FinCommon();
			distCommon = new DistCommon();
			itmDBAccessEJB = new ITMDBAccessEJB();
			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginCode");

			tranId = (String)HdrMap.get("tranId");
			tranDate = (Date)HdrMap.get("tran_date");
			effDate = (Date)HdrMap.get("eff_date");
			finEntity = (String)HdrMap.get("fin_entity");
			siteCode = (String)HdrMap.get("site_code");
			siteCodeFor = (String)HdrMap.get("site_code__for");
			projectCode = (String)HdrMap.get("proj_code");
			hcurrCode = (String)HdrMap.get("curr_code");
			hexchRate = (Double)HdrMap.get("exch_rate");
			remarks = (String)HdrMap.get("remarks");

			System.out.println("DetList SIZE "+DetList.size());
			System.out.println("DetList SIZE "+DetList);

			for (int ctr =0; ctr < DetList.size(); ctr++)
			{

				System.out.println("no of times "+ctr);
				DetMap = new HashMap();
				DetMap = (HashMap) DetList.get(ctr);


				refDate = (Date)HdrMap.get("ref_date");
				billDate = (Date)HdrMap.get("bill_date");
				dueDate = (Date)HdrMap.get("due_date");


				System.out.println("DetMap SIZE "+DetMap);




				glTraceMap = new HashMap();
				glTraceMap.put("tran_date",new Timestamp(tranDate.getTime()));
				glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
				glTraceMap.put("fin_entity", finEntity);
				glTraceMap.put("site_code", siteCode);
				glTraceMap.put("sundry_type",(String)DetMap.get("sundry_type")==null?"O":(String)DetMap.get("sundry_type"));
				glTraceMap.put("sundry_code",(String)DetMap.get("sundry_code")== null?"":(String)DetMap.get("sundry_code"));
				glTraceMap.put("acct_code", (String)DetMap.get("acct_code"));
				System.out.println("818 account chek ="+acctCode+"  "+sundryType+"   "+sundryCode);
				glTraceMap.put("cctr_code", (String)DetMap.get("cctr_code")==null?"":(String)DetMap.get("cctr_code"));
				glTraceMap.put("emp_code", (String)DetMap.get("emp_code"));
				glTraceMap.put("anal_code", (String)DetMap.get("anal_code"));
				glTraceMap.put("curr_code", (String)DetMap.get("curr_code")==null?hcurrCode:(String)DetMap.get("curr_code"));
				glTraceMap.put("proj_code", projectCode);
				glTraceMap.put("exch_rate", (Double)DetMap.get("exch_rate"));

				amount = (Double)DetMap.get("tot_amt");
				if(amount > 0)
				{
					glTraceMap.put("dr_amt",0.0);
					glTraceMap.put("cr_amt",amount);
				}
				else
				{
					glTraceMap.put("dr_amt",0 - amount);
					glTraceMap.put("cr_amt",0.0);
				}
				glTraceMap.put("ref_type","F");
				glTraceMap.put("ref_ser", "RCP");
				glTraceMap.put("ref_id", tranId);
				glTraceMap.put("remarks",remarks);

				System.out.println("848 glTraceUpdate Called..............");
				errString = finCommon.glTraceUpdate(glTraceMap,conn);
				if(errString != null && errString.trim().length() > 0)
				{
					System.out.println("ERROR IN GLTRACE ...........");

					return errString;
				}

				// Populate sundry balance structure
				sundryBalMap = new HashMap();
				sundryBalMap.put("tran_date",new Timestamp(tranDate.getTime()));
				sundryBalMap.put("eff_date",new Timestamp(effDate.getTime()));
				sundryBalMap.put("fin_entity", finEntity);
				sundryBalMap.put("site_code", siteCode);
				sundryBalMap.put("sundry_type", sundryType);
				sundryBalMap.put("sundry_code", sundryCode);
				sundryBalMap.put("acct_code", (String)DetMap.get("acct_code"));
				sundryBalMap.put("cctr_code", (String)DetMap.get("cctr_code")==null?"":(String)DetMap.get("cctr_code"));
				sundryBalMap.put("curr_code", (String)DetMap.get("curr_code"));
				sundryBalMap.put("exch_rate", (Double)DetMap.get("exch_rate"));

				amount = (Double)DetMap.get("amount");
				if(amount > 0)
				{
					sundryBalMap.put("dr_amt", 0.0);
					sundryBalMap.put("cr_amt", amount);
				}
				else
				{
					sundryBalMap.put("dr_amt", 0 - amount);
					sundryBalMap.put("cr_amt", 0.0);
				}
				sundryBalMap.put("adv_amt", 0.0);

				System.out.println("2366 sundryBaleUpdate Called..............");
				errString = finCommon.gbf_sundrybal_upd(sundryBalMap, conn);
				if(errString != null && errString.trim().length() > 0)
				{
					System.out.println("error is sundryBaleUpdate ..........."+errString);

					return errString;
				}


				///Populate the misc_payables structure				/////
				// insert into misc_payable	
				miscPayMap = new HashMap();
				miscPayMap.put("tran_date",new Timestamp(tranDate.getTime()));
				miscPayMap.put("ref_no",(String)DetMap.get("ref_no"));
				miscPayMap.put("ref_date", new Timestamp(refDate.getTime()));			
				miscPayMap.put("bill_no", (String)DetMap.get("bill_no"));
				miscPayMap.put("bill_date", new Timestamp(billDate.getTime()));
				miscPayMap.put("sundry_type",(String)DetMap.get("sundry_type")==null?"O":(String)DetMap.get("sundry_type"));
				miscPayMap.put("sundry_code", (String)DetMap.get("sundry_code")==null?"O":(String)DetMap.get("sundry_code"));
				miscPayMap.put("acct_code", (String)DetMap.get("acct_code"));
				miscPayMap.put("cctr_code", (String)DetMap.get("cctr_code")==null?"":(String)DetMap.get("cctr_code"));
				miscPayMap.put("curr_code", (Double)DetMap.get("curr_code"));
				miscPayMap.put("exch_rate", (Double)DetMap.get("exch_rate__vouch"));


				miscPayMap.put("due_date", new Timestamp(dueDate.getTime()));
				miscPayMap.put("site_code",siteCode);
				miscPayMap.put("fin_entity",finEntity);
				miscPayMap.put("tot_amt", (Double)DetMap.get("tot_amt"));
				miscPayMap.put("bank_code", (String)DetMap.get("bank_code"));
				miscPayMap.put("auto_pay", (String)DetMap.get("auto_pay"));
				miscPayMap.put("pay_mode", (String)DetMap.get("pay_mode"));
				miscPayMap.put("paid", "N");
				miscPayMap.put("adv_amt", (Double)DetMap.get("adv_amt"));
				miscPayMap.put("tds_amt", (Double)DetMap.get("tds_amt"));
				miscPayMap.put("supp_bill_amt", (Double)DetMap.get("supp_bill_amt"));
				miscPayMap.put("entry_batch_no", (Double)DetMap.get("entry_batch_no"));
				miscPayMap.put("purc_order",(Double)DetMap.get("purc_order"));
				miscPayMap.put("ref_ser__org", (Double)DetMap.get("ref_ser__org"));

				System.out.println("884 sundryBaleUpdate Called..............");
				errString = finCommon.gbfMiscPayUpd(miscPayMap, conn);
				if(errString != null && errString.trim().length() > 0)
				{
					return errString;
				}




			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}

	private  String gbfPostPibcaHdrRcp(HashMap MapHrd ,String xtraParams, Connection conn) throws ITMException
	{
		System.out.println("gbfPostPibcaHdrRcp called........");
		String errString = "";
		String linkType = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		String acctCode = "";
		String cctrCode = "";
		String acctCodePay = "";
		String cctrCodePay = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String contactCode = "";
		String empCode = "";
		String refNO = "";
		String rcpMode = "";
		String batchNo = "";
		String tranType = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String confirmed = "";
		String sql = "";
		String errorType = "";
		String bdFluctuationCf = "";
		String acctCodeBal = "";
		String cctrCodeBal = "";
		String basecurrCode = "";
		String projCode = "";
		String custCode = "";
		String salesPers = "";
		String refSer = "";
		String refNo = "";
		String acctCodeCf = "";
		String payslip = "";
		String tranId = "";
		boolean isInBaseCurr =false;
		int count = 0;
		int cnt1 = 0 ;
		int cnt = 0;
		double exchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double advAmt = 0.0;
		double netAmt = 0.0;
		double chqAmt = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double ediOption = 0.0;
		double netAmountBc = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		HashMap detListMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap receivablesMap = null;
		HashMap epcadjMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();
		ITMDBAccessEJB itmDBAccessEJB = null;
		try
		{
			finCommon =new  FinCommon();

			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			java.util.Date today=	new java.sql.Date(new java.util.Date().getTime());
			itmDBAccessEJB = new ITMDBAccessEJB();

			linkType = (String)MapHrd.get("link_type");
			tranId = (String)MapHrd.get("tran_id");

			if(!linkType.equalsIgnoreCase("R") && !linkType.equalsIgnoreCase("C"))
			{


				tranDate = (Date)MapHrd.get("tran_date");
				refDate = (Date)MapHrd.get("ref_date");
				effDate = (Date)MapHrd.get("eff_date");
				remarks = (String)MapHrd.get("remarks");

				finEntity = (String)MapHrd.get("fin_entity__to");
				siteCode = (String)MapHrd.get("site_code__to");

				bankCode = (String)MapHrd.get("bank_code");

				acctCode = (String)MapHrd.get("acct_code__to");
				cctrCode = (String)MapHrd.get("cctr_code__to");

				currCode = (String)MapHrd.get("curr_code");
				exchRate = (Double)MapHrd.get("exch_rate");



				glTraceMap = new HashMap();
				glTraceMap.put("tran_date", new Timestamp(tranDate.getTime()));
				glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
				glTraceMap.put("fin_entity", finEntity);
				glTraceMap.put("site_code", siteCode);
				glTraceMap.put("sundry_type", "O");
				glTraceMap.put("sundry_code", "");
				glTraceMap.put("acct_code", acctCode);
				glTraceMap.put("cctr_code", cctrCode);
				glTraceMap.put("emp_code", "");
				glTraceMap.put("anal_code", "");
				glTraceMap.put("curr_code", currCode);
				glTraceMap.put("exch_rate", exchRate);
				if((Double)MapHrd.get("amount") > 0 )
				{
					glTraceMap.put("dr_amt", (Double)MapHrd.get("amount"));
					glTraceMap.put("cr_amt", 0.0 );
				}

				else{
					glTraceMap.put("dr_amt", 0.0);
					glTraceMap.put("cr_amt",  0 - (Double)MapHrd.get("amount"));
				}
			}

			glTraceMap.put("ref_type","F");
			glTraceMap.put("ref_ser", "P-IBCA");
			glTraceMap.put("ref_id", tranId);
			glTraceMap.put("remarks", remarks);

			System.out.println("1766 glTraceUpdate Called..............");
			errString = finCommon.glTraceUpdate(glTraceMap,conn); 
			if(errString != null && errString.trim().length() > 0)
			{
				return errString;
			}

		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}



	private  String  gbfPostPibcaHdrIss(HashMap MapHrd, String xtraParams ,Connection conn) throws ITMException
	{

		System.out.println("gbfPostPibcaHdrIss called........");
		String errString = "";
		String linkType = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		String acctCode = "";
		String cctrCode = "";
		String acctCodePay = "";
		String cctrCodePay = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String contactCode = "";
		String empCode = "";
		String refNO = "";
		String rcpMode = "";
		String batchNo = "";
		String tranType = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String confirmed = "";
		String sql = "";
		String errorType = "";
		String bdFluctuationCf = "";
		String acctCodeBal = "";
		String cctrCodeBal = "";
		String basecurrCode = "";
		String projCode = "";
		String custCode = "";
		String salesPers = "";
		String refSer = "";
		String refNo = "";
		String acctCodeCf = "";
		String payslip = "";
		String tranId = "";
		boolean isInBaseCurr =false;
		int count = 0;
		int cnt1 = 0 ;
		int cnt = 0;
		double exchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double advAmt = 0.0;
		double netAmt = 0.0;
		double chqAmt = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double ediOption = 0.0;
		double netAmountBc = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		HashMap detListMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap receivablesMap = null;
		HashMap epcadjMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();
		ITMDBAccessEJB itmDBAccessEJB = null;
		try
		{
			finCommon =new  FinCommon();

			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			java.util.Date today=	new java.sql.Date(new java.util.Date().getTime());
			itmDBAccessEJB = new ITMDBAccessEJB();

			linkType = (String)MapHrd.get("link_type");
			tranId = (String)MapHrd.get("tran_id");

			if(!linkType.equalsIgnoreCase("R") && !linkType.equalsIgnoreCase("C"))
			{


				tranDate = (Date)MapHrd.get("tran_date");
				refDate = (Date)MapHrd.get("ref_date");
				effDate = (Date)MapHrd.get("eff_date");
				remarks = (String)MapHrd.get("remarks");

				finEntity = (String)MapHrd.get("fin_entity__from");
				siteCode = (String)MapHrd.get("site_code__from");

				bankCode = (String)MapHrd.get("bank_code");

				acctCode = (String)MapHrd.get("acct_code__ifr");
				cctrCode = (String)MapHrd.get("cctr_code__ifr");

				currCode = (String)MapHrd.get("curr_code");
				exchRate = (Double)MapHrd.get("exch_rate");



				glTraceMap = new HashMap();
				glTraceMap.put("tran_date", new Timestamp(tranDate.getTime()));
				glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
				glTraceMap.put("fin_entity", finEntity);
				glTraceMap.put("site_code", siteCode);
				glTraceMap.put("sundry_type", "O");
				glTraceMap.put("sundry_code", "");
				glTraceMap.put("acct_code", acctCode);
				glTraceMap.put("cctr_code", cctrCode);
				glTraceMap.put("emp_code", "");
				glTraceMap.put("anal_code", "");
				glTraceMap.put("curr_code", currCode);
				glTraceMap.put("exch_rate", exchRate);
				if((Double)MapHrd.get("amount") > 0 )
				{
					glTraceMap.put("dr_amt", 0.0);
					glTraceMap.put("cr_amt", (Double)MapHrd.get("amount"));
				}

				else{
					glTraceMap.put("dr_amt", 0 - (Double)MapHrd.get("amount"));
					glTraceMap.put("cr_amt", 0.0);
				}
			}

			glTraceMap.put("ref_type","F");
			glTraceMap.put("ref_ser", "P-IBCA");
			glTraceMap.put("ref_id", tranId);
			glTraceMap.put("remarks", remarks);

			System.out.println("1766 glTraceUpdate Called..............");
			errString = finCommon.glTraceUpdate(glTraceMap,conn); 
			if(errString != null && errString.trim().length() > 0)
			{
				return errString;
			}

		}
		catch(Exception e)
		{

			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}




	private  String gbfPostPibcaDetIss(HashMap MapHrd, ArrayList MapDet ,String xtraParams ,Connection conn) throws ITMException
	{
		System.out.println("gbfPostPibcaDetIss called..............");
		String errString = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		String acctCode = "";
		String cctrCode = ""; 
		String recoAcctCode = "";
		String recoCctrCode = "";
		String taxAcctCode = "";
		String taxCctrCode = "";
		String acctCode1 = "";
		String cctrCode1 = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String contactCode = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String tranType = "";
		String empCode = "";
		String refNO = "";
		String rcpMode = "";
		String batchNo = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String sql = "";
		String hcurrCode = "";
		String errorType = "";
		String payslip = "";
		String partyDocRef = "";
		String refSer = "";
		String refNo = "";
		String salesPers = "";
		String status = "";
		String lineNoPef = "";
		String link = "";
		String finlink = "";
		String code = "";
		String tranId = "";
		int count = 0;
		int lineNo = 0;
		int cnt =0;
		double exchRate = 0.0;
		double hexchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double taxAmount = 0.0;
		double recoAmount = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double advAmt = 0.0;
		double adjAmt = 0.0;
		double advAdj = 0.0;
		double recoverAmt = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		Date frDate = null;
		HashMap DetMap = null;
		HashMap RcpDetMap = null;
		HashMap ADetMap = null;
		HashMap EpcAdjMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap detListMap = null;
		HashMap recofiltMap = null;
		HashMap recodataMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		DistCommon distCommon = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();

		java.util.Date dateInterest = null;
		try
		{
			finCommon = new  FinCommon();
			distCommon = new DistCommon();
			itmDBAccessEJB = new ITMDBAccessEJB();
			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginCode");

			finlink = finCommon.getFinparams("999999", "ADM_FIN_LINK", conn);

			tranDate = (Date)MapHrd.get("tran_date");
			effDate = (Date)MapHrd.get("eff_date");

			finEntity = (String)MapHrd.get("fin_entity__from");
			siteCode = (String)MapHrd.get("site_code__from");
			tranId = (String)MapHrd.get("tran_id");
			hcurrCode = (String)MapHrd.get("curr_code");
			hexchRate = (Double)MapHrd.get("exch_rate");
			remarks = (String)MapHrd.get("remarks");
			link    =  (String)MapHrd.get("link_type");

			System.out.println("DetList SIZE "+MapDet.size());
			System.out.println("DetList SIZE "+MapDet);

			for (int ctr =0; ctr < MapDet.size(); ctr++)
			{

				System.out.println("no of times "+ctr);
				DetMap = new HashMap();
				DetMap = (HashMap) MapDet.get(ctr);

				System.out.println("DetMap SIZE "+DetMap);

				/* sundryType = (String)detListMap.get("sundry_type");
			sundryCode = (String)detListMap.get("sundry_code");					
			acctCode = (String)detListMap.get("acct_code");
			cctrCode = (String)detListMap.get("cctr_code");
			analCode = (String)detListMap.get("anal_code");
			empCode = (String)detListMap.get("emp_code");
			//projectCode = (String)detListMap.get("proj_code");
			currCode = (String)detListMap.get("curr_code");
			exchRate = (Double)detListMap.get("exch_rate");
			partyDocRef = (String)detListMap.get("party_doc_ref");*/


				glTraceMap = new HashMap();
				glTraceMap.put("tran_date",new Timestamp(tranDate.getTime()));
				glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
				glTraceMap.put("fin_entity", finEntity);
				glTraceMap.put("site_code", siteCode);
				glTraceMap.put("sundry_type",(String)DetMap.get("sundry_type")==null?"O":(String)DetMap.get("sundry_type"));
				glTraceMap.put("sundry_code",(String)DetMap.get("sundry_code")== null?"":(String)DetMap.get("sundry_code"));
				glTraceMap.put("acct_code", (String)DetMap.get("acct_code"));
				System.out.println("818 account chek ="+acctCode+"  "+sundryType+"   "+sundryCode);
				glTraceMap.put("cctr_code", (String)DetMap.get("cctr_code")==null?"":(String)DetMap.get("cctr_code"));
				glTraceMap.put("emp_code", "");
				glTraceMap.put("anal_code", "");
				glTraceMap.put("curr_code", (String)DetMap.get("curr_code")==null?hcurrCode:(String)DetMap.get("curr_code"));
				glTraceMap.put("proj_code", projectCode);
				glTraceMap.put("exch_rate", (Double)DetMap.get("exch_rate"));

				amount = (Double)DetMap.get("tot_amt");
				if(amount > 0)
				{
					glTraceMap.put("dr_amt",amount);
					glTraceMap.put("cr_amt",0.0);
				}
				else
				{
					glTraceMap.put("dr_amt",0.0);
					glTraceMap.put("cr_amt",0 - amount);
				}
				glTraceMap.put("ref_type","F");
				glTraceMap.put("ref_ser", "P-IBCA");
				glTraceMap.put("ref_id", tranId);
				glTraceMap.put("remarks",remarks);
				glTraceMap.put("party_doc_ref",partyDocRef);
				System.out.println("848 glTraceUpdate Called..............");
				errString = finCommon.glTraceUpdate(glTraceMap,conn);
				if(errString != null && errString.trim().length() > 0)
				{
					System.out.println("ERROR IN GLTRACE ...........");

					return errString;
				}
				// Populate sundry balance structure /////////////////

				sundryBalMap = new HashMap();
				sundryBalMap.put("tran_date",new Timestamp(tranDate.getTime()));
				sundryBalMap.put("eff_date",new Timestamp(effDate.getTime()));
				sundryBalMap.put("fin_entity", finEntity);
				sundryBalMap.put("site_code", siteCode);
				sundryBalMap.put("sundry_type", sundryType);
				sundryBalMap.put("sundry_code", sundryCode);
				sundryBalMap.put("acct_code", (String)DetMap.get("acct_code"));
				sundryBalMap.put("cctr_code", (String)DetMap.get("cctr_code")==null?"":(String)DetMap.get("cctr_code"));
				sundryBalMap.put("curr_code", (String)DetMap.get("curr_code")==null?hcurrCode:(String)DetMap.get("curr_code"));
				sundryBalMap.put("exch_rate", (Double)DetMap.get("exch_rate"));

				amount = (Double)DetMap.get("tot_amt");
				if(amount > 0)
				{
					glTraceMap.put("dr_amt",amount);
					glTraceMap.put("cr_amt",0.0);
				}
				else
				{
					glTraceMap.put("dr_amt",0.0);
					glTraceMap.put("cr_amt",0 - amount);
				}
				sundryBalMap.put("adv_amt", 0.0);

				contactCode = finCommon.getContactCode(sundryType, sundryCode, conn);
				sundryBalMap.put("contact_code",contactCode );
				System.out.println("2366 sundryBaleUpdate Called..............");
				errString = finCommon.gbf_sundrybal_upd(sundryBalMap, conn);
				if(errString != null && errString.trim().length() > 0)
				{
					System.out.println("error is sundryBaleUpdate ..........."+errString);

					return errString;
				}
			}
			System.out.println("last ...........");


			for (int ctr =0; ctr < MapDet.size(); ctr++)
			{
				RcpDetMap = new HashMap();
				RcpDetMap = (HashMap) MapDet.get(ctr);


				refSer = (String)RcpDetMap.get("ref_ser");
				refNo = (String)RcpDetMap.get("ref_no");
				amount = (Double)RcpDetMap.get("rcp_amt");
				lineNoPef = (String)RcpDetMap.get("line_no__ref");


				itmDBAccessEJB = new ITMDBAccessEJB();

				if ("db2".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql = "SELECT tot_amt, adj_amt FROM receivables  WHERE tran_ser = ?  and ref_no = ?  for update ";
				}

				else if ( "mssql".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql = "SELECT tot_amt, adj_amt FROM receivables (updlock) where tran_ser = ?  and ref_no = ?  " ;
				}
				else
				{
					sql =" SELECT tot_amt, adj_amt FROM receivables WHERE tran_ser = ?  and ref_no = ?  for update nowait" ;
				}
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,refSer);
				pstmt.setString(2,refNo);

				rs = pstmt.executeQuery();
				while(rs.next())
				{
					totAmt = rs.getDouble("tot_amt");
					adjAmt = rs.getDouble("adj_amt");
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				if(Math.abs(amount - adjAmt) < Math.abs(amount))
				{
					errString = itmDBAccessEJB.getErrorString("","VTBAL1","","",conn);
					return errString;
				}


				adjAmt = adjAmt + totAmt;
				if(totAmt == adjAmt)
				{
					status = "A";
				}
				else
				{
					status = "P";
				}


				sql = "update misc_payables set adj_amt = ?, status = ?,stat_date = ? where tran_ser = ? and ref_no = ? and line_no__ref = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setDouble(1,adjAmt+amount);
				pstmt.setString(2,status);
				pstmt.setDate(3,new java.sql.Date(new java.util.Date().getTime()));
				pstmt.setString(4,refSer);
				pstmt.setString(5,refNo);
				pstmt.setString(6,lineNoPef);
				pstmt.executeUpdate();
				pstmt.close();
				pstmt = null;

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


			}



			// if ibca is for loans related to payroll then update the interest date
			// in the loans table

			if("P-VOUC".equals(refSer) && "Y".equals(finlink)) 
			{

				sql = "select tran_type, ref_no  from payr_voucher where tran_id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,refNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					tranType = rs.getString(1);
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				if("LN".equalsIgnoreCase(tranType))
				{
					sql = "select date__interest  from loans where loan_no = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,refNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						dateInterest = rs.getDate(1);
					}

					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					if(dateInterest == null)
					{
						sql = "select code, fr_date, to_date from period  where ? between fr_date and to_date";
						pstmt.setDate(1,new java.sql.Date(tranDate.getDate()));
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							code = rs.getString(1);
							frDate = rs.getDate(2);
						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						sql = "select count(*)  from payroll where prd_code = ? and emp_code = ?";
						pstmt.setString(1,code);
						pstmt.setString(2,checkNull((String)DetMap.get("sundry_code")));
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							cnt =rs.getInt(1);
						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(cnt >0)
						{
							sql = "select code  from period where fr_date = ?";
							pstmt.setDate(1,new java.sql.Date(frDate.getDate()));
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								code =rs.getString(1);
							}
						}



						sql ="update loans set start_reco where loan_no = ?";
						pstmt.setDate(1,new java.sql.Date(frDate.getDate()));
						pstmt.setString(2,refNo);
						pstmt.executeUpdate();

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						sql =" update loans set date__interest = ?, start_dedn = 'Y'" +
								"where loan_no = ? ";
						pstmt.setDate(1,new java.sql.Date(tranDate.getDate()));
						pstmt.setString(2,refNo);
						pstmt.executeUpdate();

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

					}

				}

			}	


			if("A".equalsIgnoreCase(link))
			{
				errString = gbfPostPibcaDetRcp(MapHrd, MapDet ,xtraParams ,conn);
				return errString;

			}

			if("R".equalsIgnoreCase(link))
			{
				errString = gbfPostPibcaDetRcp(MapHrd, MapDet ,xtraParams ,conn);
				return errString;

			}
			if("C".equalsIgnoreCase(link))
			{
				errString = gbfPostPibcaDetRcp(MapHrd, MapDet ,xtraParams ,conn);
				return errString;

			}

		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}



	private  String gbfCreateCrdrAdj (String dbnoteId, String calledFrom , Connection conn) throws RemoteException, ITMException

	{
		String 	 invibcagen = "", site	= "", cust = "", sitePay = "", finentFr = "", finentTo = "", acctTo	= "", 
				cctrTo = "" , link	= "" , acctFr = "", cctrFr = "", ibcaId = "" , currCd = "" , acct = "", cctr = "", 
				bank = "" , reftype = "" , crterm = ""  ,  	sundryCode = ""	, sundryType = "" , finEntity = "" , 
				itemSer  = "" ,drTranId = "" ,	errcode = "" , remark = "" , salesPers = "" ,taxClass = ""	,	
				taxChap = "" , taxEnv = "" , reasCode = "" , itemCode = "" ,tranId	= "" , keystr = "" , mpadjTranid = "" ,	
				mpayTranid = "" , confDrcrOpt = "", acctCodeCf = "" , cctrCodeCf = "" ,	 crTranId = "",		
				invoiceid = "" , transerCr	= "" ,autoLinktype = "" ,	autoConfirm = "" , transerDb = "" , sql = "" ,
				keyString = "" , errString = "";
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		java.util.Date now	= new Date();
		java.util.Date dueDate	= null;
		java.util.Date Date	= new Date();

		double exch	=0.0, factor=0.0, discount =0.0 , amountBc  = 0.0 ,	amount	= 0.0,	taxAmt	= 0.0 ,
				netAmt	= 0.0  , drcrAmt = 0.0 , totamt	= 0.0 , adjamt = 0.0 , rows = 0  , totrow	= 0 ;
		int cnt = 0;

		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			sql = "select invoice_id, sundry_code, amount, site_code, curr_code from  drcr_inv" +
					" where	 tran_id = ? and drcr_flag = 'D' " ;

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, dbnoteId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				invoiceid = rs.getString(1);
				sundryCode = rs.getString(2);
				amount = rs.getDouble(3);
				site = rs.getString(4);
				currCd = rs.getString(5);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;


			sql = "select tran_id	from drcr_inv  where  invoice_id = ? and	 sundry_code = ? and	 drcr_flag = 'C' " +
					"and  curr_code = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, invoiceid);
			pstmt.setString(2, sundryCode);
			pstmt.setString(3, currCd);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				crTranId  = rs.getString(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql = "select count(1)   from misc_payables where ref_no = ? and tran_ser = 'P-IBCA' ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, crTranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				cnt  = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if(cnt == 0 )
			{

				transerCr = "CRNINV" ;
			}
			else
			{
				transerCr = "P-IBCA" ;
			}


			if("SR".equalsIgnoreCase(calledFrom))
			{
				sql = "select site_code__pay   from sales_pers  where sales_pers = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, salesPers);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					sitePay  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = " select auto_confirm from ibca_pay_ctrl where site_code__from = ? and site_code__to 	= ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, site);
				pstmt.setString(1, sitePay);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					autoConfirm  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = " select link_type from pay_ibca hdr, pay_ibca_det det where hdr.tran_id = det.tran_id" +
						"and	det.sundry_code = ? and	det.ref_ser = 'DRNINV' and	det.ref_no = ?" ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, sundryCode);
				pstmt.setString(2, drTranId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					link  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if("A".equalsIgnoreCase(autoLinktype) || ("P".equalsIgnoreCase(autoLinktype) &&  "A".equalsIgnoreCase(autoConfirm)))
				{
					autoLinktype = "Y";
				}

				else
				{
					autoLinktype = "N";
				}
			}

			if(!"SR".equalsIgnoreCase(calledFrom) || ("SR".equalsIgnoreCase(calledFrom) && "Y".equalsIgnoreCase(autoLinktype)))
			{
				sql = "select tot_amt, adj_amt from	misc_payables WHERE tran_ser = ? AND ref_no = ? AND sundry_code = ?" ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, transerCr);
				pstmt.setString(2, crTranId);
				pstmt.setString(3, sundryCode);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					totamt = rs.getDouble(1);
					adjamt = rs.getDouble(2);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(adjamt == totamt)
				{
					errString = itmDBAccessEJB.getErrorString("","VTADJAMTSP","","",conn);
					return errString;
				}
				else if ((totamt -adjamt) < netAmt)
				{
					errString = itmDBAccessEJB.getErrorString("","VTBALAMTSP","","",conn);
					return errString;

				}

				sql = "UPDATE misc_payables SET status = (case when (adj_amt + ?) = tot_amt then 'A' else 'P' end)," +
						"status_date = ?, adj_amt = (case when adj_amt is null then 0 else adj_amt end) + ? WHERE tran_ser = ?" +
						" AND ref_no = ? AND sundry_code = ?" ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setDouble(1, netAmt);
				pstmt.setDate(2, new java.sql.Date(Date.getTime()));
				pstmt.setDouble(3, netAmt);
				pstmt.setString(4, transerCr);
				pstmt.setString(5, tranId);
				pstmt.setString(6, sundryCode);
				pstmt.executeUpdate();

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				sql = "select key_string from transetup where upper(tran_window) = 'T_MISC_PAY_ADJ'";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					keyString = rs.getString("key_string");
				}
				else
				{
					sql = "select key_string from transetup where upper(tran_window) = 'GENERAL'";
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						keyString = rs.getString("key_string");
					}
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				//ls_mpadj_tranid = gf_gen_key_nvo(lds_keygen, 'PAYADJ', 'tran_id', ls_keystr)
				TransIDGenerator tg = new TransIDGenerator("", "SYSTEM", CommonConstants.DB_NAME);
				mpadjTranid = tg.generateTranSeqID("PAYADJ", "tran_id", keyString, conn);


				sql = "select count(1) from misc_payables  where ref_no = ? and tran_ser = 'P-IBCA'";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, drTranId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					cnt = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(cnt == 0)

				{
					transerDb = "DRNINV";
				}
				else
				{
					transerDb = "P-IBCA";
				}

				sql = "select tran_id  from misc_payables where tran_ser = 'DRNINV'  and ref_no = ? and sundry_code = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, drTranId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					mpayTranid = rs.getString(1);
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				sql  = "UPDATE misc_payables SET adj_amt = ? * -1,  status = 'A', status_date = ? where tran_ser = ? AND ref_no = ? AND sundry_code = ?";	
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, new java.sql.Date(Date.getTime()));
				pstmt.setString(2, transerDb);
				pstmt.setString(3, tranId);
				pstmt.setString(4, sundryCode);
				pstmt.executeUpdate();

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				sql = "INSERT INTO misc_payables_adj (tran_id, ref_ser, ref_no, tot_amt, adj_amt, ref_ser_adj,ref_no_adj, net_amt, tran_id__pay) VALUES (?, ?, ? , ? , ?, ?, ?, ?, ?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, mpadjTranid);
				pstmt.setString(2, "DRNINV");
				pstmt.setString(3, drTranId);
				pstmt.setDouble(4, netAmt);
				pstmt.setDouble(5, netAmt);
				pstmt.setString(6, "CRNINV");
				pstmt.setString(7, crTranId);
				pstmt.setDouble(8, 0);
				pstmt.setString(9, mpayTranid);
				pstmt.executeUpdate();

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = "select tran_id from misc_payables where tran_ser = 'CRNINV' and ref_no = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, crTranId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					mpayTranid = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = " INSERT INTO misc_payables_adj (tran_id, ref_ser, ref_no, tot_amt, adj_amt, ref_ser_adj,ref_no_adj, net_amt, tran_id__pay)" +
						"VALUES (?,?,?,?,?,?,?,?,?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, mpadjTranid);
				pstmt.setString(2, "DRNINV");
				pstmt.setString(3, crTranId);
				pstmt.setDouble(4, netAmt);
				pstmt.setDouble(5, netAmt);
				pstmt.setString(6, "");
				pstmt.setString(7, "");
				pstmt.setDouble(8, 0);
				pstmt.setString(9, mpayTranid);
				pstmt.executeUpdate();	

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}


		return errString;
	}

	private  String updateCreditNote (HashMap hrd ,HashMap det ,String post , String xtraParams ,Connection conn) throws ITMException
	{
		String invoiceId = "";
		String voucherNo = "";
		String errString = "";
		String trainId = "";

		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();
		try {

			if(hrd.size() < 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTBALAMTSP","","",conn);
				return errString;
			}
			else
			{
				if(det.size() < 0)
				{
					errString = itmDBAccessEJB.getErrorString("","VTBALAMTSP","","",conn);
					return errString;
				}
				else 
				{

					/// set null to invoice id in header // amish 21-01-04
					for (int row = 1 ; hrd.size() > row ;row++)
					{
						invoiceId = (String)hrd.get("invoice_id");
						voucherNo = (String)hrd.get("voucher_no");

						if(invoiceId.trim().length() == 0 )
						{
							hrd.put("invoice_id", "");

						}
						else
						{
							det.put("voucher_no", "");

						}
					}

					/// set null to invoice id in detail // amish 21-01-04
					for (int row = 1 ; det.size() > row ;row++)
					{
						invoiceId = (String)det.get("invoice_id");
						voucherNo = (String)det.get("voucher_no");

						if(invoiceId.trim().length() == 0 )
						{
							hrd.put("invoice_id", "");
							// 	lds_drcr_inv_hdr.setitem(ll_row,'invoice_id',ls_null)
						}
						else
						{
							det.put("voucher_no", "");
							//lds_drcr_inv_det.setitem(ll_row,'voucher_no',ls_null)	
						}
					}

					if("Y".equals(post))
					{
						trainId = (String)hrd.get("tran_id");
						errString = gbfRetrieveDrCr(trainId, trainId, 1, xtraParams, conn);

					}

				}

			}
		}catch(Exception e ){
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);

		}
		return errString;
	}



	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
	
	
	private String checkNull( String input )
	{
		if ( input == null )
		{
			input = "";
		}
		return input;
	}

	private String commCrditNote(String invno, int factor, String post,String calledFrom,String xtraParams , Connection conn) throws Exception

	{	
		String invoiceId = "", currCode = "", finEnt = "", siteCode = "", itemCode = "", salesPer = "", 
				common = "", dlvTerm = "", errCode = "" , oldSp = "", itemSer = "", tranSer = "" ,remarks = "", 
				trnofld = "", keyStr = "", crTerm = "", acctCode = "", cctrcode = "", autoTranId = "", 
				insReqd = "", frtReqd = "", acctcodeExp = "", cctrcodeExp = "", hdr = "", det = "", 
				saleOrder = "", slineNo = "", currcodeSp = "", str1 = "", despId = "", fchgType = "", 
				acctcodeDeduct = "" , cctrcodeDeduct = "", currCodeBase = "", rcpRefser = "", rcpSitecd = "", 
				currcdSpOld = "",  commHdr = "", sitecodeOld = "" , sql = "" , commCalc = "", acctCodecf = "" ,
				cctrCodecf = ""  ,taxClass  = "" , taxChap = "" , cctrCodeAp  = "" , acctCodeAp  = "" ,
				siteCodeRcp = "" , siteCodeCd = "" , errString = "" , tranType = "" , salesPers = "" , tranId = ""
				, currCodeSp = "" , iddate = "" , taxEnv = "" ,tranIdInvdet = "", sreCurrCode = "" , xmlString = null;

		StringBuffer xmlBuff = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		HashMap commMap = new HashMap();
		ArrayList commtList = new ArrayList();
		SimpleDateFormat sdf  = null;
		GenericUtility genericUtility = null;

		sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());

		Double invAmt = 0.0 , frtAmt = 0.0, netAmt = 0.0, qtyStduom = 0.0, rateStduom = 0.0,
				commfrt = 0.0 , commInsu = 0.0 , detInvamt = 0.0, commPerc = 0.0, ordAmt = 0.0, insuAmt = 0.0,
				totNetAmt = 0.0 , drcrAmt = 0.0, invDisc = 0.0 , val = 0.0, val1 = 0.0, commQty = 0.0, amount = 0.0,
				exchRate = 0.0 , exchrateSp , jvExchrate = 0.0, crntExchrate = 0.0, commPerc1 = 0.0, commperc2 = 0.0,
				exchRateSp = 0.0 , rcpExchRateTot = 0.0 ,invNetamt = 0.0 , sretPerc = 0.0 , sretNetAmt = 0.0 ,
				sretExchRate = 0.0 , finChg = 0.0;


		PreparedStatement pstmt = null;
		ResultSet rs = null;

		int crdays = 0 ,refLineNo = 0 , count = 0 , lineNo = 0 , lineNoInv = 0 ,invLineNo = 0 ,days = 0;

		java.util.Date tranDate  = new Date();
		java.util.Date date = new Date();
		java.util.Date dueDate = new Date();

		FinCommon finCommon = new FinCommon();
		tranSer = "CRNINV";
		trnofld = "tran_id";
		remarks = "Agst Receipt No ";
		try
		{

			sql = "select key_string from transetup where upper(tran_window) = 'W_DRCRINV'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{

				keyStr = rs.getString(1);
			}
			else
			{
				sql = "select key_string from transetup where upper(tran_window) = 'GENERAL'";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();	
				if(rs.next())
				{

					keyStr = rs.getString(1);
				}
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;


			// get the a/c code for commission expense a/c
			if(errCode == null || errCode.trim().length() == 0 )
			{
				if("I".equalsIgnoreCase(calledFrom))
				{
					acctcodeExp = finCommon.getFinparams("999999", "COMM_EXP_ACCT", conn);
					if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
					{
						errString = itmDBAccessEJB.getErrorString("","VTBALAMTSP","","",conn);
						return errString;
					}
					else
					{
						cctrcodeExp = finCommon.getFinparams("999999", "COMM_EXP_CCTR", conn);
						if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
						{
							errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
							return errString;
						}
					}
				}else if ("P".equalsIgnoreCase(calledFrom))
				{
					acctcodeExp = finCommon.getFinparams("999999", "SAL_COM_PROV_REV_ACT", conn);
					if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
					{
						errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
						return errString;
					}
					else
					{
						cctrcodeExp = finCommon.getFinparams("999999", "SAL_COM_PROV_REV_CTR", conn);
						if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
						{
							errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
							return errString;
						}
					}
				}
				else
				{
					acctcodeExp = finCommon.getFinparams("999999", "PROV_COMM_ACCT", conn);
					if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
					{
						errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
						return errString;
					}
					else
					{
						cctrcodeExp = finCommon.getFinparams("999999", "PROV_COMM_CCTR", conn);
						if("NULLFOUND".equalsIgnoreCase(acctcodeExp))
						{
							errString = itmDBAccessEJB.getErrorString("","VTFINPARM","","",conn);
							return errString;
						}
					}
				}

			}

			commCalc = finCommon.getFinparams("999999", "COMM_CALC", conn);
			invoiceId = invno ;

			sql = "Select acct_code__cf, cctr_code__cf from bank where bank_code = (Select bank_code from site where" +
					" site_code = (select site_code from invoice where invoice_id = ?))";

			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				acctCodecf = rs.getString("acct_code__cf");
				cctrCodecf = rs.getString("cctr_code__cf");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;


			sql = "select sale_order from invoice where invoice_id = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, invoiceId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				saleOrder = rs.getString("sale_order");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql = "select comm_perc, comm_perc_1, comm_perc_2 from	sorder  where sale_order = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, saleOrder);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				commPerc = rs.getDouble("comm_perc");
				commPerc1 = rs.getDouble("comm_perc_1");
				commperc2 = rs.getDouble("comm_perc_2");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			commHdr = "N";
			if(commPerc != null || (commPerc1 != null  || commperc2 != null ))
			{
				commHdr = "Y";
			}
			if("Y".equalsIgnoreCase(commHdr))
			{

				sql = "select invoice_id, ref_line_no, inv_amt, frt_amt, item_ser, tran_date, eff_date, curr_code, exch_rate, fin_entity, site_code," +
						" sales_pers,comm_perc__on,comm_perc,dlv_term, ord_amt, insu_amt,sorder_no, curr_code_sp, exch_rate_sp,comm_amt from (" +
						" select DISTINCT a.invoice_id, 1 as ref_line_no, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt," +
						" a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date,a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity," +
						" a.site_code site_code,d.sales_pers sales_pers,(case when (case when d.comm_perc__on is null then ' ' else d.comm_perc__on end) = ' ' " +
						" then c.comm_perc_on_1 else d.comm_perc__on end) comm_perc__on, (case when (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end)  = 0 " +
						" then (case when d.comm_perc is null then 0 else d.comm_perc end) else (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt, (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm) insu_amt,d.sale_order sorder_no, d.curr_code__comm curr_code_sp, " +
						" d.exch_rate__comm exch_rate_sp, (case when (case when b.sales_pers_comm_1 is null then 0 else b.sales_pers_comm_1 end) = 0 " +
						" then a.sales_pers_comm_1 else b.sales_pers_comm_1 end) comm_amt from invoice a, invdet b, sorddet c, sorder d 	where a.invoice_id = b.invoice_id  " +
						" and b.sord_no = c.sale_order and b.sord_line_no = c.line_no  and c.sale_order = d.sale_order  and a.invoice_id = ? and " +
						" (case when d.sales_pers is null then ' ' else d.sales_pers end) <> ' ' UNION ALL select DISTINCT a.invoice_id, 2 as ref_line_no, a.inv_amt inv_amt," +
						"  a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code,  a.exch_rate exch_rate," +
						"  a.fin_entity fin_entity, a.site_code site_code, d.sales_pers__1 sales_pers, (case when (case when d.comm_perc_on_1 is null then ' ' else d.comm_perc_on_1 end) = ' ' " +
						" then c.comm_perc_on_2 else d.comm_perc_on_1 end) comm_perc__on, (case when (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) = 0 then " +
						" (case when d.comm_perc_1 is null then 0 else d.comm_perc_1 end) else (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt, (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_1) insu_amt, d.sale_order sorder_no, d.curr_code__comm_1 curr_code_sp, " +
						" d.exch_rate__comm_1 exch_rate_sp,(case when (case when b.sales_pers_comm_2 is null then 0 else b.sales_pers_comm_2 end) = 0 " +
						" then a.sales_pers_comm_2 else b.sales_pers_comm_2 end) comm_amt from invoice a,invdet b, sorddet c, sorder d 	where a.invoice_id = b.invoice_id " +
						" and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no and c.sale_order = d.sale_order  and a.invoice_id = ?  " +
						" and (case when d.sales_pers__1 is null then ' ' else d.sales_pers__1 end) <> ' ' UNION ALL SELECT DISTINCT a.invoice_id, 3 as ref_line_no, " +
						" a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code," +
						" a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code, d.sales_pers__2 sales_pers, (case when (case when d.comm_perc_on_2 is null then ' ' else d.comm_perc_on_2 end) = ' ' " +
						" then c.comm_perc_on_3 else d.comm_perc_on_2 end) comm_perc__on, (case when (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) = 0 then " +
						" (case when d.comm_perc_2 is null then 0 else d.comm_perc_2 end) else (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) end) comm_perc, d.dlv_term dlv_term, d.ord_amt ord_amt, " +
						" (d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_2) insu_amt , d.sale_order sorder_no, d.curr_code__comm_2 curr_code_sp, d.exch_rate__comm_2 exch_rate_sp," +
						" (case when (case when b.sales_pers_comm_3 is null then 0 else b.sales_pers_comm_3 end) = 0 then a.sales_pers_comm_3 else b.sales_pers_comm_3 end) comm_amt " +
						" from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order  " +
						" and a.invoice_id = ? and (case when d.sales_pers__2 is null then ' ' else d.sales_pers__2 end) <> ' ' ) commtab  where " +
						"((case when sales_pers is null then ' ' else sales_pers end) <> ' ')  and	((case when comm_perc__on is null then ' ' else comm_perc__on end) <> ' ') " +
						" and comm_amt > 0 order by invoice_id, sales_pers, comm_perc__on";

				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, invoiceId);
				pstmt.setString(2, invoiceId);
				pstmt.setString(3, invoiceId);

				rs = pstmt.executeQuery();
				while(rs.next())
				{
					commMap.put("invoice_id",rs.getString("invoice_id"));
					commMap.put("ref_line_no" ,rs.getString("ref_line_no"));
					commMap.put("inv_amt" ,rs.getDouble("inv_amt"));
					commMap.put("frt_amt" ,rs.getDouble("frt_amt"));
					commMap.put("item_ser" ,rs.getString("item_ser"));
					commMap.put("tran_date" ,rs.getDate("tran_date"));
					commMap.put("eff_date " ,rs.getDate("eff_date"));
					commMap.put("curr_code" ,rs.getString("curr_code"));
					commMap.put("exch_rate" , rs.getDouble("exch_rate"));
					commMap.put("fin_entity" , rs.getString("fin_entity"));		
					commMap.put("site_code" , rs.getString("site_code"));	
					commMap.put("sales_pers" , rs.getString("sales_pers"));
					commMap.put("comm_perc__on" , rs.getString("comm_perc__on"));
					commMap.put("comm_perc" ,  rs.getString("comm_perc"));
					commMap.put("dlv_term" , rs.getString("dlv_term"));					
					commMap.put("ord_amt" , rs.getDouble("ord_amt"));
					commMap.put("insu_amt" , rs.getDouble("insu_amt"));
					commMap.put("sorder_no" , rs.getString("sorder_no"));
					commMap.put("curr_code_sp" , rs.getString("curr_code_sp"));
					commMap.put("exch_rate_sp" , rs.getDouble("exch_rate_sp"));

					commtList.add(commMap);

				}

			}
			else
			{
				sql = "select ref_line_no , invoice_id, inv_amt, frt_amt, item_ser, tran_date, eff_date, curr_code, exch_rate, fin_entity, site_code, line_no__inv, item_code, net_amt, " +
						" quantity__stduom, rate__stduom, inv_disc, comm_frt, comm_insu, amt_inv, sales_pers, comm_perc__on, comm_perc, dlv_term, ord_amt, insu_amt, sorder_no, " +
						" sline_no, curr_code_sp, exch_rate_sp, comm_amt from ( select 1 as ref_line_no,a.invoice_id, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt," +
						" a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code,  " +
						" b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom, b.discount inv_disc,(case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) " +
						" / a.inv_amt * a.frt_amt end) comm_frt, (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) / d.ord_amt * d.ins_amt end) comm_insu, " +
						" b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv,b.sord_line_no sline_no, d.sales_pers sales_pers,(case when (case when d.comm_perc__on is null then ' ' " +
						" else d.comm_perc__on end) = ' ' then c.comm_perc_on_1 else d.comm_perc__on end) comm_perc__on, (case when (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end)" +
						"  = 0 then (case when d.comm_perc is null then 0 else d.comm_perc end) else (case when c.comm_perc_1 is null then 0 else c.comm_perc_1 end) end) comm_perc," +
						" d.dlv_term dlv_term, d.ord_amt ord_amt,d.ins_amt * d.exch_rate__ins / d.exch_rate__comm insu_amt, d.sale_order sorder_no, d.curr_code__comm curr_code_sp, d.exch_rate__comm exch_rate_sp, " +
						" (case when b.sales_pers_comm_1 is null then 0 else b.sales_pers_comm_1 end)  comm_amt from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id  " +
						" and b.sord_no = c.sale_order 	and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order and a.invoice_id = ? and (case when d.sales_pers is null then ' ' else d.sales_pers end) <> ' '	" +
						" union all select 2 as ref_line_no, a.invoice_id, a.inv_amt inv_amt, a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt, a.item_ser item_ser, 	a.tran_date tran_date," +
						"  a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, a.site_code site_code,b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom," +
						" b.discount inv_disc, (case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt) / a.inv_amt * a.frt_amt end) comm_frt, " +
						" (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)  / d.ord_amt * d.ins_amt end) comm_insu, 	b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv," +
						"  b.sord_line_no sline_no, d.sales_pers__1 sales_pers, (case when (case when d.comm_perc_on_1 is null then ' ' else d.comm_perc_on_1 end) = ' ' then c.comm_perc_on_2 else d.comm_perc_on_1 end) " +
						" comm_perc__on, (case when (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) = 0 then (case when d.comm_perc_1 is null then 0 else d.comm_perc_1 end) else " +
						" (case when c.comm_perc_2 is null then 0 else c.comm_perc_2 end) end) comm_perc,d.dlv_term dlv_term, d.ord_amt ord_amt, d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_1 insu_amt," +
						" d.sale_order sorder_no,d.curr_code__comm_1 curr_code_sp, d.exch_rate__comm_1 exch_rate_sp, (case when b.sales_pers_comm_2 is null then 0 else b.sales_pers_comm_2 end) comm_amt " +
						"  from invoice a, invdet b, sorddet c, sorder d where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order and b.sord_line_no = c.line_no 	and c.sale_order = d.sale_order  	" +
						" and a.invoice_id = ? and (case when d.sales_pers__1 is null then ' ' else d.sales_pers__1 end) <> ' '	union all select 3 as ref_line_no, a.invoice_id, a.inv_amt inv_amt,  " +
						" a.frt_amt * d.exch_rate__frt / a.exch_rate frt_amt , a.item_ser item_ser, a.tran_date tran_date, a.eff_date eff_date, a.curr_code curr_code, a.exch_rate exch_rate, a.fin_entity fin_entity, " +
						" a.site_code site_code, b.line_no line_no__inv, b.item_code, b.net_amt, b.quantity__stduom, b.rate__stduom, b.discount inv_disc, 	(case when a.inv_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)" +
						" / a.inv_amt * a.frt_amt end) comm_frt, (case when d.ord_amt = 0 then 0 else (b.quantity__stduom * b.rate__stduom - b.disc_amt)  / d.ord_amt * d.ins_amt end) comm_insu,  " +
						"  b.quantity__stduom * b.rate__stduom - b.disc_amt amt_inv, b.sord_line_no sline_no, d.sales_pers__2 sales_pers, (case when (case when d.comm_perc_on_2 is null then ' ' else d.comm_perc_on_2 end) = ' ' " +
						" then c.comm_perc_on_3 else d.comm_perc_on_2 end) comm_perc__on, (case when (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) = 0 then (case when d.comm_perc_2 is null then 0 else d.comm_perc_2 end) else " +
						" (case when c.comm_perc_3 is null then 0 else c.comm_perc_3 end) end) comm_perc, d.dlv_term dlv_term, d.ord_amt ord_amt,d.ins_amt * d.exch_rate__ins / d.exch_rate__comm_2 insu_amt , d.sale_order sorder_no, " +
						" d.curr_code__comm_2 curr_code_sp, d.exch_rate__comm_2 exch_rate_sp, (case when b.sales_pers_comm_3 is null then 0 else b.sales_pers_comm_3 end)  comm_amt from invoice a, invdet b, sorddet c, sorder d " +
						" where a.invoice_id = b.invoice_id and b.sord_no = c.sale_order and b.sord_line_no = c.line_no and c.sale_order = d.sale_order  and a.invoice_id = ? and (case when d.sales_pers__2 is null then ' ' else d.sales_pers__2 end) <> ' ' ) " +
						" commtab  where ((case when sales_pers is null then ' ' else sales_pers end) <> ' ')  	and	((case when comm_perc__on is null then ' ' else comm_perc__on end) <> ' ') and comm_amt > 0 order by invoice_id, sales_pers, comm_perc__on ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, invoiceId);
				pstmt.setString(2, invoiceId);
				pstmt.setString(3, invoiceId);

				rs = pstmt.executeQuery();
				if(rs.next())
				{
					commMap.put("invoice_id" , rs.getString("invoice_id"));
					commMap.put("ref_line_no" , rs.getString("ref_line_no"));
					commMap.put("inv_amt" ,rs.getDouble("inv_amt"));
					commMap.put("frt_amt" , rs.getDouble("frt_amt"));
					commMap.put("item_ser" , rs.getString("item_ser"));
					commMap.put("tran_date" , rs.getDate("tran_date"));
					commMap.put("eff_date" , rs.getDate("eff_date"));
					commMap.put("curr_code" , rs.getString("curr_code"));
					commMap.put("exch_rate" , rs.getDouble("exch_rate"));
					commMap.put("fin_entity" , rs.getString("fin_entity"));		
					commMap.put("site_code" , rs.getString("site_code"));				
					commMap.put("line_no__inv" , rs.getInt("line_no__inv"));
					commMap.put("item_code" , rs.getString("item_code"));
					commMap.put("net_amt" , rs.getInt("net_amt"));
					commMap.put("quantity__stduom" , rs.getInt("net_amt"));
					commMap.put("rate__stduom" , rs.getInt("rate__stduom"));
					commMap.put("inv_disc" , rs.getInt("inv_disc"));
					commMap.put("comm_frt" , rs.getString("comm_frt"));
					commMap.put("comm_insu" , rs.getString("comm_insu"));
					commMap.put("amt_inv" , rs.getInt("amt_inv"));
					commMap.put("sales_pers" , rs.getString("sales_pers"));
					commMap.put("comm_perc__on" , rs.getString("comm_perc__on"));
					commMap.put("comm_perc" , rs.getString("comm_perc"));
					commMap.put("dlv_term" , rs.getString("dlv_term"));					
					commMap.put("ord_amt" , rs.getDouble("ord_amt"));
					commMap.put("insu_amt" ,rs.getDouble("insu_amt"));
					commMap.put("sorder_no" , rs.getString("sorder_no"));
					commMap.put("sline_no " , rs.getInt("sline_no"));
					commMap.put("curr_code_sp" ,rs.getString("curr_code_sp"));
					commMap.put("exch_rate_sp" ,  rs.getDouble("exch_rate_sp"));
					commMap.put("comm_amt" , rs.getDouble("comm_amt"));

					commtList.add(commMap);

				}

			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if(oldSp.equalsIgnoreCase(salesPer) || currcdSpOld.equalsIgnoreCase(currcdSpOld))
			{
				oldSp = salesPer;
				currcdSpOld = currcdSpOld;



				sql = "select cr_term , tax_class, tax_chap , tax_env  from sales_pers 	where sales_pers = ?";		
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, salesPer);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					crTerm  = rs.getString("cr_term");
					taxClass  = rs.getString("tax_class");
					taxChap  = rs.getString("tax_chap");
				}

				else
				{
					errString = itmDBAccessEJB.getErrorString("","VTSLPERS1 ","","",conn);
					return errString;
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = " select cr_days  from crterm where cr_term = ?";	
				pstmt.setString(1, crTerm);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					crdays  = rs.getInt("cr_term");
				}
				else
				{
					errString = itmDBAccessEJB.getErrorString("","VTCRTERM1 ","","",conn);
					return errString;

				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

			}
			else
			{

				sql = "select acct_code__ap  cctr_code__ap  from sales_pers where sales_pers = ?";
				pstmt.setString(1, salesPer);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					acctCodeAp  = rs.getString(1);
					cctrCodeAp  = rs.getString(2);
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = "select ins_reqd, frt_reqd  from delivery_term where dlv_term = ?";
				pstmt.setString(1, dlvTerm);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					insReqd  = rs.getString(1);
					frtReqd  = rs.getString(2);
				}
				else
				{
					errString = itmDBAccessEJB.getErrorString("","VTDLV1 ","","",conn);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				jvExchrate = 0.0;

				sql = "select exch_rate  from journal where ref_ser = 'S-INV' and ref_no = ? and ref_line_no = ?";
				pstmt.setString(1, invno);
				pstmt.setInt(2, refLineNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					exchRate  = rs.getDouble(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = "select c.site_code__rcp  from invoice i, customer c where i.invoice_id = ? and	c.cust_code  = i.cust_code ;";
				pstmt.setString(1, invoiceId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					siteCodeRcp  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(siteCodeRcp == null || siteCodeRcp.trim().length() == 0 || siteCodeRcp.equalsIgnoreCase(siteCode))
				{
					rcpRefser = "S-INV";
				}

				else
				{
					rcpRefser = "R-IBCA";
				}


				sql = "Select distinct h.site_code from receipt h, rcpdet d where h.tran_id = d.tran_id" +
						"and d.ref_ser = ? and d.ref_no = ? and " +
						"(case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'";
				pstmt.setString(1, rcpRefser);
				pstmt.setString(2, invoiceId);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					siteCodeCd  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(siteCodeRcp != null && siteCodeRcp.trim().length() > 0)
				{
					siteCode =siteCodeRcp ;
				}

				xmlBuff = null;	
				xmlBuff = new StringBuffer();
				xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
				xmlBuff.append("<DocumentRoot>");
				xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
				xmlBuff.append("<group0>");
				xmlBuff.append("<description>").append("Group0 description").append("</description>");
				xmlBuff.append("<Header0>");
				xmlBuff.append("<objName><![CDATA[").append("sorder_insert").append("]]></objName>");        //sorder modify to sorder_insert by kunal on 14/12/12 
				xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
				xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
				xmlBuff.append("<description>").append("Header0 members").append("</description>");
				xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"sorder_insert\" objContext=\"1\">");  //sorder modify to sorder_insert by kunal on 14/12/12
				xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<order_date><![CDATA["+ sdf.format(date).toString() +"]]></order_date>");
				xmlBuff.append("<site_code><![CDATA["+ siteCode +"]]></site_code>");
				xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
				xmlBuff.append("<fin_entity><![CDATA["+ finEnt +"]]></fin_entity>");
				xmlBuff.append("<sundry_type><![CDATA["+ "P" +"]]></sundry_type>");
				xmlBuff.append("<sundry_code><![CDATA["+salesPer+"]]></sundry_code>");
				xmlBuff.append("<item_ser><![CDATA["+ itemSer +"]]></item_ser>");
				xmlBuff.append("<acct_code><![CDATA["+ acctCode +"]]></acct_code>");
				xmlBuff.append("<cctr_code><![CDATA["+ cctrCodeAp +"]]></cctr_code>");
				xmlBuff.append("<eff_date><![CDATA["+ sdf.format(date).toString() +"]]></eff_date>");
				xmlBuff.append("<curr_code><![CDATA["+ currCodeSp +"]]></curr_code>");


				sql = "select curr_code from finent f, site s where f.fin_entity = s.fin_entity  and	s.site_code  = ?" ;
				pstmt.setString(1, siteCode);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					currCodeBase  = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = "Select distinct h.tran_id from  receipt h, rcpdet d where h.tran_id = d.tran_id " +
						"and d.ref_ser = ? and	d.ref_no = ? and  (case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'";
				pstmt.setString(1, rcpRefser);
				pstmt.setString(2, invoiceId);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					tranId= rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if(!currCode.equalsIgnoreCase(currCodeSp))
				{
					crntExchrate = finCommon.getDailyExchRateSellBuy(currCodeSp, currCodeBase, siteCode, iddate, "S", conn);

				}else
				{
					sql = " Select h.exch_rate from receipt h, rcpdet d where h.tran_id = d.tran_id and	d.ref_ser = ?" +
							" and	d.ref_no = ? and (case when h.confirmed is null then 'N' else h.confirmed end) = 'Y'" +
							"order by h.tran_date, h.tran_id desc";
					pstmt.setString(1, rcpRefser);
					pstmt.setString(2, invoiceId);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						exchRate= rs.getDouble(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					if( crntExchrate > 0 )
					{
						exchRateSp = crntExchrate;
					}
					else
					{
						crntExchrate = exchRateSp;
					}	

				}
				xmlBuff.append("<exch_rate><![CDATA["+ crntExchrate +"]]></exch_rate>");

				if(jvExchrate == 0)
				{
					if( "P".equalsIgnoreCase(commCalc))
					{
						jvExchrate = exchRate;
					}
					else
					{
						if(currCode.equalsIgnoreCase(currCodeSp))
						{
							jvExchrate = crntExchrate;
						}
					}
				}

				rcpExchRateTot = 0.0;
				count = 0;

				tranType = finCommon.getFinparams("999999", "SALES_COMM_TRAN_TYPE", conn);
				if("NULLFOUND".equalsIgnoreCase(tranType))
				{
					errString = itmDBAccessEJB.getErrorString("","VTFINPARM ","","",conn);
					System.out.println("@@@@@2: retString:"+errString);
				}
				xmlBuff.append("<tran_type><![CDATA["+ tranType +"]]></tran_type>");

				// 05-12-02 Arif to set the remarks
				xmlBuff.append("<drcr_flag><![CDATA["+ "C" +"]]></drcr_flag>");
				xmlBuff.append("<emp_code__aprv><![CDATA["+ remarks +"]]></emp_code__aprv>");
				xmlBuff.append("<tran_type><![CDATA["+ tranType +"]]></tran_type>");
				xmlBuff.append("<tran_ser><![CDATA["+ tranSer +"]]></tran_ser>");
				xmlBuff.append("<cr_term><![CDATA["+ crTerm +"]]></cr_term>");
				xmlBuff.append("<due_date><![CDATA["+ remarks +"]]></due_date>");
				xmlBuff.append("<acct_code__cf><![CDATA["+ acctCodecf +"]]></acct_code__cf>");
				xmlBuff.append("<cctr_code__cf><![CDATA["+ cctrCodecf +"]]></cctr_code__cf>");
				xmlBuff.append("</Detail1>");


			}		


			if(errString == null || errString.trim().length() ==0)
			{
				xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"sorder_insert\" objContext=\"2\">");  //sorder modify to sorder_insert by kunal
				xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<line_no><![CDATA["+ lineNo +"]]></line_no>");
				xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
				xmlBuff.append("<line_no__inv><![CDATA["+ lineNoInv +"]]></line_no__inv>");
				xmlBuff.append("<item_code><![CDATA["+ itemCode +"]]></item_code>");
				xmlBuff.append("<tax_class><![CDATA["+ taxClass +"]]></tax_class>");
				xmlBuff.append("<tax_chap><![CDATA["+ taxChap +"]]></tax_chap>");
				xmlBuff.append("<tax_env><![CDATA["+ taxEnv +"]]></tax_env>");
				xmlBuff.append("<acct_code><![CDATA["+ acctcodeExp +"]]></acct_code>");
				xmlBuff.append("<cctr_code><![CDATA["+ cctrcodeExp +"]]></cctr_code>");
				xmlBuff.append("<exch_rate__inv><![CDATA["+ jvExchrate +"]]></exch_rate__inv>");
				xmlBuff.append("</Detail2>");	
				xmlBuff.append("</Header0>");
				xmlBuff.append("</group0>");
				xmlBuff.append("</DocumentRoot>");
				xmlString = xmlBuff.toString();
				System.out.println("...............just before savdata()");
				siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

				errString = saveData(siteCode,xmlString,conn);
				System.out.println("@@@@@2: retString:"+errString);
				


				if(lineNoInv == 0)

				{
					invLineNo = lineNoInv;

				}

				if("SR".equalsIgnoreCase(calledFrom) && "P".equalsIgnoreCase(commCalc))
				{

				}
				else
				{
					sql = "select net_amt from drcr_inv, drcr_invdet  where drcr_inv.tran_id = drcr_invdet.tran_id and " +
							"drcr_inv.invoice_id = ? and drcr_inv.sundry_code = ? " +
							"and drcr_inv.curr_code = ? and drcr_flag = 'D' " +
							"and (case when line_no__inv is null then 0 else line_no__inv end) = ?";
					pstmt.setString(1,tranIdInvdet );				
					pstmt.setString(2, salesPers);
					pstmt.setString(3, currCodeSp);
					pstmt.setInt(4, invLineNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						netAmt = rs.getDouble(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

				}


				sql = "select due_date  from invoice  where invoice_id = ?";
				pstmt.setString(1, invoiceId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{

					dueDate = rs.getDate(1);
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				days = daysBetween(dueDate, date);

				sql =  "select fin_chg,fchg_type from crtermfc where (min_day <= ? and max_day >= ? ) and  cr_term = ? ";
				pstmt.setInt(1,days);
				pstmt.setInt(2, days);
				pstmt.setString(3, crTerm);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					finChg = rs.getDouble(1);
					fchgType = rs.getString(2);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if("P".equalsIgnoreCase(fchgType))
				{


					acctcodeDeduct = finCommon.getFinparams("999999", "DEDUCT_COMM_ACCT", conn);
					if("NULLFOUND".equalsIgnoreCase(acctcodeDeduct) || acctcodeDeduct== null ||acctcodeDeduct.trim().length() == 0)
					{
						acctcodeDeduct = acctcodeExp;
						cctrcodeDeduct = cctrcodeExp;
					}

					else
					{
						acctcodeDeduct = finCommon.getFinparams("999999", "DEDUCT_COMM_CCTR", conn);
						if("NULLFOUND".equalsIgnoreCase(cctrcodeDeduct) || cctrcodeDeduct== null ||cctrcodeDeduct.trim().length() == 0)
						{

							cctrcodeDeduct = cctrcodeExp;
						}
					}

				}


				xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"sorder_insert\" objContext=\"2\">");  //sorder modify to sorder_insert by kunal
				xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<line_no><![CDATA["+ lineNo++ +"]]></line_no>");
				xmlBuff.append("<invoice_id><![CDATA["+ invoiceId +"]]></invoice_id>");
				xmlBuff.append("<line_no__inv><![CDATA["+ lineNoInv +"]]></line_no__inv>");
				xmlBuff.append("<item_code><![CDATA["+ itemCode +"]]></item_code>");
				xmlBuff.append("<tax_class><![CDATA["+ taxClass +"]]></tax_class>");
				xmlBuff.append("<tax_chap><![CDATA["+ taxChap +"]]></tax_chap>");
				xmlBuff.append("<tax_env><![CDATA["+ taxEnv +"]]></tax_env>");
				xmlBuff.append("<acct_code><![CDATA["+ acctcodeDeduct +"]]></acct_code>");
				xmlBuff.append("<cctr_code><![CDATA["+ cctrcodeDeduct +"]]></cctr_code>");
				xmlBuff.append("<exch_rate__inv><![CDATA["+ jvExchrate +"]]></exch_rate__inv>");
				xmlBuff.append("</Detail2>");	
				xmlBuff.append("</Header0>");
				xmlBuff.append("</group0>");
				xmlBuff.append("</DocumentRoot>");
				xmlString = xmlBuff.toString();
				System.out.println("...............just before savdata()");
				siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

				errString = saveData(siteCode,xmlString,conn);
				
				System.out.println("@@@@@2: retString:"+errString);
				return errString;


			}
			if(errString == null || errString.trim().length() ==0)
			{
				errString = updateCreditNote(commMap, commMap ,xtraParams , post, conn);
			}

		}catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}

	public int daysBetween(Date d1, Date d2){
		return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
	}


	private String gbfRetrieveDrCr(String asFrom, String asTo, int aiCommit ,  String  xtraParams,Connection conn) throws ITMException {

		String errCode = "",keyFld = "" , expHdr = "",expDet = "", winName = "", ledgPostconf= "" , ledgPostConf = "",
				sql = "" , sql1 = "" ,winname ="";
		String currCode[],custCode[],acctCode[],cctrCode[];

		HashMap tranId = new HashMap();
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		HashMap HdrMap = null;
		HashMap DetMap = null;
		ArrayList DetList = new ArrayList();
		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		int cntrHdr = 0,cntr = 0,insertedRow = 0,rows = 0;

		java.util.Date tranDate = null, today;
		try
		{
			sql = "tran_id ,tran_date ,fin_entity ,acct_code , cctr_code ,eff_date , invoice_id , amount , curr_code , exch_rate , remarks , " +
					"site_code,  anal_code ,  drcr_flag  ,  tran_id__rcv,  confirmed,conf_date ,emp_code__aprv, tran_type , tran_ser ,   " +
					"due_date ,cr_term ,amount__bc, item_ser , round_adj , sundry_type , sundry_code ,  " +
					"  acct_code__cf , cctr_code__cf  , diff_amt_exch ,voucher_no , invvouc_flag , parent__tran_id , rev__tran " +
					" from drcr_inv where tran_id = ?";


			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,asFrom);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				HdrMap = new HashMap();
				HdrMap.put("tran_id",rs.getString("tran_id"));
				HdrMap.put("tran_date",rs.getDate("tran_date"));
				HdrMap.put("fin_entity",rs.getString("fin_entity"));
				HdrMap.put("acct_code",rs.getDouble("acct_code"));
				HdrMap.put("cctr_code",rs.getString("cctr_code"));
				HdrMap.put("eff_date",rs.getString("eff_date"));
				HdrMap.put("invoice_id",rs.getString("invoice_id"));
				HdrMap.put("amount",rs.getDouble("amount"));
				HdrMap.put("curr_code",rs.getString("curr_code"));
				HdrMap.put("exch_rate",rs.getDouble("exch_rate"));
				HdrMap.put("remarks",rs.getString("remarks"));
				HdrMap.put("site_code",rs.getString("site_code"));
				HdrMap.put("anal_code",rs.getString("anal_code"));
				HdrMap.put("drcr_flag",rs.getString("drcr_flag"));
				HdrMap.put("tran_id__rcv",rs.getString("tran_id__rcv"));
				HdrMap.put("confirmed",rs.getDouble("confirmed"));
				HdrMap.put("conf_date",rs.getDouble("conf_date"));
				HdrMap.put("emp_code__aprv",rs.getString("emp_code__aprv"));
				HdrMap.put("tran_type",rs.getString("tran_type"));
				HdrMap.put("tran_ser",rs.getString("tran_ser"));

				HdrMap.put("due_date",rs.getDate("due_date"));
				HdrMap.put("cr_term",rs.getString("cr_term"));
				HdrMap.put("amount__bc",rs.getDouble("amount__bc"));
				HdrMap.put("item_ser",rs.getString("item_ser"));
				HdrMap.put("round_adj",rs.getDouble("round_adj"));
				HdrMap.put("sundry_type",rs.getString("sundry_type"));
				HdrMap.put("sundry_code",rs.getString("sundry_code"));
				HdrMap.put("acct_code__cf",rs.getString("acct_code__cf"));
				HdrMap.put("cctr_code__cf",rs.getString("cctr_code__cf"));
				HdrMap.put("diff_amt_exch",rs.getDouble("diff_amt_exch"));

				HdrMap.put("voucher_no",rs.getString("voucher_no"));
				HdrMap.put("invvouc_flag",rs.getString("invvouc_flag"));
				HdrMap.put("parent__tran_id",rs.getDouble("parent__tran_id"));
				HdrMap.put("rev__tran",rs.getDouble("rev__tran"));




				System.out.println(" Header Map..........");
				System.out.println(HdrMap.toString());
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			



			DetMap = new HashMap();
			sql = " tran_id ,line_no ,acct_code,cctr_code ,amount,emp_code  ,anal_code ,exch_rate__inv where tran_id = ? ";              
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,asFrom);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				
				DetMap.put("tran_id", rs.getString("tran_id"));
				DetMap.put("line_no", rs.getString("line_no"));
				DetMap.put("amount", rs.getString("amount"));
				DetMap.put("emp_code", rs.getString("emp_code"));
				DetMap.put("anal_code", rs.getString("anal_code"));
				DetMap.put("acct_code", rs.getDouble("acct_code"));
				DetMap.put("cctr_code", rs.getDouble("cctr_code"));
				DetMap.put("exch_rate__inv", rs.getDouble("exch_rate__inv"));

				DetList.add(DetMap);

				System.out.println(" DetMap  Map..........");
				System.out.println(DetMap.toString());

			}    

			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;
			

			sql = "select tran_id from drcr_inv  where tran_id 	>= ? and tran_id <= ? and 	site_code__from = ? and upper(confirmed) <> 'Y'";
			pstmt = conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				tranId.put("tran_id",rs.getString(1));                                 


				if ("db2".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql1 = "SELECT tran_id FROM drcr_inv  WHERE tran_id = ? for update ";
				}

				else if ( "mssql".equalsIgnoreCase(CommonConstants.DB_NAME ))
				{
					sql1 = "SELECT tran_id FROM drcr_inv (updlock) WHERE tran_id = ? " ;
				}
				else
				{
					sql1 =" SELECT tran_id  FROM drcr_inv WHERE tran_id =  ? for update nowait" ;
				}
				pstmt1 = conn.prepareStatement(sql1);
				pstmt1.setString(1,asFrom);
				rs1 = pstmt1.executeQuery();
				if(rs1.next())
				{
					keyFld = rs1.getString("tran_id") == null ? " ":rs1.getString("tran_id");

				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;


				today 		=  new java.util.Date();
				winname = "W_DRCRINV";

				sql = "select ledg_post_conf from transetup where upper(tran_window) = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,"W_PAY_IBCA");
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					ledgPostConf = rs.getString(1);
				}
				else
				{
					errCode = itmDBAccessEJB.getErrorString("","VTSEQ ","","",conn);
					return errCode;
				}

				if("Y".equalsIgnoreCase(ledgPostConf))
				{
					if(tranDate.compareTo(today) == 0)
					{
						tranDate = today;
					}
					tranDate = today;
					sql = " update drcr_inv set tran_date = ? where tran_id   = ?" ;
					pstmt.setDate(1, new java.sql.Date(tranDate.getDate()));
					pstmt.setString(2,(String)tranId.get("tran_id"));
					pstmt.executeUpdate();		
					
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
				}


			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			errCode = gbfPostDrCr(HdrMap,DetList,aiCommit,xtraParams,conn);
			
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}

		return errCode;
	}



	private String gbfPostDrCr(HashMap HdrMap, ArrayList DetList, int aiCommit ,String xtraParams, Connection conn) throws ITMException {



		String errCode = "",keyFld = "" , expHdr = "",expDet = "", winName = "", ledgPostconf= "" , ledgPostConf,
				sql = "" ,winname ="" ,loginEmpCode = "";
		String currCode[],custCode[],acctCode[],cctrCode[];
		String tranSer = "" ,linkType = "";

		ITMDBAccessEJB itmDBAccessEJB = null;
		itmDBAccessEJB = new ITMDBAccessEJB();

		String tranId = new String();
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		int cntrHdr = 0,cntr = 0,insertedRow = 0,rows = 0, 
				ediOption = 0;

		java.util.Date tranDate, today;
		today =new java.util.Date();

		try
		{
			sql = "select edi_option from transetup where tran_window = 'w_pay_ibca'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				ediOption  = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;


			errCode = gbfPostDrcrInvhdr(HdrMap, xtraParams,conn);
			if(errCode == null || errCode.trim().length() ==0)
			{
				errCode = gbfPostDrcrInvdet(HdrMap,DetList , xtraParams,conn);
				return errCode;
			}


		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errCode ;

	}


	private  String gbfPostDrcrInvhdr(HashMap HdrMap ,String xtraParams,  Connection conn) throws ITMException
	{


		System.out.println("gbfPostRcpdet called..............");
		String errString = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		String acctCode = "";
		String cctrCode = ""; 
		String recoAcctCode = "";
		String recoCctrCode = "";
		String taxAcctCode = "";
		String taxCctrCode = "";
		String acctCode1 = "";
		String cctrCode1 = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String contactCode = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String tranType = "";
		String empCode = "";
		String refNO = "";
		String payMode = "";
		String rcpMode = "";
		String batchNo = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String sql = "";
		String hcurrCode = "";
		String errorType = "";
		String payslip = "";
		String partyDocRef = "";
		String refSer = "";
		String refNo = "";
		String salesPers = "";
		String status = "";
		String lineNoPef = "";
		String tranId = "";
		String tranSer = "";
		int count = 0;
		int lineNo = 0;
		double exchRate = 0.0;
		double hexchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double taxAmount = 0.0;
		double recoAmount = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double advAmt = 0.0;
		double adjAmt = 0.0;
		double advAdj = 0.0;
		double recoverAmt = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		Date billDate = null;
		Date dueDate = null;


		HashMap DetMap = null;
		//HashMap RcpDetMap = null;
		HashMap miscPayMap = null;
		//HashMap EpcAdjMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap detListMap = null;
		HashMap recofiltMap = null;
		HashMap recodataMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		DistCommon distCommon = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();
		try
		{
			finCommon = new  FinCommon();
			distCommon = new DistCommon();
			itmDBAccessEJB = new ITMDBAccessEJB();
			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginCode");

			tranId = (String)HdrMap.get("tranId");
			tranSer = (String)HdrMap.get("tran_ser");

			tranDate = (Date)HdrMap.get("tran_date");
			effDate = (Date)HdrMap.get("eff_date");
			finEntity = (String)HdrMap.get("fin_entity");
			siteCode = (String)HdrMap.get("site_code");
			siteCodeFor = (String)HdrMap.get("site_code__for");
			projectCode = (String)HdrMap.get("proj_code");
			hcurrCode = (String)HdrMap.get("curr_code");
			hexchRate = (Double)HdrMap.get("exch_rate");
			remarks = (String)HdrMap.get("remarks");
			confirm = (String)HdrMap.get("confirm");


			glTraceMap = new HashMap();
			glTraceMap.put("tran_date",new Timestamp(tranDate.getTime()));
			glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
			glTraceMap.put("fin_entity", finEntity);
			glTraceMap.put("site_code", siteCode);
			glTraceMap.put("sundry_type",sundryType);
			glTraceMap.put("sundry_code",sundryCode);
			glTraceMap.put("acct_code", (String)HdrMap.get("acct_code"));

			glTraceMap.put("cctr_code", (String)HdrMap.get("cctr_code")==null?"":(String)HdrMap.get("cctr_code"));
			glTraceMap.put("emp_code", "");
			glTraceMap.put("anal_code", (String)HdrMap.get("anal_code"));
			glTraceMap.put("curr_code", (String)HdrMap.get("curr_code")==null?hcurrCode:(String)HdrMap.get("curr_code"));

			glTraceMap.put("exch_rate", (Double)HdrMap.get("exch_rate__inv"));

			if("D".equals(HdrMap.get("drcr_flag")))
			{

				glTraceMap.put("dr_amt",0.0);
				glTraceMap.put("cr_amt",amount);
			}

			else
			{
				glTraceMap.put("dr_amt", amount);
				glTraceMap.put("cr_amt",0.0);
			}

			glTraceMap.put("ref_type","F");
			glTraceMap.put("ref_ser", tranSer);
			glTraceMap.put("ref_id", tranId);
			glTraceMap.put("remarks",remarks);

			System.out.println("848 glTraceUpdate Called..............");
			errString = finCommon.glTraceUpdate(glTraceMap,conn);
			if(errString != null && errString.trim().length() > 0)
			{
				System.out.println("ERROR IN GLTRACE ...........");

				return errString;
			}

			// Populate sundry balance structure
			sundryBalMap = new HashMap();
			sundryBalMap.put("tran_date",new Timestamp(tranDate.getTime()));
			sundryBalMap.put("eff_date",new Timestamp(effDate.getTime()));
			sundryBalMap.put("fin_entity", finEntity);
			sundryBalMap.put("site_code", siteCode);
			sundryBalMap.put("sundry_type", sundryType);
			sundryBalMap.put("sundry_code", sundryCode);
			sundryBalMap.put("acct_code", (String)HdrMap.get("acct_code"));
			sundryBalMap.put("cctr_code", (String)HdrMap.get("cctr_code")==null?"":(String)HdrMap.get("cctr_code"));
			sundryBalMap.put("curr_code", (String)HdrMap.get("curr_code"));
			sundryBalMap.put("exch_rate", (Double)HdrMap.get("exch_rate"));

			if("D".equals(HdrMap.get("drcr_flag")))
			{
				sundryBalMap.put("dr_amt", amount);
				sundryBalMap.put("cr_amt", 0.0);
			}

			else
			{
				sundryBalMap.put("dr_amt", 0.0);
				sundryBalMap.put("cr_amt", amount);
			}


			sundryBalMap.put("adv_amt", 0.0);

			System.out.println("2366 sundryBaleUpdate Called..............");
			errString = finCommon.gbf_sundrybal_upd(sundryBalMap, conn);
			if(errString != null && errString.trim().length() > 0)
			{
				System.out.println("error is sundryBaleUpdate ..........."+errString);

				return errString;
			}


			///Populate the misc_payables structure				/////
			// insert into misc_payable	
			miscPayMap = new HashMap();
			miscPayMap.put("tran_date",new Timestamp(tranDate.getTime()));
			miscPayMap.put("ref_no",(String)HdrMap.get("ref_no"));
			miscPayMap.put("ref_date", new Timestamp(refDate.getTime()));			
			miscPayMap.put("bill_no", (String)HdrMap.get("bill_no"));
			miscPayMap.put("bill_date", new Timestamp(billDate.getTime()));
			miscPayMap.put("sundry_type",(String)HdrMap.get("sundry_type")==null?"O":(String)HdrMap.get("sundry_type"));
			miscPayMap.put("sundry_code", (String)HdrMap.get("sundry_code")==null?"O":(String)HdrMap.get("sundry_code"));
			miscPayMap.put("acct_code", (String)HdrMap.get("acct_code"));
			miscPayMap.put("cctr_code", (String)HdrMap.get("cctr_code")==null?"":(String)HdrMap.get("cctr_code"));
			miscPayMap.put("curr_code", (Double)HdrMap.get("curr_code"));
			miscPayMap.put("exch_rate", (Double)HdrMap.get("exch_rate__vouch"));


			miscPayMap.put("due_date", new Timestamp(dueDate.getTime()));
			miscPayMap.put("site_code",siteCode);
			miscPayMap.put("fin_entity",finEntity);
			if("C".equals(HdrMap.get("drcr_flag")))
			{
				miscPayMap.put("tot_amt", amount);
			}
			else
			{
				miscPayMap.put("tot_amt", amount);
			}
			sql = "select bank_code   from site where site_code = ?";
			pstmt.execute(sql);
			pstmt.setString(1, siteCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				bankCode = rs.getString(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql = "select pay_mode from sales_pers where sales_pers = ?" ;
			pstmt.execute(sql);
			pstmt.setString(1, salesPers);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				payMode = rs.getString(1)==null?"Q":rs.getString(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			miscPayMap.put("bank_code", bankCode);
			miscPayMap.put("auto_pay", "Y");
			miscPayMap.put("pay_mode", payMode);
			miscPayMap.put("paid", "N");
			miscPayMap.put("adv_amt", 0.0);

			if("Y".equals(confirm))
			{
				sql = "update drcr_inv set confirmed = 'Y', conf_date = ? ,emp_code__aprv = ? where tran_id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
				pstmt.setString(2, loginEmpCode);
				pstmt.setString(3, tranId);
				int updateCoount = pstmt.executeUpdate();
				System.out.println("no of row update = "+updateCoount);
				pstmt.close();
				pstmt = null;
				if(updateCoount > 0)
				{
					errString= itmDBAccessEJB.getErrorString("","VTCICONF3 ","","",conn);
					return errString;
				}
			}


			System.out.println("884 sundryBaleUpdate Called..............");
			errString = finCommon.gbfMiscPayUpd(miscPayMap, conn);
			if(errString != null && errString.trim().length() > 0)
			{
				return errString;
			}


		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}


	private  String gbfPostDrcrInvdet(HashMap MapHrd , ArrayList DetList ,String xtraParams, Connection conn) throws ITMException
	{
		System.out.println("gbfPostDrcrInvdet called........");
		String errString = "";
		String linkType = "";
		String currCode = "";
		String siteCode = "";
		String siteCodeFor = "";
		String finEntity = "";
		HashMap DetMap = null;
		String acctCode = "";
		String cctrCode = "";
		String acctCodePay = "";
		String cctrCodePay = "";
		String acctCodeAr = "";
		String cctrCodeAr = "";
		String tranSer = "";
		String projectCode = "";
		String analCode = "";
		String bankCode = "";
		String remarks = "";
		String sundryType = "";
		String sundryCode = "";
		String sundryTypeFor = "";
		String sundryCodeFor = "";
		String contactCode = "";
		String empCode = "";
		String refNO = "";
		String rcpMode = "";
		String batchNo = "";
		String tranType = "";
		String confirm = "";
		String loginEmpCode = "";
		String winName = "";
		String editOption = "";
		String confirmed = "";
		String sql = "";
		String errorType = "";
		String bdFluctuationCf = "";
		String acctCodeBal = "";
		String cctrCodeBal = "";
		String basecurrCode = "";
		String projCode = "";
		String custCode = "";
		String salesPers = "";
		String refSer = "";
		String refNo = "";
		String acctCodeCf = "";
		String payslip = "";
		String tranId = "";
		boolean isInBaseCurr =false;
		int count = 0;
		int cnt1 = 0 ;
		int cnt = 0;
		double exchRate = 0.0;
		double netAmount = 0.0;
		double amount = 0.0;
		double advAmt = 0.0;
		double netAmt = 0.0;
		double chqAmt = 0.0;
		double debit  = 0.0;
		double credit = 0.0;
		double totAmt = 0.0;
		double ediOption = 0.0;
		double netAmountBc = 0.0;
		Date effDate = null;
		Date tranDate = null;
		Date refDate = null;
		HashMap detListMap = null;
		HashMap glTraceMap = null;
		HashMap sundryBalMap = null;
		HashMap bankTranLogMap = null;
		HashMap receivablesMap = null;
		HashMap epcadjMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		ValidatorEJB validatorEJB = new ValidatorEJB();
		GenericUtility genericUtility = new GenericUtility();
		ITMDBAccessEJB itmDBAccessEJB = null;
		try
		{
			finCommon =new  FinCommon();

			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			
			java.util.Date today=	new java.sql.Date(new java.util.Date().getTime());
			
			itmDBAccessEJB = new ITMDBAccessEJB();

			linkType = (String)MapHrd.get("link_type");
			tranId = (String)MapHrd.get("tran_id");

			tranDate = (Date)MapHrd.get("tran_date");
			refDate = (Date)MapHrd.get("ref_date");
			effDate = (Date)MapHrd.get("eff_date");
			remarks = (String)MapHrd.get("remarks");

			finEntity = (String)MapHrd.get("fin_entity__to");
			siteCode = (String)MapHrd.get("site_code__to");
			tranSer = (String)MapHrd.get("tran_ser");
			bankCode = (String)MapHrd.get("bank_code");

			acctCode = (String)MapHrd.get("acct_code__to");
			cctrCode = (String)MapHrd.get("cctr_code__to");

			currCode = (String)MapHrd.get("curr_code");
			exchRate = (Double)MapHrd.get("exch_rate");

			System.out.println("DetList SIZE "+DetList.size());
			System.out.println("DetList SIZE "+DetList);

			for (int ctr =0; ctr < DetList.size(); ctr++)
			{

				System.out.println("no of times "+ctr);
				DetMap = new HashMap();
				DetMap = (HashMap) DetList.get(ctr);


				sundryCode = (String)DetMap.get("sundry_code");
				sundryType = (String)DetMap.get("sundry_type");

				acctCode = (String)DetMap.get("acct_code");
				cctrCode = (String)DetMap.get("cctr_code");
				empCode = (String)DetMap.get("emp_code");
				analCode = (String)DetMap.get("anal_code");

				exchRate = (Double)DetMap.get("exch_rate__inv");
				analCode = (String)DetMap.get("anal_code");
				analCode = (String)DetMap.get("anal_code");



				System.out.println("DetMap SIZE "+DetMap);

				glTraceMap = new HashMap();
				glTraceMap.put("tran_date", new Timestamp(tranDate.getTime()));
				glTraceMap.put("eff_date",new Timestamp(effDate.getTime()));
				glTraceMap.put("fin_entity", finEntity);
				glTraceMap.put("site_code", siteCode);
				glTraceMap.put("sundry_type", sundryType);
				glTraceMap.put("sundry_code", sundryCode);
				glTraceMap.put("acct_code", acctCode);
				glTraceMap.put("cctr_code", cctrCode);
				glTraceMap.put("emp_code", empCode);
				glTraceMap.put("anal_code", analCode);
				glTraceMap.put("curr_code", currCode);
				glTraceMap.put("exch_rate", exchRate);
				if("D".equals(MapHrd.get("drcr_flag")))
				{
					if((Double)MapHrd.get("amount") > 0 )
					{
						glTraceMap.put("dr_amt",0.0);
						glTraceMap.put("cr_amt",amount);
					}

					else
					{
						glTraceMap.put("dr_amt", 0-amount);
						glTraceMap.put("cr_amt",0.0);
					}



				}
				else
				{
					if((Double)MapHrd.get("amount") > 0 )
					{
						glTraceMap.put("dr_amt", (Double)MapHrd.get("amount"));
						glTraceMap.put("cr_amt", 0.0 );
					}

					else{
						glTraceMap.put("dr_amt", 0.0);
						glTraceMap.put("cr_amt",  0 - (Double)MapHrd.get("amount"));
					}
				}

				glTraceMap.put("ref_type","F");
				glTraceMap.put("ref_ser", tranSer);
				glTraceMap.put("ref_id", tranId);
				glTraceMap.put("remarks", remarks);

				System.out.println("1766 glTraceUpdate Called..............");
				errString = finCommon.glTraceUpdate(glTraceMap,conn); 
				if(errString != null && errString.trim().length() > 0)
				{
					return errString;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			System.out.println(e.getMessage());
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;

	}

}