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

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
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.util.ArrayList;
//import java.util.Date;
import java.sql.Timestamp;
import java.util.HashMap;
import java.text.*;



import javax.ejb.Stateless;
@Stateless
public class PayIbcaConf extends ActionHandlerEJB implements PayIbcaConfLocal, PayIbcaConfRemote 
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		String retString = "";
		boolean isConn= false;
		Connection conn = null;

		try
		{
			retString = confirm( tranID, xtraParams, forcedFlag, conn );

			if ( retString != null && retString.length() > 0 )
			{
				throw new Exception("Exception while calling confirm for tran  Id:["+tranID+"]");
			}
		}
		catch(Exception exception)
		{
			System.out.println("Exception in [InvHoldConfEJB] getCurrdateAppFormat " + exception.getMessage());
		}
		return retString;
	}
	
	public String confirm(String tranId,String xtraParams,String forcedFlag, Connection conn) throws RemoteException,ITMException
	{
		System.out.println("confirm called........");
		String sql = "";
		String confirm = "";
		String siteCode = "";
		String errString = "" ;
		String tranSer = "";
		String loginEmpCode = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		GenericUtility genericUtility = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB validatorEJB = null;
		System.out.println("tran id = "+tranId);
		boolean connStatus=false;
		String chgUser="";
		java.sql.Timestamp tranDate = null, today = null;

		try
		{
			if ( conn == null )
			{
				ConnDriver connDriver = null;
				connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				connDriver = null;
				connStatus = true;
			}
			finCommon = new FinCommon();
			genericUtility = new GenericUtility();
			itmDBAccessEJB = new ITMDBAccessEJB();
			validatorEJB = new ValidatorEJB();
			loginEmpCode =validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			System.out.println("Printing loginEmpCode---1-----"+loginEmpCode+"--");
			
			

			sql = "select confirmed ,site_code__from,chg_user  from pay_ibca where tran_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirm = rs.getString("confirmed") == null ?"N":rs.getString("confirmed");
				siteCode = rs.getString("site_code") == null ?" ":rs.getString("site_code__from");
				chgUser = rs.getString("chg_user") == null ?" ":rs.getString("chg_user");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			if(chgUser==null || chgUser.trim().length()==0)
			{
				chgUser="SYSTEM";
			}
			if("null".equalsIgnoreCase(loginEmpCode) || loginEmpCode==null || loginEmpCode.trim().length()==0)
			{
				sql="select emp_code from users where code=?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1,chgUser);
				
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					loginEmpCode=rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("Printing loginEmpCode---2-----"+loginEmpCode+"--");
				
			}
			if(confirm != null  && confirm.equalsIgnoreCase("N"))
			{
				errString = gbfRetrievePibca(tranId,siteCode,xtraParams,conn);
				System.out.println("err String from gdfRetrieveMiscRcp ="+errString);
				if(errString != null && errString.trim().length() > 0)
				{
					return errString;
				}
				if(errString != null && errString.trim().length() > 0)
				{
					return errString;
				}
				
				if(errString == null || errString.trim().length() == 0)
				{
					if("null".equalsIgnoreCase(loginEmpCode) || loginEmpCode==null || loginEmpCode.trim().length()==0)
					{
						loginEmpCode="E03952";
					}
					today = new java.sql.Timestamp(System.currentTimeMillis()) ;
					System.out.println("loginEmpCode--3-"+loginEmpCode);
					sql = "update pay_ibca set confirmed = 'Y', conf_date = ?,emp_code__aprv = ? where tran_id = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setTimestamp(1, today);
					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);
					}
				}
				else 
				{
					//errString = itmDBAccessEJB.getErrorString("","VTDESNCONF ","","",conn);
					return errString;
				}
			}
			else
			{
				System.out.println("The Selected transaction is already confirmed");
				errString = itmDBAccessEJB.getErrorString("","VTMCONF1","","",conn);
				return errString;
			}
			System.out.println("Error String from confirm method.....[" + errString + "]");
		} 
		catch( Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			
				try
				{
					
					if( conn != null && !conn.isClosed() && connStatus ) 
					{
						if(errString.indexOf("VTCICONF3") > -1)
						{
							conn.commit();
						}
						else
						{
							conn.rollback();
						}
						conn.close();
						conn = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e)
				{
					System.out.println("Exception : "+e);
					e.printStackTrace();
					throw new ITMException(e);
				}
			
		}
		return errString;
	} //end of confirm method

	private String gbfRetrievePibca(String tranId, String site, String  xtraParams,Connection conn) throws ITMException 
	{

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

		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;
		GenericUtility genericUtility = null;
		java.sql.Timestamp tranDate = null, today = null;
		try
		{
		
			genericUtility = GenericUtility.getInstance();
			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,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				HdrMap = new HashMap();
				HdrMap.put("tran_date",rs.getTimestamp("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.getDouble("amount"));
				HdrMap.put("curr_code",rs.getString("curr_code"));
				HdrMap.put("confirmed",rs.getString("confirmed"));
				HdrMap.put("conf_date",rs.getTimestamp("conf_date"));
				HdrMap.put("emp_code__aprv",rs.getString("emp_code__aprv"));
				HdrMap.put("acct_code__ifr",rs.getString("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.getDouble("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,tranId);
			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.getTimestamp("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.getTimestamp("due_date"));
				DetMap.put("tot_amt", rs.getDouble("tot_amt"));
				DetMap.put("discount", rs.getDouble("discount"));
				DetMap.put("tax_amt", rs.getDouble("tax_amt"));
				DetMap.put("auto_pay", rs.getString("auto_pay"));
				DetMap.put("bank_code", rs.getString("bank_code"));
				DetMap.put("ref_type", rs.getString("ref_type"));
				DetMap.put("cr_term", rs.getString("cr_term"));
				DetMap.put("bill_no", rs.getString("bill_no"));
				DetMap.put("bill_date", rs.getTimestamp("bill_date"));
				DetMap.put("sundry_type", rs.getString("sundry_type"));
				DetMap.put("sundry_code", rs.getString("sundry_code"));		
				DetMap.put("pay_mode", rs.getString("pay_mode"));
				DetMap.put("exch_rate", rs.getDouble("exch_rate"));
				DetMap.put("entry_batch_no", rs.getString("entry_batch_no"));
				DetMap.put("purc_order", rs.getString("purc_order"));		
				DetMap.put("supp_bill_amt", rs.getDouble("supp_bill_amt"));
				DetMap.put("adv_amt", rs.getDouble("adv_amt"));
				DetMap.put("tds_amt", rs.getDouble("tds_amt"));


				DetList.add(DetMap);

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

			}    

			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,tranId);
			rs1 = pstmt1.executeQuery();
			if(rs1.next())
			{
				keyFld = rs1.getString("tran_id") == null ? " ":rs1.getString("tran_id");
				tranDate = rs1.getTimestamp("tran_date");
			}
			rs1.close();
			rs1 = null;
			pstmt1.close();
			pstmt1 = null;


			today = new java.sql.Timestamp(System.currentTimeMillis()) ;

			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))
			{
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				tranDate = java.sql.Timestamp.valueOf(sdf.format(today) + " 00:00:00.000");
				sql = " update rcp_ibca set tran_date = ? where tran_id   = ?" ;
				pstmt.setTimestamp(1,tranDate);
				pstmt.setString(2,tranId);
				pstmt.executeUpdate();		

			}
			errCode = gbfPostPibca(HdrMap,DetList,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, 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.sql.Timestamp tranDate, today;
		try
		{
			loginEmpCode = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			today = new java.sql.Timestamp(System.currentTimeMillis()) ;
			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.setTimestamp(2,today);
				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  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;
		Timestamp effDate = null;
		Timestamp tranDate = null;
		Timestamp 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 = (Timestamp)MapHrd.get("tran_date");
				refDate = (Timestamp)MapHrd.get("ref_date");
				effDate = (Timestamp)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", tranDate);
				glTraceMap.put("eff_date",effDate);
				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;
			}
			if(linkType.equalsIgnoreCase("A") )
			{
				//ls_errcode = gbf_post_pibca_hdr_rcp(as_hdrdata)
				errString = gbfPostPibcaHdrRcp(MapHrd ,xtraParams, conn);
			}
			else if(linkType.equalsIgnoreCase("P") )
			{
				errString = gbfCreatePibca(tranId, tranId,xtraParams, conn);
			}
			else if(linkType.equalsIgnoreCase("R") )
			{
				//ls_errcode = gbf_post_pibca_hdr_rcp(as_hdrdata)
				errString = gbfPostPibcaHdrRcp(MapHrd ,xtraParams, conn);
			}
			else if(linkType.equalsIgnoreCase("C") )
			{
				//ls_errcode = gbf_post_pibca_hdr_rcp(as_hdrdata)
				errString = gbfPostPibcaHdrRcp(MapHrd ,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 gbfCreatePibca(String tranIdFr, String tranIdTo,String xtraParams ,Connection conn) throws ITMException
	{
	
		String 	errString = "", keyString = "",  linkType = "", thisWin = "", ibcaConf = "N", siteCodeFrom = "", siteCodeTo = "", finEntFrom = "", finEntTo = "";
		ArrayList<String>  	tranIdList = null;
		int count = 0;
		String 	tranType = "",newTranId = "",chgUser = "",chgTerm = "", sql = "";
		PreparedStatement pstmt = null, pstmtHdr = null, pstmtDet = null;
		ResultSet rs = null, rs1 = null;
		java.sql.Timestamp tranDate = null, today;

		try
		{
			
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			
			 sql = "insert into pay_ibca (tran_id, tran_ser,tran_id__iss,tran_type, tran_date, eff_date, "
				+ " site_code__from, fin_entity__from, site_code__to, fin_entity__to, acct_code__ifr, "
				+ " cctr_code__ifr, acct_code__ito, cctr_code__ito, amount, curr_code, link_type, confirmed, "
				+ " amount__bc, chg_date, chg_user, chg_term, add_date, add_user, add_term, remarks, sundry_type, sundry_code ) "
				+ " values (?, ?,?,?, ?, ?,  ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";
			pstmtHdr = conn.prepareStatement(sql);
			
			 sql = "insert into pay_ibca_det ( 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, ref_ser__org ) "
				+ " values (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, ref_ser__org )";
			pstmtDet = conn.prepareStatement(sql);


			errString = "";
			sql = "select key_string from transetup where tran_window = 'w_pay_ibca'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				keyString  = rs.getString(1);
			}
			else
			{
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				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;
			tranIdList = new ArrayList<String>();
			sql = "select tran_id from pay_ibca where tran_id >= ? and tran_id <= ? and upper(confirmed) <> 'Y'";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranIdFr);
			pstmt.setString(2,tranIdTo);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				tranIdList.add(rs.getString(1));
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			for (int hdrCtr = 0;  hdrCtr < tranIdList.size(); hdrCtr++)
			{
			
				sql = " SELECT tran_id, tran_ser, tran_id__iss, tran_type, tran_date, eff_date, site_code__from, fin_entity__from, "
					+ " site_code__to, fin_entity__to, acct_code__ifr, cctr_code__ifr, acct_code__ito, cctr_code__ito, amount, "
					+ " curr_code, link_type, confirmed, conf_date, emp_code__aprv, amount__bc, exch_rate, remarks, sundry_type, sundry_code "  
					+ " FROM pay_ibca   WHERE  tran_id = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,(String) tranIdList.get(hdrCtr));
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					today = new java.sql.Timestamp(System.currentTimeMillis()) ;
					SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
					tranDate = java.sql.Timestamp.valueOf(sdf.format(today) + " 00:00:00.000");
					
					sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
					
					String xmlValues = "";
					xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues +	"<tran_id/>";
					xmlValues = xmlValues + "<site_code__from>" + rs.getString("site_code__from") + "</site_code__from>";
					xmlValues = xmlValues + "<site_code__to>" + rs.getString("site_code__to") + "</site_code__to>";
					xmlValues = xmlValues + "<tran_date>"+ sdf.format(tranDate) + "</tran_date>";
					xmlValues = xmlValues + "<tran_ser>R</tran_ser>";
					xmlValues = xmlValues + "<link_type>R</link_type>";
					xmlValues = xmlValues + "</Detail1></Root>";
					
					TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
					newTranId = tg.generateTranSeqID("P-IBCA", "tran_id", keyString, conn);
					
					tranType = rs.getString("tran_ser");
					linkType = rs.getString("link_type");
					siteCodeFrom = rs.getString("site_code__from");
					siteCodeTo 	= rs.getString("site_code__to");
					finEntFrom	= rs.getString("fin_entity__from");
					finEntTo = rs.getString("fin_entity__to");
					pstmtHdr.clearParameters();
					pstmtHdr.setString(1,newTranId);
					pstmtHdr.setString(2,"R");
					pstmtHdr.setString(3,(String) tranIdList.get(hdrCtr));
					pstmtHdr.setString(4,rs.getString("tran_type"));
					pstmtHdr.setTimestamp(5,tranDate);
					pstmtHdr.setTimestamp(6,rs.getTimestamp("eff_date"));
					pstmtHdr.setString(7,rs.getString("site_code__from"));
					pstmtHdr.setString(8,rs.getString("fin_entity__from"));
					pstmtHdr.setString(9,rs.getString("site_code__to"));
					pstmtHdr.setString(10,rs.getString("fin_entity__to"));
					pstmtHdr.setString(11,rs.getString("acct_code__ifr"));
					pstmtHdr.setString(12,rs.getString("cctr_code__ifr"));
					pstmtHdr.setString(13,rs.getString("acct_code__ito"));
					pstmtHdr.setString(14,rs.getString("cctr_code__ito"));
					pstmtHdr.setDouble(15,rs.getDouble("amount"));
					pstmtHdr.setString(16,rs.getString("curr_code"));
					pstmtHdr.setString(17,rs.getString("link_type"));
					pstmtHdr.setString(18,rs.getString("N"));
					pstmtHdr.setDouble(19,rs.getDouble("amount__bc"));
					pstmtHdr.setTimestamp(20,today);
					pstmtHdr.setString(21,chgUser);
					pstmtHdr.setString(22,chgTerm);
					pstmtHdr.setTimestamp(23,today);
					pstmtHdr.setString(24,chgUser);
					pstmtHdr.setString(25,chgTerm);
					pstmtHdr.setString(26,rs.getString("remarks"));
					pstmtHdr.setString(27,rs.getString("sundry_type"));
					pstmtHdr.setString(28,rs.getString("sundry_code"));
								
					count = pstmtHdr.executeUpdate();
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				sql = " SELECT 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, ref_ser__org " 
					+ " FROM pay_ibca_det   WHERE  tran_id = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,(String) tranIdList.get(hdrCtr));
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					pstmtDet.clearParameters();
					pstmtDet.setString(1,newTranId);
					pstmtDet.setString(2,rs.getString("ref_ser"));
					pstmtDet.setString(3,rs.getString("ref_no"));
					pstmtDet.setTimestamp(4,rs.getTimestamp("ref_date"));
					pstmtDet.setString(5,rs.getString("curr_code"));
					pstmtDet.setString(6,rs.getString("acct_code"));
					pstmtDet.setString(7,rs.getString("cctr_code"));
					pstmtDet.setTimestamp(8,rs.getTimestamp("due_date"));
					pstmtDet.setDouble(9,rs.getDouble("tot_amt"));
					pstmtDet.setDouble(10,rs.getDouble("discount"));
					pstmtDet.setDouble(11,rs.getDouble("tax_amt"));
					pstmtDet.setString(12,rs.getString("auto_pay"));
					pstmtDet.setString(13,rs.getString("bank_code"));
					pstmtDet.setString(14,rs.getString("ref_type"));
					pstmtDet.setString(15,rs.getString("cr_term"));
					pstmtDet.setString(16,rs.getString("bill_no"));
					pstmtDet.setTimestamp(17,rs.getTimestamp("bill_date"));
					pstmtDet.setString(18,rs.getString("sundry_type"));
					pstmtDet.setString(19,rs.getString("sundry_code"));
					pstmtDet.setString(20,rs.getString("pay_mode"));
					pstmtDet.setDouble(21,rs.getDouble("exch_rate"));
					pstmtDet.setString(22,rs.getString("entry_batch_no"));
					pstmtDet.setString(23,rs.getString("purc_order"));
					pstmtDet.setDouble(24,rs.getDouble("supp_bill_amt"));
					pstmtDet.setDouble(25,rs.getDouble("adv_amt"));
					pstmtDet.setDouble(26,rs.getDouble("tds_amt"));
					pstmtDet.setString(27,rs.getString("ref_ser__org"));
					pstmtDet.addBatch();
					pstmtDet.clearParameters();

				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				pstmtDet.executeBatch();
				
				sql = " select 	case when auto_confirm is null then 'N' else auto_confirm end "
					+ " from IBCA_PAY_CTRL "
					+ " where  site_code__from   = ? "
					+ " and    site_code__to     = ? "
					+ " and    fin_entity__from  = ? "
					+ "	and    fin_entity__to    = ? "
					+ " and    link_type         = 'P' " ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCodeFrom);
				pstmt.setString(2,siteCodeTo);
				pstmt.setString(3,finEntFrom);
				pstmt.setString(4,finEntTo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					ibcaConf = rs.getString(1);
				}
				else
				{
					ibcaConf = "N";
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if ("Y".equals(ibcaConf))
				{
					errString = confirm(newTranId,xtraParams,"N",  conn);
					if(errString.indexOf("VTCICONF3") > -1)
					{
						errString = "";
					}
				}
			}
			pstmtDet.close();
			pstmtDet = null;
			pstmtHdr.close();
			pstmtHdr = null;
			
		}
		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;
		java.sql.Timestamp effDate = null;
		java.sql.Timestamp tranDate = null;
		java.sql.Timestamp refDate = null;
		java.sql.Timestamp 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.sql.Timestamp 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 = (Timestamp)MapHrd.get("tran_date");
			effDate = (Timestamp)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);

				glTraceMap = new HashMap();
				glTraceMap.put("tran_date",tranDate);
				glTraceMap.put("eff_date",effDate);
				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",tranDate);
				sundryBalMap.put("eff_date",effDate);
				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();
				if(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;
			}



			// 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.getTimestamp(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.setTimestamp(1,tranDate);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							code = rs.getString(1);
							frDate = rs.getTimestamp(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,(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.setTimestamp(1,frDate);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								code =rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}



						sql ="update loans set start_reco where loan_no = ?";
						pstmt.setTimestamp(1,frDate);
						pstmt.setString(2,refNo);
						pstmt.executeUpdate();
						pstmt.close();
						pstmt = null;

						sql =" update loans set date__interest = ?, start_dedn = 'Y'" +
								"where loan_no = ? ";
						pstmt.setTimestamp(1,tranDate);
						pstmt.setString(2,refNo);
						pstmt.executeUpdate();
						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 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;
		Timestamp effDate = null;
		Timestamp tranDate = null;
		Timestamp 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 = (Timestamp)MapHrd.get("tran_date");
				refDate = (Timestamp)MapHrd.get("ref_date");
				effDate = (Timestamp)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",tranDate);
				glTraceMap.put("eff_date",effDate);
				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 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;
		Timestamp effDate = null;
		Timestamp tranDate = null;
		Timestamp refDate = null;
		Timestamp billDate = null;
		Timestamp 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 = (Timestamp)HdrMap.get("tran_date");
			effDate = (Timestamp)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 = (Timestamp)HdrMap.get("ref_date");
				billDate = (Timestamp)HdrMap.get("bill_date");
				dueDate = (Timestamp)HdrMap.get("due_date");


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




				glTraceMap = new HashMap();
				glTraceMap.put("tran_date",tranDate);
				glTraceMap.put("eff_date",effDate);
				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",tranDate);
				sundryBalMap.put("eff_date",effDate);
				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",tranDate);
				miscPayMap.put("ref_no",(String)DetMap.get("ref_no"));
				miscPayMap.put("ref_date", refDate);			
				miscPayMap.put("bill_no", (String)DetMap.get("bill_no"));
				miscPayMap.put("bill_date", billDate);
				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", dueDate);
				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;

	}

	
	public double getReqDecimal(double actVal, int prec)
	{
		String fmtStr = "############0";
		String strValue = null;
		double retVal = 0;
		if (prec > 0)
		{
			fmtStr = fmtStr + "." + "000000000".substring(0, prec);
		}
		DecimalFormat decFormat = new DecimalFormat(fmtStr);
		retVal = Double.parseDouble(decFormat.format(actVal));
		if (Math.abs(retVal) == 0)
		{
			retVal = 0;
		}
		return retVal;
	}


}
