package ibase.webitm.ejb.fin;
import java.lang.String;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import ibase.utility.CommonConstants;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.text.*;
import java.io.*;
import org.w3c.dom.*; 
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import java.util.*;
import javax.naming.InitialContext;
//import ibase.webitm.ejb.MasterStateful;// comented for ejb3
//import ibase.webitm.ejb.MasterStatefulHome;// commented for ejb3
import ibase.webitm.ejb.MasterStatefulLocal;//added for ejb3
import ibase.webitm.ejb.MasterStatefulEJB;//addes for ejb3
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import java.io.File;
import ibase.system.config.ConnDriver;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class AutoPmtGenPrc extends ProcessEJB implements AutoPmtGenPrcLocal,AutoPmtGenPrcRemote //SessionBean
{
	File filePtr ;
	File logDir ;
	String logDirName = "";			
	static String logOnOffFlag = "";//For On-Off Log file.
	ValidatorEJB validatorEJB = new ValidatorEJB();// Added by Jaimin 16/08/2007
	String err = "";
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();		
//	Connection conn = null;
	ResultSet rs1 = null;
	PreparedStatement pstmt1 = null;
	ResultSet rs2 = null;
	PreparedStatement pstmt2 = null;
	String Sql1="";
	java.sql.Timestamp dateTo = null;
	java.sql.Timestamp dateFr = null;	
	
	/*static void writeLog(File f,String Msg,boolean flag)
	{
		try
		{  
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);				
			if(logOnOffFlag.trim().equals("Y"))
			{
				pw.println( Msg);		
			}
			pw.close();
		}
		catch(Exception exWm){exWm.printStackTrace();}		
	}
	static void writeLog(File f,Exception Msg,boolean flag)
	{
		try{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);				
			pw.println(" "+Msg);		
			pw.close();		
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}*/
	
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		if(CommonConstants.J2EE_VERSION.equals("1"))
		{
			logDirName =  CommonConstants.JBOSSHOME  + File.separator + "log" ;
		}
		else if(CommonConstants.J2EE_VERSION.equals("2"))
		{
			logDirName =  CommonConstants.JBOSSHOME   + File.separator + "server"+ File.separator +"default"+ File.separator +"log" ;
		}
		logDir = new File(logDirName);
		filePtr = new File(logDirName+ File.separator + "AutoPmtGenSave.log");

		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;	
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
			//System.out.println("rtrStr================"+rtrStr);
		}
		catch (Exception e)
		{			
			//writeLog(filePtr,"Exception -->"+e,true);
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		StringBuffer retTabSepStrBuff = new StringBuffer();
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		String fromDate = null;
		String toDate = null;		
		String vouchNoFrom = null;
		String vouchNoTo = null;
		String siteCode = null;
		String bankCode = null;
		String sundryType = null;
		String sundryCode = null;
		String payMode = null;
		String entryBatchNo = null;
		String chqSplit = null;
		String bankAdd = null;
		String dueDate="";
		String errCode = "";
		String resultString = "";
		String getSql= null ;
		String currCode = "";
		String sql= null ;
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		//Statement st = null; // Remarked - Rej - Asnot used - 29/12/2007

		//Added by Raj (FI78DIS032)- 29/12/2007
		double unapprovedPayAmt = 0d , payAmt = 0d , netPayable = 0d;
		String tranSer = "";
		String refNo = "";
		String tempSql = "";
		Statement stmtTemp = null; 
		ResultSet rsTemp = null;
		// End addition  - Raj - (FI78DIS032)- 29/12/2007
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			stmtTemp = conn.createStatement(); // Added - by Raj  - (FI78DIS032)- 29/12/2007
			DatabaseMetaData dbmd = conn.getMetaData();
			//For logonoff
			getSql = "select var_value from finparm where prd_code='999999' and var_name='AUTOPAYGEN_LOG_FLAG'";
			pstmt = conn.prepareStatement(getSql); 
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				logOnOffFlag = rs.getString(1);
				System.out.println("------------------in rs--------");
			}		
			System.out.println("----------------logOnOff:"+logOnOffFlag);
			rs.close();
			//pstmt.close();
			//
			//writeLog(filePtr,"In log File",true);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			fromDate = genericUtility.getColumnValue("date__fr",headerDom);
			////writeLog(filePtr,"fromDate-->"+fromDate,true);
			currCode= genericUtility.getColumnValue("curr_code",headerDom);
			////writeLog(filePtr,"currCode-->"+currCode,true);
			toDate = genericUtility.getColumnValue("date__to",headerDom);
			//writeLog(filePtr,"toDate-->"+toDate,true);
			siteCode = genericUtility.getColumnValue("site_code__fr",headerDom);
			//writeLog(filePtr,"siteCode-->"+siteCode,true);
			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
			  siteCode = "";					
			} 
			vouchNoFrom = genericUtility.getColumnValue("vouch_no__fr",headerDom);
			//writeLog(filePtr,"vouchNoFrom-->"+vouchNoFrom,true);
			if ( vouchNoFrom == null || vouchNoFrom.trim().length() == 0 )
			{
				 vouchNoFrom = "0";					
			} 
			vouchNoTo = genericUtility.getColumnValue("vouch_no__to",headerDom);
			//writeLog(filePtr,"vouchNoTo -->"+vouchNoTo ,true);
			if(vouchNoTo == null || vouchNoTo.trim().length() == 0)
			{
				vouchNoTo = "z";				
			}
			sundryType = genericUtility.getColumnValue("sundry_type",headerDom);
			//writeLog(filePtr,"sundryType -->"+sundryType ,true);
			if ( sundryType == null  )
			{
				sundryType = "%";
			}
			else
			{
				sundryType =sundryType.trim()+"%";				
			}		
			sundryCode = genericUtility.getColumnValue("sundry_code",headerDom);
			//writeLog(filePtr,"sundryCode -->"+sundryCode ,true);
			if ( sundryCode == null)
			{
				sundryCode = "%";
			}
			else
			{
				sundryCode = sundryCode.trim()+"%";
			}
			payMode = genericUtility.getColumnValue("pay_mode",headerDom);
			//writeLog(filePtr,"payMode -->"+payMode ,true);
			if ( payMode == null || payMode.trim().length() == 0 )
			{
				payMode = "%";
			}
			entryBatchNo = genericUtility.getColumnValue("entry_batch_no",headerDom);
			//writeLog(filePtr,"entryBatchNo -->"+entryBatchNo ,true);
			if(entryBatchNo == null)
			{
				entryBatchNo = "%";
			}
			else
			{
				entryBatchNo = entryBatchNo.trim()+"%";
			}			
			fromDate=genericUtility.getValidDateString(fromDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
			//writeLog(filePtr,"fromDate -->"+fromDate ,true);
			toDate=genericUtility.getValidDateString(toDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
			//writeLog(filePtr,"toDate -->"+toDate ,true);
			dateFr = java.sql.Timestamp.valueOf(fromDate + " 00:00:00 "); 
			//writeLog(filePtr,"dateFr -->"+dateFr ,true);
			dateTo = java.sql.Timestamp.valueOf(toDate + " 00:00:00 ");			
			//writeLog(filePtr,"dateTo -->"+dateTo ,true);
			getSql= "SELECT misc_payables.ref_no,"   
				+"misc_payables.tran_date,"   
				+"misc_payables.ref_date,"   
				+"misc_payables.bill_no,"   
				+"misc_payables.bill_date,"   
				+"misc_payables.curr_code,"   
				+"misc_payables.exch_rate,"   
				+"misc_payables.sundry_code,"   
				+"misc_payables.acct_code,"   
				+"misc_payables.cctr_code,"   
				+"misc_payables.due_date,"   
				+"misc_payables.site_code,"   
				+"misc_payables.fin_entity,"   
				+"misc_payables.tot_amt,"   
				+"misc_payables.sundry_type,"   
				+"misc_payables.bank_code,"   
				+"misc_payables.pay_mode,"   
				+"misc_payables.adv_amt,"   
				+"misc_payables.tran_id,"   
				+"misc_payables.tran_ser,"   
				+"misc_payables.adj_amt,"   
				+"misc_payables.hold_amt,"   
				+"fn_confirmed_by(misc_payables.tran_ser, misc_payables.ref_no) as username,"   
				+"misc_payables.tot_amt - (case when misc_payables.adj_amt is null then 0 else misc_payables.adj_amt end) - (case when misc_payables.hold_amt is null then 0 else misc_payables.hold_amt end) as pay_amt,"   
				+"fn_sundry_name(misc_payables.sundry_type,misc_payables.sundry_code,'') as sundry_name,"   
				+" misc_payables.tot_amt - (case when misc_payables.adj_amt is null then 0 else misc_payables.adj_amt end) - (case when misc_payables.hold_amt is null then 0 else misc_payables.hold_amt end) as net_payable "
				+"FROM misc_payables " 
				+"WHERE ( misc_payables.site_code = '"+siteCode+"' ) AND "  
				+"( misc_payables.sundry_type like '"+sundryType+"' ) AND "  
				+"( misc_payables.sundry_code like '"+sundryCode+"' ) AND "  
				+"( misc_payables.due_date >= ? ) AND "  
				+"( misc_payables.due_date <= ? ) AND "  
				+"( misc_payables.ref_no >= '" + vouchNoFrom + "' ) AND "  
				+"( misc_payables.ref_no <= '" + vouchNoTo + "' ) AND "  
				+"( misc_payables.auto_pay = 'Y' ) AND "  
				+"(misc_payables.tot_amt - misc_payables.adj_amt <>  0 ) AND "  
				+"(misc_payables.hold_amt is null or misc_payables.tot_amt - misc_payables.adj_amt - misc_payables.hold_amt <>  0 ) AND "  
				+"misc_payables.pay_mode like '" + payMode + "' AND "  
				+"case when misc_payables.entry_batch_no is null then ' ' else"    
				+" misc_payables.entry_batch_no end like '"+entryBatchNo+"' AND "
				+" curr_code ='"+ currCode + "'"
				+" ORDER BY misc_payables.sundry_type ASC,"   
				+"misc_payables.sundry_code ASC,"   
				+"misc_payables.ref_no ASC";   
			    System.out.println("SQL==>"+getSql);
				//writeLog(filePtr,"getSql -->"+getSql,true);
				pstmt = conn.prepareStatement(getSql);   
				pstmt.setTimestamp(1,dateFr);
				pstmt.setTimestamp(2,dateTo);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					//Added below by Raj (FI78DIS032)- 29/12/2007
					tranSer = rs.getString("tran_ser");
					refNo = rs.getString("ref_no");
					payAmt = rs.getDouble("pay_amt");
					netPayable = rs.getDouble("net_payable");
					dueDate = rs.getString("due_date");
					
					/*tempSql= "SELECT sum(case when auto_pay_det.pay_amt is null then 0 else auto_pay_det.pay_amt end) as pay_amt "
						+"FROM auto_pay_hdr, auto_pay_det " 
						+"WHERE ( auto_pay_det.tran_ser = '" + tranSer + "') AND "  
						+"( auto_pay_det.ref_no = '" + refNo + "' ) AND " 
						+"( auto_pay_hdr.tran_id = auto_pay_det.tran_id ) AND "  
						+"case when auto_pay_det.tran_id__pay is null then ' ' else "    
						+" auto_pay_det.tran_id__pay end = ' ' ";
					System.out.println("SQL==>"+tempSql);
					rsTemp = stmtTemp.executeQuery(tempSql);
					if (rsTemp.next()) 
					{
						unapprovedPayAmt = rsTemp.getDouble("pay_amt");
					}
					else
					{
						unapprovedPayAmt = 0d;
					}
					rsTemp.close();

					if (netPayable < 0 && netPayable > unapprovedPayAmt)
					{
						unapprovedPayAmt = netPayable;
					}
					else
					{
						if (netPayable > 0 && unapprovedPayAmt > netPayable)
						{
							unapprovedPayAmt = netPayable;
						}
						//payAmt = netPayable - unapprovedPayAmt;
					}*/

					
					payAmt = netPayable;

					//Add ended by Raj (FI78DIS032)- 29/12/2007
					
					//Refno					  
					retTabSepStrBuff.append((rs.getString(1)==null)?" " :rs.getString(1)).append("\t");					
					//tran_date
					retTabSepStrBuff.append(rs.getTimestamp(2)).append("\t");
					dateTo = rs.getTimestamp(2);
	     			 //ref_date
					retTabSepStrBuff.append(rs.getTimestamp(3)).append("\t");
					dateFr = rs.getTimestamp(3);
					//bill_no
					retTabSepStrBuff.append((rs.getString(4)==null)?" " :rs.getString(4)).append("\t");
					//bill_date
					if(rs.getTimestamp(5)==null)
						retTabSepStrBuff.append("").append("\t");
					else
						retTabSepStrBuff.append(rs.getTimestamp(5)).append("\t");
					//fromDate = rs.getTimestamp(5);
					//curr_code
					retTabSepStrBuff.append((rs.getString(6)==null)?" " :rs.getString(6)).append("\t");
					//exch_rate
					retTabSepStrBuff.append(rs.getDouble(7)).append("\t");
					//sundry_code
					retTabSepStrBuff.append((rs.getString(8)==null)?" " :rs.getString(8)).append("\t");
					//acct_code
					retTabSepStrBuff.append((rs.getString(9)==null)?" " :rs.getString(9)).append("\t");
					//cctr_code
					retTabSepStrBuff.append((rs.getString(10)==null)?" " :rs.getString(10)).append("\t");
					//due_date
					retTabSepStrBuff.append(rs.getTimestamp(11)).append("\t"); 
					//toDate = rs.getTimestamp(11);
					//site_code
					retTabSepStrBuff.append((rs.getString(12)==null)?" " :rs.getString(12)).append("\t");
					//fin_entity
					retTabSepStrBuff.append((rs.getString(13)==null)?" " :rs.getString(12)).append("\t");
					//tot_amt
					retTabSepStrBuff.append(rs.getDouble(14)).append("\t");
					//sundry_type
					retTabSepStrBuff.append((rs.getString(15)==null)?" " :rs.getString(15)).append("\t");
					//bank_code
					retTabSepStrBuff.append((rs.getString(16)==null)?" " :rs.getString(16)).append("\t");
					//pay_mode
					retTabSepStrBuff.append((rs.getString(17)==null)?" " :rs.getString(17)).append("\t");
					//adv_amt
					retTabSepStrBuff.append(rs.getDouble(18)).append("\t");
					//tran_id
					retTabSepStrBuff.append((rs.getString(19)==null)?" " :rs.getString(19)).append("\t");
					//tran_ser
					retTabSepStrBuff.append((rs.getString(20)==null)?" " :rs.getString(20)).append("\t");
					//adj_amt
					retTabSepStrBuff.append(rs.getDouble(21)).append("\t");
					//hold_amt
					retTabSepStrBuff.append(rs.getDouble(22)).append("\t");
					//username
					retTabSepStrBuff.append(rs.getString(23)).append("\t");
					//pay_amt
					//retTabSepStrBuff.append(rs.getDouble(24)).append("\t");//Remarked by Raj (FI78DIS032)- 29/12/2007
					retTabSepStrBuff.append(payAmt).append("\t");//Added by Raj (FI78DIS032)- 29/12/2007
					//sundry_name
					retTabSepStrBuff.append((rs.getString(25)==null)?" " :rs.getString(25)).append("\t");
					//net_payable					
					retTabSepStrBuff.append(rs.getDouble(26)).append("\t");
					//unapproved_amt					
					retTabSepStrBuff.append(unapprovedPayAmt).append("\r\n");//Added by Raj (FI78DIS032)- 29/12/2007
					//retTabSepStrBuff.append(rs.getDouble(26)).append("\n");
					////writeLog(filePtr,"Data Feched -->"+retTabSepStrBuff ,true);
					////writeLog(filePtr,"----------------------------------------------------------------" ,true);
				}
				rs.close();
				pstmt.close();	
				resultString = retTabSepStrBuff.toString();
			}	
			catch(Exception e)
			{
				//writeLog(filePtr,"Exception in getData-->"+e,true);
				 throw new ITMException(e);				
			}
			finally
			{
				try
				{
					conn.close();
					conn = null;
				}
				catch (Exception e)
				{
					//writeLog(filePtr,"In Fianally... Exception in getData-->"+e,true);
					System.out.println(e.getMessage());					
				}
			}
		return resultString;	
	} 

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		
		Document detailDom = null;
		Document headerDom = null;
		String retStr = "";
		
		try
		{	
			//writeLog(filePtr,"xmlString-->"+xmlString,true);
			//writeLog(filePtr,"xmlString2-->"+xmlString2,true);
			//writeLog(filePtr,"windowName-->"+windowName,true);			

			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
				//writeLog(filePtr,"headerDom-->"+headerDom,true);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
				//writeLog(filePtr,"detailDom-->"+detailDom,true);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :AutoPrmGen :process:" + e.getMessage() + ":");
			e.printStackTrace();
			//writeLog(filePtr,"Exception in process-->"+e.getMessage(),true);
			retStr = e.getMessage();
		}
		//writeLog(filePtr,"Return from process-->"+retStr,true);
		return retStr;
	}
	// END OF PROCESS ONE

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		//writeLog(filePtr,"In process.............",true);
		//writeLog(filePtr,"headerDom-->"+headerDom,true);
		//writeLog(filePtr,"detailDom-->"+detailDom,true);
		//writeLog(filePtr,"windowName-->"+windowName,true);
		//writeLog(filePtr,"xtraParams-->"+xtraParams,true);
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String refNo = "";
	//	String miscPayablesTranDate = "";
		String chgDate = "";
		String sDate= "";
		String refDate = "";
	//	String fromDate = "";
		String billNo = "";
		String billDate = "";
		String currCode = "";
		String dueDate = "";
		String exchRate = "";
		String sundryCode = "";
		String acctCode = "";
		String cctrCode = "";
		String siteCode = "";
		String finEntity = "";
		String totAmt = "";
		String sundryType = "";
		String bankCode = "";
		String bankCodeAdd = "";
		String payMode = "";
		String drawnAt="";
		String advAmt = "";
		String tranId = "";
		String tranSer = "";
		String adjAmt = "";
		String holdAmt = "";
		String userName = "";
		String payAmt = "";
		String sundryName = "";
		String netPayable = "";
		String childNodeName = "";
		String errCode = "";
		String errFrSret ="";
		String tranType = "";
		String chgTerm = "";
		String chgUser = "";
		String xmlOutString = "";
		String payDate = "";
		String wfStatus="";
		String stanCode="";
		String tranDate="";
		double diffAmt=0;
		String retString = "";
		String lastChq = ""; //Added by Jaimin 06/08/2007
		String uptoChq = "";//Added by Jaimin 06/08/2007
		String errString = "";
		StringBuffer retBuf;
		String tranDt="";
		//StringBuffer refNoBuff = null, tranSerBuff = null, payAmtBuff = null, netPayableBuff = null;//Added by jaimin 17/08/02007
		StringBuffer errStringBuff = null;//Added by jaimin 17/08/02007
		boolean validEntry = true;
		StringBuffer xmlString = null;
		int curDate = 0;
		int	curMonth = 0;
		int	curYear = 0;
		int lineNo = 0;
		//Added by Jaimin 25/07/2007
		Connection connectionObject = null;
		Statement statement = null;
		ResultSet resultSet = null;	
		String sql = "";
		String siteDescr = "",finentDescr = "",bankName = "",chgFrm="",chgTo="";
		//End Jaimin 25/07/2007
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null; 	
		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;	
		String acctCodeBal="",cctrCodeBal="",acctCodeBc="",cctrCodeBc="",acctCodeCf="",acctCodeCfAp="",cctrCodeCf="",cctrCodeCfAp="";
		String currCodeBc="",porder="",sfld1="",acctCodeDisc="",cctrCodeDisc="",startFrom="";
		double excRateBc=0,discount=0,mexrate=0,disAmt=0,payAmt1=0;
		 Date effDate=null,billDt=null,ldStartDate=null,reDate1=null;
		Date ldStartDate1=null,payDate1=null,mPayDate=null;
		String transactionDate="";//added by priyanka
		
		 long datediff=0;
		FinCommon fin=new FinCommon();
		DistCommon dist=new DistCommon();
		try
		{			
			retBuf = new StringBuffer();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			System.out.println("AutoPmtGenPrcEJB ejbCreate called.........");
			
			 Date currentDate = new Date(); 
			 SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());  
			 

			//writeLog(filePtr,"AutoPmtGenPrcEJB ejbCreate called.........",true);
			//For logonoff
			sql = "select var_value from finparm where prd_code='999999' and var_name='AUTOPAYGEN_LOG_FLAG'";
			//writeLog(filePtr,"sql-->"+sql,true);
			pstmt = conn.prepareStatement(sql); 
			resultSet = pstmt.executeQuery();
			if (resultSet.next())
			{
				logOnOffFlag = resultSet.getString(1);					
			}		
			//writeLog(filePtr,"logOnOffFlag-->"+logOnOffFlag,true);
			System.out.println("----------------logOnOff:"+logOnOffFlag);
			resultSet.close();
			//pstmt.close();
			//
			siteCode = genericUtility.getColumnValue("site_code__fr",headerDom);
			//writeLog(filePtr,"siteCode-->"+siteCode,true);
			bankCode = genericUtility.getColumnValue("bank_code",headerDom);
			//writeLog(filePtr,"bankCode-->"+bankCode,true);
			bankCodeAdd = genericUtility.getColumnValue("bank_code__add",headerDom);
			//writeLog(filePtr,"bankCodeAdd-->"+bankCodeAdd,true);
			tranType = genericUtility.getColumnValue("tran_type",headerDom);
			//writeLog(filePtr,"tranType-->"+tranType,true);
			payDate = genericUtility.getColumnValue("date__pay",headerDom);
			//writeLog(filePtr,"payDate-->"+payDate,true);
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");  
			//writeLog(filePtr,"chgUser-->"+chgUser,true);
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			//writeLog(filePtr,"chgTerm-->"+chgTerm,true);
			Calendar calCurr = Calendar.getInstance();
			curDate = calCurr.get(calCurr.DATE);
			//writeLog(filePtr,"curDate-->"+curDate,true);
			curMonth = calCurr.get(calCurr.MONTH);
			//writeLog(filePtr,"curMonth-->"+curMonth,true);
			curYear = calCurr.get(calCurr.YEAR);
			//writeLog(filePtr,"curYear-->"+curYear,true);
			chgDate = new Integer(curYear).toString()+ "-"+new Integer(curMonth).toString()+"-"+new Integer(curDate).toString();
			//writeLog(filePtr,"chgDate-->"+chgDate,true);
			exchRate = genericUtility.getColumnValue("exch_rate",headerDom);
			//writeLog(filePtr,"currExchangeRate-->"+exchRate,true);
			currCode = genericUtility.getColumnValue("curr_code",headerDom);
			//writeLog(filePtr,"currCode-->"+currCode,true);
			lastChq = genericUtility.getColumnValue("ref_no",headerDom);
			//writeLog(filePtr,"lastChq-->"+lastChq,true);
			uptoChq = genericUtility.getColumnValue("ref_no__upto",headerDom);
			
			System.out.println("chgDate========"+chgDate);
			
			payMode = genericUtility.getColumnValue("pay_mode",headerDom);
			System.out.println("Getting pay Mode================"+payMode);
			
			sundryCode = genericUtility.getColumnValue("sundry_code",headerDom);
			System.out.println("Getting sundry_code================"+sundryCode);
			
			sundryType = genericUtility.getColumnValue("sundry_type",headerDom);
			System.out.println("Getting sundryType================"+sundryType);
			
			refNo = genericUtility.getColumnValue("ref_no",headerDom);
			System.out.println("Getting ref_no================"+refNo);
			
			dueDate = genericUtility.getColumnValue("due_date",headerDom);
			System.out.println("Getting dueDate=============="+dueDate);
			
			wfStatus = genericUtility.getColumnValue("wf_status",headerDom);
			System.out.println("Getting wfStatus=============="+wfStatus);
			
/*			acctCode = genericUtility.getColumnValue("acct_code",headerDom);
			System.out.println("Getting acct_code__bal================"+acctCode);*/
			//writeLog(filePtr,"uptoChq-->"+uptoChq,true);
			//chgDate = java.sql.Timestamp.valueOf(sDate + " 00:00:00");
			//Added by Jaimin 25/07/2007
			if (siteCode != null)
			{
				sql = "SELECT FIN_ENTITY,DESCR FROM SITE WHERE SITE_CODE ='"+siteCode+"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					finEntity = rs.getString(1);
					siteDescr = rs.getString(2);
				}
				//writeLog(filePtr,"finEntity-->"+finEntity,true);
				//writeLog(filePtr,"siteDescr-->"+siteDescr,true);
			}
			rs.close();
			pstmt.close();
			pstmt = null;
			if ( finEntity != null )
			{
				sql = "SELECT DESCR FROM FINENT WHERE FIN_ENTITY ='"+finEntity+"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					finentDescr = rs.getString(1);					
				}		
				//writeLog(filePtr,"finentDescr-->"+finentDescr,true);
			}
			rs.close();
			pstmt.close();
			pstmt = null;
			if ( bankCode != null )
			{
				sql = "SELECT BANK_NAME,chq1,chq3 FROM BANK WHERE BANK_CODE ='" + bankCode +"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					bankName= checkNull(rs.getString(1));		
					//chgFrm= checkNull(rs.getString(2));		
					//chgTo= checkNull(rs.getString(3));		
					
				}	
				//writeLog(filePtr,"bankName-->"+bankName,true);
			}
			rs.close();	
			pstmt.close();
			pstmt = null;
			
			System.out.println("Bank Code====="+bankCode);
			
			sql="select acct_code__bal, cctr_code__bal, acct_code__bc, cctr_code__bc," +
					" acct_code__cf, acct_code__cf_ap, cctr_code__cf, cctr_code__cf_ap " +
					"from bank where bank_code = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,bankCode);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				acctCodeBal=checkNull(rs.getString("acct_code__bal"));
				cctrCodeBal=checkNull(rs.getString("cctr_code__bal"));
				acctCodeBc=checkNull(rs.getString("acct_code__bc"));
				cctrCodeBc=checkNull(rs.getString("cctr_code__bc"));
				acctCodeCf=checkNull(rs.getString("acct_code__cf"));
				acctCodeCfAp=checkNull(rs.getString("acct_code__cf_ap"));
			     cctrCodeCf=checkNull(rs.getString("cctr_code__cf"));
				cctrCodeCfAp=checkNull(rs.getString("acct_code__cf_ap"));
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			
			System.out.println("Site Code>>>>>>>>>>"+siteCode);
			
			sql="select curr_code  from site, finent " +
					"where site.fin_entity = finent.fin_entity and site_code =?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,siteCode);
			rs = pstmt.executeQuery();			
			if(rs.next())
			{
				currCodeBc=checkNull(rs.getString("curr_code"));
			
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("currCodeBc=========="+currCodeBc);
			
           sql="select std_exrt  from currency where curr_code =? ";
           pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,currCodeBc);
			rs = pstmt.executeQuery();			
			if(rs.next())
			{
				excRateBc=rs.getDouble("std_exrt");
			
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("excRateBc=========="+excRateBc);

			
			mexrate=fin.getDailyExchRateSellBuy(currCode, "", siteCode, payDate, "B", conn);//through itemchange
			System.out.println("ExcRate from getDailyExchRateSellBuy========="+mexrate);
		
		
			//End by Jaimin 25/07/2007
		
			xmlString = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			xmlString.append("<DocumentRoot><description>Datawindow Root</description><group0><description>Group0 escription</description>");
			xmlString.append("<Header0>");
			xmlString.append("<description>Header0 members</description>");
			xmlString.append("<objName><![CDATA[").append("misc_pay").append("]]></objName>");//"auto_pay" Added by Jaimin 25/07/2007
			xmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			xmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlString.append("<Detail1 dbID='' domID=\"1\" objName=\"misc_pay\" objContext=\"1\">");//"auto_pay" Added by Jaimin 25/07/2007
			xmlString.append("<attribute pkNames=\"tran_id:\" status=\"N\" updateFlag=\"A\" selected=\"N\" />");
			xmlString.append("<tran_id><![CDATA[]]></tran_id>");			
			xmlString.append("<tran_date><![CDATA[" + payDate + "]]></tran_date>");			
			xmlString.append("<tran_type><![CDATA[" + tranType + "]]></tran_type>");
			xmlString.append("<sundry_type><![CDATA[" + sundryType + "]]></sundry_type>");
			xmlString.append("<sundry_code><![CDATA[" + sundryCode + "]]></sundry_code>");
			xmlString.append("<pay_mode><![CDATA[" + payMode + "]]></pay_mode>");
			xmlString.append("<bank_code><![CDATA[" + bankCode + "]]></bank_code>");
			xmlString.append("<ref_no><![CDATA[" + refNo + "]]></ref_no>");
			xmlString.append("<ref_date>").append("<![CDATA[").append(sdf.format(currentDate).toString()).append("]]></ref_date>\r\n");
			//xmlString.append("<ref_date><![CDATA[" + dueDate + "]]></ref_date>");
			xmlString.append("<remarks><![CDATA[" + "Generate Automatic payment from scheduler" + "]]></remarks>");
			xmlString.append("<net_amt><![CDATA[" + 0 + "]]></net_amt>");
			xmlString.append("<curr_code><![CDATA[" + currCode + "]]></curr_code>");
			xmlString.append("<exch_rate><![CDATA[" + mexrate + "]]></exch_rate>");
			xmlString.append("<net_amt__bc><![CDATA[" + 0 + "]]></net_amt__bc>");			
			xmlString.append("<site_code><![CDATA[" + siteCode + "]]></site_code>");
			xmlString.append("<site_descr><![CDATA[" + siteDescr + "]]></site_descr>");//Added by Jaimin 25/07/2007
			xmlString.append("<fin_entity><![CDATA[" + finEntity + "]]></fin_entity>");
			xmlString.append("<finent_descr><![CDATA[" + finentDescr + "]]></finent_descr>");//Added by Jaimin 25/07/2007
			xmlString.append("<acct_code__bal><![CDATA[" + acctCodeBal + "]]></acct_code__bal>");
			xmlString.append("<cctr_code__bal><![CDATA[" + cctrCodeBal + "]]></cctr_code__bal>");
			xmlString.append("<auto_paid><![CDATA[" + "Y" + "]]></auto_paid>");		
			xmlString.append("<bank_charges><![CDATA[" + 0 + "]]></bank_charges>");
			xmlString.append("<acct_code__bc><![CDATA[" + acctCodeBc + "]]></acct_code__bc>");
			xmlString.append("<cctr_code__bc><![CDATA[" + cctrCodeBc + "]]></cctr_code__bc>");
			xmlString.append("<curr_code__bc><![CDATA[" + currCodeBc + "]]></curr_code__bc>");
			xmlString.append("<exch_rate__bc><![CDATA[" + excRateBc + "]]></exch_rate__bc>");	
			xmlString.append("<acct_code__cf><![CDATA[" + acctCodeCf + "]]></acct_code__cf>");	
			xmlString.append("<cctr_code__cf><![CDATA[" + cctrCodeCf + "]]></cctr_code__cf>");
			xmlString.append("<tax_amt><![CDATA[" + 0 + "]]></tax_amt>");
			xmlString.append("<tax_date><![CDATA[" + payDate + "]]></tax_date>");
			xmlString.append("<WF_STATUS ><![CDATA[" + wfStatus + "]]></WF_STATUS >");
			xmlString.append("<bank_name><![CDATA[" + bankName + "]]></bank_name>");//Added by Jaimin 25/07/2007
						
			if (bankCodeAdd==null)
			{bankCodeAdd = "";}
			xmlString.append("<bank_code__add><![CDATA[" + bankCodeAdd + "]]></bank_code__add>");
			xmlString.append("<confirmed><![CDATA[N]]></confirmed>");
			xmlString.append("<emp_code__conf><![CDATA[]]></emp_code__conf>");
			xmlString.append("<conf_date><![CDATA[]]></conf_date>");
			xmlString.append("<chg_user><![CDATA[" + chgUser + "]]></chg_user>");
			xmlString.append("<chg_term><![CDATA[" + chgTerm + "]]></chg_term>");
			xmlString.append("<chg_date><![CDATA[" + chgDate + "]]></chg_date>");
			//xmlString.append("<chq_no__fr><![CDATA[" + chgFrm + "]]></chq_no__fr>");
			//xmlString.append("<chq_no__to><![CDATA[" + chgTo + "]]></chq_no__to>");			
			xmlString.append("</Detail1>");	
			
			System.out.println("XmlString Header======"+xmlString.toString());
			
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			System.out.println("parentNodeListLength:::::::::"+parentNodeListLength);
			//writeLog(filePtr,"parentNodeListLength-->"+parentNodeListLength,true);
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
			    parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength::: "+ childNodeListLength+"\n");
				//writeLog(filePtr,"childNodeListLength-->"+childNodeListLength,true);
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equals("ref_no"))
					{
						if(childNode.getFirstChild()!=null)
						{
							refNo = childNode.getFirstChild().getNodeValue();
						}
					}
					
					if (childNodeName.equals("ref_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							//refDate = childNode.getFirstChild().getNodeValue();
							refDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						}
					}
					if (childNodeName.equals("bill_no"))
					{
						if(childNode.getFirstChild()!=null)
						{
							billNo = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("bill_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							billDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
							
							//billDate = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("curr_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							currCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("exch_rate"))
					{
						if(childNode.getFirstChild()!=null)
						{
							exchRate = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("acct_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							acctCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("cctr_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							cctrCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("due_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							System.out.println("before tmpDate==========="+tmpDate);
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							System.out.println("after tmpDate==========="+tmpDate);
							//dueDate = childNode.getFirstChild().getNodeValue();
							dueDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
							System.out.println(" dueDate==========="+dueDate);
						}
					}
					if (childNodeName.equals("tot_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							totAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_type"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryType = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("pay_mode"))
					{
						if(childNode.getFirstChild()!=null)
						{
							payMode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("adv_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							advAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("tran_id"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranId = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("tran_ser"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranSer = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("adj_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							adjAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("hold_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							holdAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("username"))
					{
						if(childNode.getFirstChild()!=null)
						{
							userName = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("pay_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							payAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_name"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryName = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("net_payable"))
					{
						if(childNode.getFirstChild()!=null)
						{
							netPayable = childNode.getFirstChild().getNodeValue();
						}
					}
					
					if (childNodeName.equals("tran_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranDate = childNode.getFirstChild().getNodeValue();
						}
						transactionDate = genericUtility.getValidDateString(tranDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						
					}
					
				} // For inner loop
					//if (Double.parseDouble(netPayable) != 0 ) // Condition added by jaimin 16/08/2007 // Remarked by Raj - 29/12/2007
					
				//added on 30/mar by priyanka
				
				System.out.println("Getting RefNo Detail================="+refNo);
				System.out.println("Getting tranDate================"+tranDate);
				System.out.println(" transactionDate==========="+transactionDate);
				sql="select purc_order,eff_date,bill_date from voucher where tran_id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,refNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					porder=checkNull(rs.getString("purc_order"));
					effDate=rs.getDate("eff_date");
					billDt=rs.getDate("bill_date");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("Purchase order========="+porder);
				System.out.println("effDate========="+effDate);
				System.out.println("billDt========="+billDt);
				
				sql="select cr_term from porder where purc_order =?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,porder);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					sfld1=rs.getString("cr_term");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("sfld1========="+sfld1);
				
				sql="select crtermfc.fin_chg,crterm.acct_code__disc,crterm.cctr_code__disc,crterm.start_from from crterm,crtermfc " +
						"where crtermfc.cr_term = crterm.cr_term and crterm.cr_term =  ? and trim(crtermfc.line_no) = '1'";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,sfld1);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					discount=rs.getDouble("fin_chg");
					acctCodeDisc=checkNull(rs.getString("acct_code__disc"));
					cctrCodeDisc=checkNull(rs.getString("cctr_code__disc"));
					startFrom=checkNull(rs.getString("start_from"));
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				
				
				System.out.println("discount========="+discount);
				System.out.println("acctCodeDisc========="+acctCodeDisc);
				System.out.println("cctrCodeDisc========="+cctrCodeDisc);
				System.out.println("startFrom========="+startFrom);
				reDate1 = sdf.parse(refDate);
				 
			    Date discdt=getDiscountdate(sfld1, reDate1, effDate, billDt, conn);
			    System.out.println("Getting discdt======"+discdt);
			    if(discdt!=null)
			    {
			    	  System.out.println("Getting discdt not null==");
			        String discdt1=sdf.format(discdt);
			        System.out.println("Getting discdt================"+discdt1);	   
			        mPayDate=sdf.parse(transactionDate);
				    System.out.println("mPayDate============"+mPayDate);
				    
				    long diff = discdt.getTime() - mPayDate.getTime();
				    datediff = diff / (24 * 60 * 60 * 1000);
					 System.out.println("CurrDtae======================="+datediff);		
			    }
			
			    sql="select fin_chg  from crtermfc where  ? between min_day and max_day and cr_term = ? and trim(line_no) = '1'";
			    pstmt = conn.prepareStatement(sql);
			    pstmt.setLong(1,datediff);
			    pstmt.setString(2,sfld1);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					discount=rs.getDouble("fin_chg");					
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				System.out.println("Get Discount======="+discount);
			    if(discount==0)
			    {
			    	discount=0;
			    }
				 
				System.out.println(">>>>>>>>startFrom==="+startFrom);	
				if((startFrom!=null && startFrom.trim().length()>0) && "R".equalsIgnoreCase(startFrom))
				{
					ldStartDate=reDate1;
				}
				else if((startFrom!=null && startFrom.trim().length()>0) && "D".equalsIgnoreCase(startFrom)  && "Q".equalsIgnoreCase(startFrom))
				{
					ldStartDate=effDate;
				}
				else if((startFrom!=null && startFrom.trim().length()>0) && "B".equalsIgnoreCase(startFrom) )
				{
					ldStartDate=billDt;
				}
				
				if((payDate!=null && payDate.trim().length()>0) &&  ldStartDate!=null)
				{
					payDate1 = sdf.parse(payDate);
					
					if((payDate1.compareTo(ldStartDate)>0)&& payDate1.compareTo(discdt)<0)
					{
						if(discount!=0)
						{System.out.println("Discount not equals to Zerooooooooooooo");
							payAmt1=Double.parseDouble(payAmt);
							disAmt= payAmt1 *(discount/100);
						}
					}
				}
			    
				 System.out.println("disAmount=========="+disAmt);
			    System.out.println("PayMAode======="+payMode);
				System.out.println("BankCode>>>>>==="+bankCode);
				if("D".equalsIgnoreCase(payMode)||"P".equalsIgnoreCase(payMode))
				{
					System.out.println("payMode<<<<<<<<");
					drawnAt=checkNull(getpayablesAt(sundryType, sundryCode, bankCode, conn));
				}
			
				
				if("D".equalsIgnoreCase(payMode)||"P".equalsIgnoreCase(payMode)||"T".equalsIgnoreCase(payMode)||"N".equalsIgnoreCase(payMode))
				{
					System.out.println("payMode========>>>>");
				     stanCode=checkNull(getStanDraw(sundryType, sundryCode, conn));						
						System.out.println("Getting stanCode=============="+stanCode);
				}
				 

					
				if (Double.parseDouble(payAmt) != 0 ) // Condition added by jaimin 16/08/2007 // Changed by Raj - 29/12/2007
					{
						System.out.println("--------------> if payAmt>0 :: "+payAmt);
						System.out.println("--------------> if netPayable>0 :: "+netPayable);
						if ( (Double.parseDouble(netPayable) > 0 && Double.parseDouble(payAmt) <= Double.parseDouble(netPayable) && Double.parseDouble(payAmt) >=0) 
							|| (Double.parseDouble(netPayable) < 0 && Double.parseDouble(payAmt) <= 0 && Double.parseDouble(payAmt) >= Double.parseDouble(netPayable)) )
						{ // End by Jaimin 16/08/2007
							System.out.println("----------------In condition--------------");
						System.out.println("vouch_no============"+refNo);
						System.out.println("vouch_date============"+refDate);
						System.out.println("payAmt============"+payAmt);
						
						System.out.println("acct_code__ap========="+acctCode);
						System.out.println("cctr_code__ap========="+cctrCode);
						double payAmount=Double.parseDouble(payAmt);
						double exchRate1=Double.parseDouble(exchRate);
						diffAmt=((payAmount * exchRate1)-(payAmount*mexrate));
						System.out.println("diff_amt__exch========="+diffAmt);
											    
							lineNo++;
							xmlString.append("<Detail2 dbID=':' domID='1' objName='misc_pay' objContext='2'>");
							xmlString.append("<attribute pkNames='tran_id:line_no:' status='N' updateFlag='A' selected='N' />");
							xmlString.append("<tran_id><![CDATA[]]></tran_id>");
							xmlString.append("<tran_ser><![CDATA["+tranSer+"]]></tran_ser>");
							xmlString.append("<line_no><![CDATA["+lineNo+"]]></line_no>");							
							xmlString.append("<vouch_no><![CDATA["+refNo+"]]></vouch_no>");
							xmlString.append("<vouch_date><![CDATA[" + refDate + "]]></vouch_date>");//Added by Jaimin 25/07/2007
							xmlString.append("<net_amt><![CDATA["+payAmt+"]]></net_amt>");
							xmlString.append("<pay_amt><![CDATA["+payAmt+"]]></pay_amt>");
							xmlString.append("<curr_code><![CDATA["+currCodeBc+"]]></curr_code>");
							xmlString.append("<exch_rate__vouch><![CDATA["+exchRate+"]]></exch_rate__vouch>");							
							xmlString.append("<diff_amt__exch><![CDATA["+diffAmt+"]]></diff_amt__exch>");							
							xmlString.append("<acct_code__ap><![CDATA["+acctCode+"]]></acct_code__ap>");//
							xmlString.append("<cctr_code__ap><![CDATA["+cctrCode+"]]></cctr_code__ap>");//
							xmlString.append("<sundry_type><![CDATA["+sundryType+"]]></sundry_type>");//
							xmlString.append("<sundry_code><![CDATA["+sundryCode+"]]></sundry_code>");//					
							xmlString.append("<bank_charges><![CDATA["+0+"]]></bank_charges>");//
							xmlString.append("<stan_code><![CDATA["+stanCode+"]]></stan_code>");
							xmlString.append("<drawn_at><![CDATA["+drawnAt+"]]></drawn_at>");						
							xmlString.append("<tax_amt><![CDATA["+0+"]]></tax_amt>");//
							xmlString.append("<net_pay_amt><![CDATA["+payAmt+"]]></net_pay_amt>");//
							xmlString.append("<acct_code__disc><![CDATA["+acctCodeDisc+"]]></acct_code__disc>");//
							xmlString.append("<cctr_code__disc><![CDATA["+cctrCodeDisc+"]]></cctr_code__disc>");//	
							//xmlString.append("<tax_env><![CDATA["+exchRate+"]]></tax_env>");//doubtremaining
							xmlString.append("<bill_no><![CDATA["+billNo+"]]></bill_no>");
							xmlString.append("<bill_date><![CDATA["+billDate+"]]></bill_date>");
							xmlString.append("<exch_rate><![CDATA["+exchRate+"]]></exch_rate>");
																					
							xmlString.append("<discount_amt><![CDATA["+disAmt+"]]></discount_amt>");
							xmlString.append("<discount><![CDATA["+discount+"]]></discount>");	//		remaining		
							
						
							xmlString.append("<tot_amt><![CDATA["+totAmt+"]]></tot_amt>");
							//xmlString.append("<pay_mode><![CDATA["+payMode+"]]></pay_mode>");
							//xmlString.append("<adv_amt><![CDATA["+advAmt+"]]></adv_amt>");
							//xmlString.append("<adj_amt><![CDATA["+adjAmt+"]]></adj_amt>");
							//xmlString.append("<hold_amt><![CDATA["+holdAmt+"]]></hold_amt>");
							//xmlString.append("<net_payable><![CDATA["+netPayable+"]]></net_payable>");
							//xmlString.append("<curr_code><![CDATA["+currCode+"]]></curr_code>");
							//xmlString.append("<exch_rate><![CDATA["+exchRate+"]]></exch_rate>");
							
							//xmlString.append("<acct_code><![CDATA["+acctCode+"]]></acct_code>");
							//xmlString.append("<cctr_code><![CDATA["+cctrCode+"]]></cctr_code>");
							//xmlString.append("<due_date><![CDATA["+dueDate+"]]></due_date>");
							//xmlString.append("<pay_amt><![CDATA["+payAmt+"]]></pay_amt>");
							//xmlString.append("<tran_id__pay><![CDATA[]]></tran_id__pay>");
							//xmlString.append("<tran_id__miscpay><![CDATA["+tranId+"]]></tran_id__miscpay>");
							//xmlString.append("<sundry_name><![CDATA["+sundryName+"]]></sundry_name>");*/					
							xmlString.append("</Detail2>");		
							System.out.println("XmlString Detail======"+xmlString.toString());
						}
						else
						{//case added by Jaimin 17/08/2007
							System.out.println("--------------> Error<---------------------"+refNo);	
							
							errString= errString+	"\n"+ "[ref_no ::"+refNo+"]"
							+"\n"+ "[tran_ser ::"+tranSer+"]"
							+"\n"+ "[pay_mode ::"+payMode+"]" 
							+"\n"+"[net_payable ::"+netPayable+"]"
							+"\n"+"[pay_Amt ::"+payAmt+"]"+"\n";
							
						}
					}
				}
			System.out.println("XmlString ======"+xmlString.toString());
			System.out.println("Getting erroe-------"+errString);
			//FOR OUTER LOOP
			if (errString.trim().length()>0 )
			{				
				err = errMsg("","","",errString);
			}//End by Jaimin 17/08/2007
			else
			{
				xmlString.append("</Header0></group0></DocumentRoot>");			
				xmlOutString  = xmlString.toString();
				System.out.println("xmlOutString============="+xmlOutString);
				 //writeLog(filePtr,"xmlString-->\n"+xmlString,true);
				 String [] authencate = new String[2];
				 authencate[0] = "";
				 authencate[1] = "";
				 InitialContext ctx = null;
				 MasterStatefulLocal masterStateful = null;
				 AppConnectParm appConnect = new AppConnectParm();
				 ctx = new InitialContext(appConnect.getProperty());
				 masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");// added for ejb3
				 //MasterStateful masterStateful = masterStatefulHome.create(); //commented for ejb3
				 retString = masterStateful.processRequest(authencate, siteCode, true,xmlOutString);
				 
				 System.out.println("After save data ======================="+retString);
				 //Added - Gulzar - 25/01/08
				 if ( retString.indexOf("Success") > 0 )
				 {
					 retString = itmDBAccessEJB.getErrorString("","VTCOMPL","userId");
				 }
				 //End Added - Gulzar - 25/01/08
			}
			System.out.println("retString:: "+ retString);
		}	
		catch(Exception e)
		{
			//writeLog(filePtr,"Exception in process-->"+e,true);
			System.out.println( e.getMessage());
		}  
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch (Exception e)
			{
				//writeLog(filePtr,"Exception in process-->"+e,true);
				System.out.println(e.getMessage());
			}
		}
		if ( errString.trim().length() > 0 )
		{
			return err;
		}
		else
		{
			return retString;
		}
	}	
	//Function added by Jaimin 20/08/2007
	public String errMsg(String columnName,String msgNo,String userId,String errTrace)throws RemoteException,ITMException
	{
       Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		StringBuffer errStringXml;
		Statement stmt = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		String sqlQuery,sqlQuery1;
		String msgType = "";
		String msgString = "";
		String msgDescription = "";
		String lmsgString = "";
		String profileId = "";
		String errSource = "";
		String tempMsgType = "";
		String msgOption = "";		
		String msgTime = "";

		String redirerr = "" ;
		String soundPlay = "";
		FileOutputStream fos;
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			sqlQuery = "SELECT MSG_TYPE,MSG_STR,MSG_DESCR,MSG_OPT,MSG_TIME,ALARM,ERR_SOURCE FROM MESSAGES WHERE MSG_NO='" + msgNo + "'";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sqlQuery);
			if (rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
				msgString = rs.getString("MSG_STR");
				msgDescription = rs.getString("MSG_DESCR");
				errSource = rs.getString("ERR_SOURCE");
				msgOption = rs.getString("MSG_OPT");				
				msgTime = rs.getString("MSG_TIME");
				soundPlay = rs.getString("ALARM");
			}
			else
			{
				lmsgString = "Message Not Defined >>" + msgNo;
				msgDescription = "Message Id not found.";
				msgType = "";
				msgString = "";
			}

			if (msgType.equals("E") || msgType.trim().length() == 0) 
			{
				sqlQuery1 = "SELECT PROFILE_ID FROM USERS WHERE CODE='" + userId + "'";
				rs1 = conn.createStatement().executeQuery(sqlQuery1);
				if (rs1.next())
				{
					profileId=rs1.getString("profile_id");
					if (profileId == null)
					{
						profileId= "";
					}
					sqlQuery1 = "SELECT MSG_TYPE FROM MESSAGES_LEVEL WHERE MSG_NO='" + msgNo.trim() + "' AND PROFILE_ID='" + profileId.trim() + "'";
					rs2 = conn.createStatement().executeQuery(sqlQuery1);
					if (rs2.next())
					{
						tempMsgType = rs2.getString("msg_type");
					}
				}
				if (tempMsgType!=null && tempMsgType.trim().length()>0)
				{
					msgType = tempMsgType;
				}
			}
			if (msgType.equals("W"))
			{
				msgString = "Warning : " + msgString;
			}
			else if (msgType.equals("P"))
			{
				msgString = "Prompt : " + msgString;
			}
			else
			{
				msgType = "E";
				msgString = "Error : " + msgString;
			}
			if (errSource!=null && errSource.trim().equals("D"))
			{
				msgDescription = msgDescription +  " * From Database ";
			}
			if (redirerr==null || redirerr.trim().length()==0)
			{
				redirerr = "1";
			}
			if (msgOption!=null && msgOption.trim().equals("M"))
			{
				if (redirerr.trim().equals("1"))
				{
					redirerr = "2";
				}
				else
				{
					redirerr = "1";
				}
			}
			if (rs != null)
			{
				rs.close();
			}
			if (rs1 != null)
			{
				rs1.close();			
			}
			conn.close();
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException : [ValidatorEJB][getErrorString] :==>\n"+itme.getMessage());
			throw itme;
		}
		catch(SQLException se)
		{
			lmsgString = "Database Error >>" + se.getErrorCode(); //msgNo;
			msgDescription = se.getMessage();
			msgType = "";
			msgString = "";
			System.out.println("Exception : [ValidatorEJB][getErrorString] :==>\n"+se.getMessage());
			se.printStackTrace();
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [ValidatorEJB][getErrorString] :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		errStringXml = new StringBuffer();
		errStringXml.append("<?xml version=\"1.0\"?>\r\n<Root><Errors>\r\n");
		errStringXml.append("<error id=\"");
		errStringXml.append(msgNo).append("\" type=\"").append(msgType).append("\" column_name=\"");
		errStringXml.append(columnName).append("\">\r\n").append("<message>").append(msgString);
		errStringXml.append("</message>\r\n<description>").append(msgDescription).append("</description>\r\n");
		errStringXml.append("<type>").append(msgType).append("</type>\r\n<option>").append(msgOption).append("</option>\r\n");		
		errStringXml.append("<time>").append(msgTime).append("</time>\r\n");

		errStringXml.append("<alarm>").append(soundPlay).append("</alarm>\r\n<source>");
		errStringXml.append(errSource).append("</source>\r\n<trace>").append(errTrace);
		errStringXml.append("</trace>\r\n<redirect>").append(redirerr).append("</redirect>\r\n</error>\r\n");
		errStringXml.append("</Errors></Root>\r\n");
/*		if (msgType.trim().equals("E"))
		{
			errStringXml = buildErrorString();
		}*/
		try 
		{
			fos = new FileOutputStream("C:" + File.separator + "ErrorXml.xml");
			byte convertStringToByte[] = errStringXml.toString().getBytes();
			fos.write(convertStringToByte);
			fos.close();
		}
		catch(Exception e)
		{ 
			System.out.println("Exception : [ValidatorEJB][getErrorString] \n:==>"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errStringXml.toString();

	}
	

	private String checkNull(String str)
	{
		if(str == null)
		{
			return "";
		}
		else
		{
			return str ;
		}

	}
	
	
	public String getStanDraw(String sundryType ,String sundryCode,Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql="",stanCode="",empCode="";
		try
		{
			System.out.println(">>>>>>>>>Enter in getStanDraw method");			
			System.out.println(">>>>>>>>sundryType==="+sundryType);
			System.out.println(">>>>>>>>sundryCode==="+sundryCode);
			
			if((sundryType!=null && sundryType.trim().length()>0) && "E".equalsIgnoreCase(sundryType))
			{
				sql="select stan_code from employee where emp_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("StanCode from Sundry type=E>>>>>>"+stanCode);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "S".equalsIgnoreCase(sundryType))
			{
				sql="select stan_code from supplier where supp_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("StanCode from Sundry type= S>>>>>>"+stanCode);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "C".equalsIgnoreCase(sundryType))
			{
				sql="select stan_code from customer where cust_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("StanCode from Sundry type=C>>>>>>"+stanCode);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "P".equalsIgnoreCase(sundryType))
			{
				sql="select emp_code  from sales_pers where sales_pers = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					empCode = checkNull(rs.getString("emp_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				
				System.out.println("empCode from Sundry type=P>>>>>>"+empCode);
				
				if(empCode!=null && empCode.trim().length()>0)
				{
					sql="select stan_code from employee where emp_code = ?";
					pstmt= conn.prepareStatement(sql);
					pstmt.setString(1,empCode);				
					rs = pstmt.executeQuery(); 
					if(rs.next())
					{
						stanCode = checkNull(rs.getString("stan_code"));
					}
					rs.close();
					pstmt.close();
					pstmt = null;
					rs = null;
					System.out.println("StanCode from Sundry type=P>>>>>>"+stanCode);
				}
				
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "T".equalsIgnoreCase(sundryType))
			{
				sql="select stan_code  from transporter where tran_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("StanCode from Sundry type= T>>>>>>"+stanCode);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "X".equalsIgnoreCase(sundryType))
			{
				sql="select stan_code from tax_authority where tauth_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("StanCode from Sundry type= X>>>>>>"+stanCode);
			}
			
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + e);
		   throw new ITMException(e);
		}		
		return stanCode;
		
	}
	

	
	public String getpayablesAt(String sundryType ,String sundryCode,String bankCode,Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql="",payables="",empCode="",stanCode="",bankRef="";
		try
		{
			System.out.println(">>>>>>>>>Enter in getStanDraw method");			
			System.out.println(">>>>>>>>sundryType==="+sundryType);
			System.out.println(">>>>>>>>sundryCode==="+sundryCode);
			System.out.println(">>>>>>>>bankCode==="+bankCode);
			
			if((sundryType!=null && sundryType.trim().length()>0) && "E".equalsIgnoreCase(sundryType))
			{
				sql="select dd_payable_bank,stan_code from employee where emp_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("dd_payable_bank"));
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type=E>>>>>>"+payables);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "S".equalsIgnoreCase(sundryType))
			{
				sql="select bank_ref,stan_code from supplier where supp_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("bank_ref"));
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type= S>>>>>>"+payables);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "C".equalsIgnoreCase(sundryType))
			{
				sql="select bank_name ,stan_code from customer where cust_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("bank_name"));
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type=C>>>>>>"+payables);
			}
		
			else if((sundryType!=null && sundryType.trim().length()>0) && "T".equalsIgnoreCase(sundryType))
			{
				sql="select payable_ref,stan_code from transporter where tran_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("payable_ref"));
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type= T>>>>>>"+payables);
			}
			else if((sundryType!=null && sundryType.trim().length()>0) && "X".equalsIgnoreCase(sundryType))
			{
				sql="select bank_ref,stan_code from tax_authority where tauth_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,sundryCode);				
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("bank_ref"));
					stanCode = checkNull(rs.getString("stan_code"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type= X>>>>>>"+payables);
			}
			if(payables!=null && payables.trim().length()>0)
			{
				sql="select drawn_at, bank_ref  from bank_stan_serv where bank_code = ? and stan_code = ?";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,bankCode);
				pstmt.setString(2,stanCode);
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					payables = checkNull(rs.getString("drawn_at"));
					bankRef = checkNull(rs.getString("bank_ref"));
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				System.out.println("payables from Sundry type= X>>>>>>"+payables);
				System.out.println("bankRef from Sundry type= X>>>>>>"+bankRef);
				if(bankRef!=null && bankRef.trim().length()>0)
				{					
					payables=payables.trim() +","+bankRef.trim();
					System.out.println("Payables final====="+payables);
				}
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + e);
		   throw new ITMException(e);
		}		
		return payables;
		
	}
	
	
	public Date getDiscountdate(String crTerm ,Date vochurDate,Date effDate,Date billDt,Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql="",startFrom="",empCode="",stanCode="",bankRef="";
		Date tranDt=null,toDate=null,dueDate=null,newDate=null;
		String month1="",overrideDiscountDate="",liCrDays="";
	    long maxDay=0,liDays=0,liDueDays=0,liCrDays1=0;
		long currDays=0;
		 int liDays1=0;
		try
		{
			System.out.println(">>>>>>>>>Enter in getDiscountdate");			
			System.out.println(">>>>>>>>crTerm==="+crTerm);
			System.out.println(">>>>>>>>vochurDate==="+vochurDate);
			System.out.println(">>>>>>>>effDate==="+effDate);
			System.out.println(">>>>>>>>billDt==="+billDt);			
		
			sql="select start_from  from crterm where cr_term = ?";
			pstmt= conn.prepareStatement(sql);
			pstmt.setString(1,crTerm);			
			rs = pstmt.executeQuery(); 
			if(rs.next())
			{
				startFrom = checkNull(rs.getString("start_from"));				
			}
			rs.close();
			pstmt.close();
			pstmt = null;
			rs = null;
			System.out.println(">>>>>>>>startFrom==="+startFrom);	
			if((startFrom!=null && startFrom.trim().length()>0) && "R".equalsIgnoreCase(startFrom))
			{
				tranDt=vochurDate;
			}
			else if((startFrom!=null && startFrom.trim().length()>0) && "D".equalsIgnoreCase(startFrom)  && "Q".equalsIgnoreCase(startFrom))
			{
				tranDt=effDate;
			}
			else if((startFrom!=null && startFrom.trim().length()>0) && "B".equalsIgnoreCase(startFrom) )
			{
				tranDt=billDt;
			}
			
			SimpleDateFormat sdf=new SimpleDateFormat(genericUtility.getApplDateFormat());
			//newDate=sdf.format(tranDt);
			//newDate=sdf.parse(tranDt);
		   // Date date1 = sdf.parse(newDate);
			
			if(tranDt!=null)
			{
				Calendar cal = Calendar.getInstance();
				//cal.setTime(date1);
				cal.setTime(tranDt);
				int month = cal.get(Calendar.MONTH);
				System.out.println("Getting Month============="+month);
					if(month==12)
					{
						month=1;
						month1="01";				
					}
					else
					{
						month=month+1;
						if(month>9)
						{
							month1=Integer.toString(month);
						}
						else
						{
							month1="0"+Integer.toString(month);
						}
						
					}
					
			}
			
				sql="select override_discount_date  from crterm_disc where cr_term = ? and cr_month= ? and override_discount_date is not null";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,crTerm);	
				pstmt.setString(2,month1);	
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					System.out.println("Data  found>>>>>.");
					overrideDiscountDate = checkNull(rs.getString("override_discount_date"));		
					System.out.println("Getting overrideDiscountDate============="+overrideDiscountDate);
					liCrDays=overrideDiscountDate.substring(3, 2);
					 System.out.println("Getting liDays============="+liDays);
												
				}
				else
				{
					System.out.println("<<<<<,,,Data not found");
					sql="select crtermfc.max_day,crterm_disc.override_discount_date from crterm_disc,crtermfc " +
							"where crterm_disc.cr_term = crtermfc.cr_term  and trim(crtermfc.line_no) = '1' and crterm_disc.cr_term = ? and crterm_disc.cr_month = '99' and crterm_disc.override_discount_date is not null";
					pstmt1= conn.prepareStatement(sql);
					pstmt1.setString(1,crTerm);			
					rs1 = pstmt1.executeQuery(); 
					if(rs1.next())
					{
						maxDay = rs1.getInt("max_day");		
						overrideDiscountDate = checkNull(rs1.getString("override_discount_date"));	
						liCrDays=overrideDiscountDate.substring(3, 2);
						liCrDays1=Integer.parseInt(liCrDays);
						 System.out.println("Getting liDays============="+liDays);
					}
					else
					{
						sql="select max_day	from crtermfc where cr_term = ? and trim(crtermfc.line_no) = '1'";
						pstmt2= conn.prepareStatement(sql);
						pstmt2.setString(1,crTerm);			
						rs2 = pstmt2.executeQuery(); 
						if(rs2.next())
						{
							 liDays = rs2.getInt("max_day");		
							
						}
						rs2.close();
						pstmt2.close();
						pstmt2 = null;
						rs2 = null;
						if(liDays==0)
						{
							liDays=0;
						}
					}
					rs1.close();
					pstmt1.close();
					pstmt1 = null;
					rs1= null;
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				
				if(liDays==0)
				{
					liDays=0;
				}
				
				sql="select cr_days  from crterm where cr_term = ? ";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1,crTerm);			
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
					liDueDays = rs.getInt("cr_days");				
				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				if(overrideDiscountDate!=null && overrideDiscountDate.trim().length()>0)
				{
					sql="select to_date  from period where fr_date <= ? and to_date >=?";
					pstmt= conn.prepareStatement(sql);
					pstmt.setDate(1,(java.sql.Date) vochurDate);			
					pstmt.setDate(2,(java.sql.Date) vochurDate);			
					rs = pstmt.executeQuery(); 
					if(rs.next())
					{
						toDate = rs.getDate("to_date");				
					}
					rs.close();
					pstmt.close();
					pstmt = null;
					rs = null;
					long diff = vochurDate.getTime() - toDate.getTime();
					 currDays = diff / (24 * 60 * 60 * 1000);
					 System.out.println("CurrDtae======================="+currDays);
					 liDays=currDays+liCrDays1;
				 liDays1 = (int) liDays;
					 System.out.println("final liDays1======== "+liDays1);
				}
	if(tranDt!=null)
	{
	 Calendar calendar = Calendar.getInstance();    
   	calendar.setTime(tranDt);     
    // add one day to the date/calendar
    calendar.add(Calendar.DAY_OF_YEAR, liDays1);     
    // now get "tomorrow"
   dueDate = calendar.getTime(); 
	}
    // print out tomorrow's date
    System.out.println("dueDate: " + dueDate);
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + e);
		   throw new ITMException(e);
		}		
		return dueDate;
		
	}
 }