
package ibase.webitm.ejb.fin;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.lang.*;
import javax.ejb.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.util.HashMap;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import javax.naming.InitialContext;

import ibase.webitm.ejb.*;
import ibase.webitm.ejb.fin.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.utility.CommonConstants;
//import ibase.utility.CommunicationComp;
import ibase.webitm.utility.ITMException;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import org.xml.sax.InputSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class GenerateReceiptPrc extends ProcessEJB implements GenerateReceiptPrcLocal ,GenerateReceiptPrcRemote //SessionBean
{	
	ibase.webitm.utility.GenericUtility genericUtility = ibase.webitm.utility.GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	CommonConstants commonConstants = new CommonConstants();
	String userId = "";
	String siteCode = "";
	String custCodeFrom = "";
	String custCodeTo = "";
	String custCode = "";
	String sdueDate = "";
	String remarks = "";
	java.sql.Timestamp dueDate =  null;
	ArrayList invoiceList = new ArrayList();
	boolean amtFlag = true;
    PreparedStatement pstmt = null;
	Connection conn = null;
	ResultSet rs = null;

	int cntHdr = 0;
	double stdExchRate = 0,netAmtHdr = 0,billAmt = 0,billDiscAmt = 0;
	double advAdjAmtHdr = 0.0;
	double diffAmtExcHdr=0.0;


	File filePtr = new File("../log/pbnitrace.log");

	static
	{
		File mkd = new File("../log");
		if(!mkd.exists())
		{
			mkd.mkdirs();
			System.out.println("Directory Built................ "+mkd);
		}

	}

	/*public void ejbCreate() throws RemoteException, CreateException
	{
		try
		{

			
			System.out.println("GenerateReceiptPrcEJB ejbCreate called.........");

		}
		catch (Exception e)
		{
			System.out.println("Exception :GenerateReceiptPrcEJB :ejbCreate :==>"+e);
			throw new CreateException();
		}
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{	
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		try
		{
			writeLog(filePtr,"G E T D A T A I N P R O C E S S ",false);
			writeLog(filePtr,"Generating  Receipt(12:30).............. ",true);
			writeLog(filePtr,"Input Given To View Data.."+xmlString,true);
		}
		catch(Exception e)
		{
			e.printStackTrace(); 
			throw new ITMException(e);
		}
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0 )
			{
				System.out.println("XML String *.....*:"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :GenerateReceiptPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		return rtrStr; 
	}		

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{

	/*
	mplement customer group code concept. 

Define a running total of selected rows, receipt amt

Add the chq date, chq amount in Filter screen

Define udf str 2 of tran type gen codes, "J" for Jv. If Jv make bank code, chq no, chq date, customer bank as non editable. Set chq amount to 0.

If the customer code from and to are different make the chq no, chq date, chq amount, customer bank non editable. Set chq amount to null.

**Get chq no from sales order, not found take from argument. Should remain editable. For each different customer and chq it should create a receipt.

Put a validation chq amount in filter and total of details matches in case header chq amount is not blank/null. This should not validate on case amount in filter is null.

	*/
	
		//StringBuffer retTabSepStrBuff = new StringBuffer();
		StringBuffer retTabSepStrBuff = new StringBuffer("<?xml version = \"1.0\"?>");
		retTabSepStrBuff.append("<DocumentRoot>");
		retTabSepStrBuff.append("<description>").append("Datawindow Root").append("</description>");
		retTabSepStrBuff.append("<group0>");
		retTabSepStrBuff.append("<description>").append("Group0 description").append("</description>");
		retTabSepStrBuff.append("<Header0>");
		
		java.sql.Date currDate = new java.sql.Date(System.currentTimeMillis());
		String sql = "";
		String errCode = "";
		String errString = "";
		String resultString = "", filterChqNo = "", sFilterChqAmt = "", sFilterChqDate = "";
	    java.sql.Timestamp dueDateTo = null;
		//String tranSer2 = "";
	    SimpleDateFormat sdf=null;
		try
		{
			if(conn==null)
			{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
			}
			sdf=new SimpleDateFormat(genericUtility.getApplDateFormat());
			DatabaseMetaData dbmd = conn.getMetaData();
			writeLog(filePtr,"DriverName["+dbmd.getDriverName() + "]",true);
			writeLog(filePtr,"DriverURI["+dbmd.getURL()  + "]",true);
			writeLog(filePtr,"DriverUSER["+dbmd.getUserName() + "]",true);
			writeLog(filePtr,"ApplDateFormat["+genericUtility.getApplDateFormat() + "]",true);
			writeLog(filePtr,"DBDateFormat["+genericUtility.getDBDateFormat() + "]",true);

			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			writeLog(filePtr,"siteCode:::"+siteCode,true);
			System.out.println("siteCode------>"+ siteCode);

			if(siteCode == null || siteCode.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VMSITECD1","","",conn);
				return errString;
			}
			if(siteCode != null && siteCode.trim().length() != 0)
			{
				try
				{
					int count = 0;
					sql = "SELECT COUNT(1) AS COUNT FROM SITE WHERE SITE_CODE = ? " ;//'"+siteCode.trim()+"'";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,siteCode.trim());
					rs = pstmt.executeQuery();
			 		if(rs.next())
					{
						count = rs.getInt("COUNT");
						System.out.println("SITE_CODE count is ::- "+count );
					}
					if(count == 0)
					{
						writeLog(filePtr,"siteCode NOT founds in siteMaster:::",true);
						errCode = "VMSITE1";
						errString = itmDBAccessEJB.getErrorString("site_code",errCode,userId,"",conn);
						return errString;
					}
					rs.close();
					pstmt.close();

				}
				catch(Exception ex)
				{
					System.out.println("Exception []::"+sql+ex.getMessage());
					ex.printStackTrace();
				}
			}
			custCodeFrom = genericUtility.getColumnValue("cust_code__from",headerDom);//added by rajesh k to get cust_code__from
			custCodeTo = genericUtility.getColumnValue("cust_code__to",headerDom);//added by rajesh k to get cust_code__to
			filterChqNo = genericUtility.getColumnValue("cheque_no",headerDom);
			sFilterChqAmt = genericUtility.getColumnValue("cheque_amount",headerDom);
			remarks = genericUtility.getColumnValue("remarks",headerDom); //added by Kunal on 19/10/12
			System.out.println("remarks"+remarks+"  filterChqNo="+filterChqNo);
			sFilterChqDate = genericUtility.getColumnValue("cheque_date",headerDom);
			if (filterChqNo == null || filterChqNo.trim().length() == 0)
			{
				filterChqNo = "";
			}
			if (sFilterChqAmt == null || sFilterChqAmt.trim().length() == 0)
			{
				sFilterChqAmt = "0.00";
			}
			if (sFilterChqDate == null || sFilterChqDate.trim().length() == 0)
			{
				sFilterChqDate = "";
			}
			//custCode = genericUtility.getColumnValue("cust_code",headerDom);
			//System.out.println("custCode is :::"+custCode);
			System.out.println("cust_code__from is :::"+custCodeFrom);
			System.out.println("cust_code__to is :::"+custCodeTo);
			writeLog(filePtr,"cust_code__from:::"+custCodeFrom,true);
			writeLog(filePtr,"cust_code__to:::"+custCodeTo,true);

			if(custCodeFrom == null || custCodeFrom.trim().length() ==0)  //ADDED BY RAJESH K TO CHECK CUSTCODEFROM AND CUSTCODETO
			{
				errString = itmDBAccessEJB.getErrorString("","VTMSG","","",conn);
				return errString;
			}
			if(custCodeTo == null || custCodeTo.trim().length() ==0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTMSG","","",conn);
				return errString;
			}


			/*writeLog(filePtr,"custCode:::"+custCode,true);
			if(custCode == null || custCode.trim().length() ==0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTMSG","","",conn);
				return errString;
			}*/

			sdueDate = genericUtility.getColumnValue("due_date",headerDom);
			System.out.println("due_date is :::"+sdueDate);
			writeLog(filePtr,"sdueDate:::"+sdueDate,true);
			if ( sdueDate == null || sdueDate.trim().length() == 0 )
			{
				sdueDate = "";
				System.out.println("due_date is null.............");
				errString = itmDBAccessEJB.getErrorString("","INVDT1","","",conn);
				return errString;
			}
			sdueDate = genericUtility.getValidDateString(sdueDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dueDate = java.sql.Timestamp.valueOf(sdueDate + " 00:00:00");
			System.out.println("Due Date  **..........................**:"+dueDate);

			sdueDate = genericUtility.getColumnValue("due_date_to",headerDom);
			System.out.println("due_date is :::"+sdueDate);
			writeLog(filePtr,"sdueDate:::"+sdueDate,true);
			if ( sdueDate == null || sdueDate.trim().length() == 0 )
			{
				sdueDate = "";
				System.out.println("due_date is null.............");
				errString = itmDBAccessEJB.getErrorString("","INVDT1","","",conn);
				return errString;
			}
			sdueDate = genericUtility.getValidDateString(sdueDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dueDateTo = java.sql.Timestamp.valueOf(sdueDate + " 00:00:00");
			System.out.println("Due Date  **..........................**:"+dueDate);

			try
			{
				// 13-09-2006 manoharan as per kedar cheque # to be checked in
				// invoice_amendment (invoice_amendment is compulsory)
				//sql = "SELECT A.INVOICE_ID,A.TRAN_DATE,D.TOT_AMT - D.ADJ_AMT,C.CUST_NAME,"
				//	+ "B.BANK_CODE,B.CHEQUE_DATE,B.CHEQUE_NO,B.CHQ_AMOUNT "
				//	+ "FROM INVOICE A,SORDER B ,CUSTOMER C, RECEIVABLES D  "
				//	+ "WHERE A.SALE_ORDER = B.SALE_ORDER "
				//	+ "AND A.CUST_CODE = C.CUST_CODE "
				//	+ "AND D.TRAN_SER = 'S-INV' "
				//	+ "AND D.REF_NO = A.INVOICE_ID "
				//	+ "AND D.TOT_AMT - D.ADJ_AMT > 0 "
				//	+ "AND A.SITE_CODE = '"+siteCode.trim()+"' "
				//	+ "AND A.CUST_CODE = '"+custCode.trim()+"' "
				//	+ "AND A.DUE_DATE = ? "
				//	+ "AND B.CHEQUE_NO IS NOT NULL "
				//	+ "AND NOT EXISTS (SELECT 1 FROM RECEIPT I "
				//	+ "WHERE I.SITE_CODE = A.SITE_CODE "
				//	+ "AND I.CUST_CODE = A.CUST_CODE "
				//	+ "AND I.REF_NO = B.CHEQUE_NO ) "
				//	+ "ORDER BY B.CHEQUE_NO ";

				// 20/07/12 manoharan invoice amendment  consideration removed
				/*//Manoj dtd 28/12/2012 Not Required
				 sql = "SELECT A.INVOICE_ID,D.TRAN_SER,A.TRAN_DATE,D.TOT_AMT - D.ADJ_AMT,C.CUST_NAME,"
				 
					+ "B.BANK_CODE,B.CHEQUE_DATE,E.REF_NO AS CHEQUE_NO,B.CHQ_AMOUNT,A.CUST_CODE,D.TOT_AMT  "		//added by rajesh k to get cust_code
					+ "FROM INVOICE A,SORDER B ,CUSTOMER C, RECEIVABLES D, INVOICE_AMENDMENT E  "
					+ "WHERE A.SALE_ORDER = B.SALE_ORDER "
					+ "AND A.CUST_CODE = C.CUST_CODE "
					+ "AND D.TRAN_SER = 'S-INV' "
					+ "AND D.REF_NO = A.INVOICE_ID "
					+ "AND D.TOT_AMT - D.ADJ_AMT > 0 "
					+ "AND E.INVOICE_ID = A.INVOICE_ID "
					+ "AND E.CONFIRMED = 'Y' "
					+ "AND E.STATUS = 'S' "
					+ "AND E.REF_NO IS NOT NULL "
					+ "AND A.SITE_CODE = ? "
					//+ "AND A.CUST_CODE >= '"+custCodeFrom.trim()+"' AND A.CUST_CODE <= '"+custCodeTo.trim()+"' "
					//+ " c.cust_code in ( select distinct group_code from customer where cust_code >= ? and cust_code <= ?) "
					+" and a.cust_code in (select cust_code  from customer where group_code in ( select distinct group_code from customer where group_code >= ? and group_code <= ? ) ) " //added by Kunal on 19/10/12
				//	+ "AND A.DUE_DATE = ? "
				//	+ "AND D.EXP_RCP_DATE = ? "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					+ "AND ((D.DUE_DATE >= ? "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					+ "AND D.DUE_DATE <= ? ) OR (D.DUE_DATE IS NULL)) "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					+ "AND NOT EXISTS (SELECT 1 FROM RECEIPT I "
					+ "WHERE I.SITE_CODE = A.SITE_CODE "
					+ "AND I.CUST_CODE = A.CUST_CODE "
					+ "AND I.REF_NO = E.REF_NO ) "
					+ "ORDER BY A.CUST_CODE, E.REF_NO  ";

				sql = "SELECT A.INVOICE_ID,D.TRAN_SER,A.TRAN_DATE,D.TOT_AMT - D.ADJ_AMT,C.CUST_NAME,"
					//+ "B.BANK_CODE,B.CHEQUE_DATE,(select E.REF_NO from invoice_amendment e where e.invoice_id = a.invoice_id and e.status = 'S' and e.confirmed = 'Y') AS CHEQUE_NO ,B.CHQ_AMOUNT,A.CUST_CODE,D.TOT_AMT  "		//added by rajesh k to get cust_code
					  + "B.BANK_CODE,B.CHEQUE_DATE,'' AS CHEQUE_NO ,B.CHQ_AMOUNT,A.CUST_CODE,D.TOT_AMT  "                //Added by manoj dtd 21/12/2012            
					+ "FROM INVOICE A,SORDER B ,CUSTOMER C, RECEIVABLES D " //INVOICE_AMENDMENT E  "
					+ "WHERE A.SALE_ORDER = B.SALE_ORDER "
					+ "AND A.CUST_CODE = C.CUST_CODE "
					+ "AND D.TRAN_SER = 'S-INV' "
					+ "AND D.REF_NO = A.INVOICE_ID "
					+ "AND D.TOT_AMT - D.ADJ_AMT > 0 "
					//+ "AND E.INVOICE_ID = A.INVOICE_ID "
					//+ "AND E.CONFIRMED = 'Y' "
					//+ "AND E.STATUS = 'S' "
					//+ "AND E.REF_NO IS NOT NULL "
					+ "AND A.SITE_CODE = ? "
					//+ "AND A.CUST_CODE >= '"+custCodeFrom.trim()+"' AND A.CUST_CODE <= '"+custCodeTo.trim()+"' "
					//+ " and c.group_code in ( select distinct group_code from customer where cust_code >= ? and cust_code <= ?) "
						+" and a.cust_code in (select cust_code  from customer where group_code in ( select distinct group_code from customer where group_code >= ? and group_code <= ? ) ) " 
				//	+ "AND A.DUE_DATE = ? "
				//	+ "AND D.EXP_RCP_DATE = ? "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					+ "AND ((D.DUE_DATE >= ? "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					+ "AND D.DUE_DATE <= ? ) OR (D.DUE_DATE IS NULL)) "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					
					/* 22/12/2012 Commented by  Manoj not required
					+ "AND NOT EXISTS (SELECT 1 FROM RECEIPT I "
					+ "WHERE I.SITE_CODE = A.SITE_CODE "
					+ "AND I.CUST_CODE = A.CUST_CODE "
					//+ "AND I.REF_NO = (select E.REF_NO from invoice_amendment e where e.invoice_id = a.invoice_id and e.status = 'S' and e.confirmed = 'Y') " // Commented by manoj dtd 21/12/2012 to remove join with invoice amendment
					+" ) "
					*/
					/*+ "ORDER BY A.CUST_CODE  ";
				//this.fw.write("getData SQL ..."+ sql + "\n");
				writeLog(filePtr,"GetData 1st Sql :::."+ sql,true);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCode.trim());
				pstmt.setString(2,custCodeFrom.trim());
				pstmt.setString(3,custCodeTo.trim());
				pstmt.setTimestamp(4,dueDate);
				pstmt.setTimestamp(5,dueDateTo);
				writeLog(filePtr,"dueDate :::."+ dueDate.toString(),true);
				System.out.println("The getDataSQL becomes .................:"+sql);
				writeLog(filePtr,"############## :::."+ sql,true);
				rs = pstmt.executeQuery();

	       		while (rs.next())
				{
				// invoice_id	  tran_ser	tran_date	cust_ref	inv_amt	adj_amt	cust_name
				//TD0000       	MDRCRD  	2012-07-04	        	50.0	0.0		CVS PHARMACY			COORD		 	0.0	2012-07-04	 	CV0004    	0.0

					//INVOICE_ID
	       			System.out.println(sdf.format(rs.getTimestamp(3)));
					retTabSepStrBuff.append((rs.getString(1)==null?"  ":rs.getString(1).trim())).append("\t");
					//TRAN_SER
					retTabSepStrBuff.append((rs.getString(2)==null?"  ":rs.getString(2).trim())).append("\t");
					//TRAN_DATE
					retTabSepStrBuff.append(sdf.format(rs.getTimestamp(3))).append("\t");
					// cust_ref_no 
					retTabSepStrBuff.append("").append("\t");
					//INV_AMT
					retTabSepStrBuff.append(rs.getDouble(4)).append("\t");
					//Added by manoj dtd 18/10/2012 to display absolute value
					retTabSepStrBuff.append(Math.abs(rs.getDouble(4))).append("\t");
					// adj_amt
					retTabSepStrBuff.append(rs.getDouble(4)).append("\t");
					//CHEQUE_NO
					// 20/07/12 manoharan if cheque number is not specified in sales order set from augument
					System.out.println("ch no 1 = "+rs.getString(8));
					if(rs.getString(8)==null || rs.getString(8).trim().length() == 0)
					{
						retTabSepStrBuff.append(filterChqNo).append("\t");
					}
					else
					{
						retTabSepStrBuff.append((rs.getString(8)==null?"  ":rs.getString(8).trim())).append("\t");
					}
					//CUST_NAME
					retTabSepStrBuff.append((rs.getString(5)==null?"  ":rs.getString(5).trim())).append("\t");
					// due_date
					retTabSepStrBuff.append("").append("\t");
					// cust_ref_date
					retTabSepStrBuff.append("").append("\t");
					// reas_code
					retTabSepStrBuff.append("").append("\t");
					// reas_detail
					retTabSepStrBuff.append("").append("\t");
					//CHQ_AMOUNT
					retTabSepStrBuff.append(rs.getDouble(9)).append("\t");
					//CHEQUE_DATE
					if(rs.getString(7) == null)
					{
						//retTabSepStrBuff.append(currDate).append("\t");
						retTabSepStrBuff.append(sdf.format(currDate)).append("\t");
					}
					else
					{
						retTabSepStrBuff.append(sdf.format(rs.getTimestamp(7))).append("\t");
					}
					//BANK_CODE
					retTabSepStrBuff.append((rs.getString(6)==null?"  ":rs.getString(6).trim())).append("\t");
					//CUST_CODE
					retTabSepStrBuff.append((rs.getString(10)==null?"  ":rs.getString(10).trim())).append("\t"); // added by rajesh k to get cust_code
					// cust_ref_amt
					retTabSepStrBuff.append("0").append("\t");
					retTabSepStrBuff.append(remarks).append("\t");
					// adjusted_amt
					retTabSepStrBuff.append(0).append("\t");
					retTabSepStrBuff.append(rs.getDouble("TOT_AMT")).append("\n");
					System.out.println("INVOICE_ID :::::::: "+rs.getString(1));
					System.out.println("TRAN_DATE :::::::: "+rs.getDate(3));
					writeLog(filePtr,"@@@@@@@@@@@@@@ INVOICE_ID :::."+rs.getString(1),true);
					writeLog(filePtr,"@@@@@@@@@@@@@@ CHEQUE_DATE :::."+rs.getString(7),true);
					writeLog(filePtr,"@@@@@@@@@@@@@@ CHQ_AMOUNT :::."+rs.getDouble(9),true);
					writeLog(filePtr,"@@@@@@@@@@@@@@ BANK_CODE :::."+rs.getString(6),true);

				}//while
				rs.close();
				pstmt.close();
				*/
				//*********Added on 28092006
				sql = "SELECT D.REF_NO,D.TRAN_SER,D.REF_DATE,D.TOT_AMT - D.ADJ_AMT,C.CUST_NAME ,"
					//+ "' ' C.BANK_CODE,D.TRAN_DATE,' ' AS CHEQUE_NO,0.0 CHQ_AMOUNT,C.CUST_CODE "
					+ "' ' BANK_CODE,D.TRAN_DATE,' ' AS CHEQUE_NO,0.0 CHQ_AMOUNT,C.CUST_CODE, " //  ADDED BY RAJESH AS ALIAS IS NOT REQUIRED FOR BANK_CODE
					+ " D.CUST_REF_NO,D.REAS_CODE,D.REAS_DETAIL,D.CUST_REF_DATE,D.ADJ_AMT,D.CUST_REF_AMT,D.DUE_DATE,D.TOT_AMT  " //  ADDED BY RAJESH AS ALIAS IS NOT REQUIRED FOR BANK_CODE
					+ "FROM CUSTOMER C, RECEIVABLES D  "
					+ "WHERE  C.CUST_CODE = D.CUST_CODE "
					//+ "AND D.TRAN_SER <> 'S-INV' "//Manoj dtd 28/12/2012 Not Required
					+ "AND D.TOT_AMT - D.ADJ_AMT <> 0 "
					+ "AND D.SITE_CODE = ? " //'"+siteCode.trim()+"' "
					//+ "AND D.CUST_CODE >= '"+custCodeFrom.trim()+"' AND  D.CUST_CODE <= '"+custCodeTo.trim()+"' "
					//+ " and c.group_code in ( select distinct group_code from customer where cust_code >= ? and cust_code <= ?) "
					+" and C.cust_code in (select cust_code  from customer where group_code in ( select distinct group_code from customer where group_code >= ? and group_code <= ? ) ) "
					// commented by cpatil start on 30-03-13
					//+ "AND ((D.DUE_DATE >= ? "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					//+ "AND D.DUE_DATE <= ? ) OR (D.DUE_DATE IS NULL)) "//CHANGES MADE ON 18/12/2006 AND A.DUE_DATE->D.EXP_RCP_DATE
					//+ "ORDER BY D.DUE_DATE ";
					// commented by cpatil end on 30-03-13					
					+ "AND ((D.TRAN_DATE >= ? " 
					+ "AND D.TRAN_DATE <= ? ) OR (D.TRAN_DATE IS NULL)) "
					+ "ORDER BY D.TRAN_DATE ";
				writeLog(filePtr,"GetData 2nd Sql :::."+ sql,true);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCode.trim());
				pstmt.setString(2,custCodeFrom.trim());
				pstmt.setString(3,custCodeTo.trim());
				pstmt.setTimestamp(4,dueDate);
				pstmt.setTimestamp(5,dueDateTo);
				System.out.println("The getDataSQL Becomes ......:"+sql);
				rs = pstmt.executeQuery();
	       		while (rs.next())
				{
	       			retTabSepStrBuff.append("<Detail2>");
	       			System.out.println("ch no 1 = "+rs.getString(8));
	       			
	       		//TRAN_SERNO
					//retTabSepStrBuff.append(rs.getString(2)).append("\t");
					retTabSepStrBuff.append("<tran_ser>").append("<![CDATA[" + rs.getString(2) +"]]>").append("</tran_ser>");
					//INVOICE_ID
					//retTabSepStrBuff.append(rs.getString(1)).append("\t");
	       			
	       			//added by kunal on 04/02/13 Data set in Xml string format 	       			
	       			retTabSepStrBuff.append("<invoice_id>").append("<![CDATA[" + rs.getString(1) +"]]>").append("</invoice_id>");       			
	       			
	       		//cust_ref_no
					if (rs.getString("CUST_REF_NO") == null || rs.getString("CUST_REF_NO").trim().length() == 0)
					{
						//retTabSepStrBuff.append("").append("\t");
						retTabSepStrBuff.append("<cust_ref_no>").append("<![CDATA[]]>").append("</cust_ref_no>");
					}
					else
					{
						//retTabSepStrBuff.append(rs.getString("CUST_REF_NO")).append("\t");
						retTabSepStrBuff.append("<cust_ref_no>").append("<![CDATA[" +rs.getString("CUST_REF_NO") +"]]>").append("</cust_ref_no>");						
					}
					//TRAN_DATE
					//retTabSepStrBuff.append(rs.getDate(3)).append("\t");
					System.out.println(sdf.format(rs.getTimestamp(3)));
					//retTabSepStrBuff.append(sdf.format(rs.getTimestamp(3))).append("\t");
					retTabSepStrBuff.append("<tran_date>").append("<![CDATA[" +sdf.format(rs.getTimestamp(3)) +"]]>").append("</tran_date>");
					//TOT_AMT
					//retTabSepStrBuff.append(rs.getDouble("TOT_AMT")).append("\n");
					retTabSepStrBuff.append("<tot_amt>").append("<![CDATA["+rs.getDouble("TOT_AMT")+"]]>").append("</tot_amt>");
					//retTabSepStrBuff.append(Math.abs(rs.getDouble(4))).append("\t");
					retTabSepStrBuff.append("<bal_amt>").append("<![CDATA[" +Math.abs(rs.getDouble(4)) +"]]>").append("</bal_amt>");					
					//adj_AMT
					//retTabSepStrBuff.append(rs.getDouble(4)).append("\t");
					retTabSepStrBuff.append("<adj_amt>").append("<![CDATA[" +rs.getDouble(4) +"]]>").append("</adj_amt>");
					
					// adjusted_amt
					//retTabSepStrBuff.append(rs.getDouble("ADJ_AMT")).append("\t");
					retTabSepStrBuff.append("<adjusted_amt>").append("<![CDATA["+rs.getDouble("ADJ_AMT")+"]]>").append("</adjusted_amt>");		
					
					//INV_AMT
					//retTabSepStrBuff.append(rs.getDouble(4)).append("\t");
					retTabSepStrBuff.append("<inv_amt>").append("<![CDATA[" +rs.getDouble(4) +"]]>").append("</inv_amt>");
					//Added by manoj dtd 18/10/2012 to display absolute value					
					
					//CUST_NAME
					//retTabSepStrBuff.append(rs.getString(5)).append("\t");
					retTabSepStrBuff.append("<cust_name>").append("<![CDATA[" +rs.getString(5) +"]]>").append("</cust_name>");
					//CUST_CODE
					//retTabSepStrBuff.append(rs.getString(10)).append("\t");//added by rajesh k to append cust_code
					retTabSepStrBuff.append("<cust_code>").append("<![CDATA["+rs.getString(10)+"]]>").append("</cust_code>");
					
					//BANK_CODE
					//retTabSepStrBuff.append(rs.getString(6)).append("\t");
					retTabSepStrBuff.append("<bank_code>").append("<![CDATA["+rs.getString(6)+"]]>").append("</bank_code>");
					
					//CHEQUE_DATE
					if(rs.getDate(7) == null)
					{
						//retTabSepStrBuff.append(currDate).append("\t");
						//retTabSepStrBuff.append(sdf.format(currDate)).append("\t");
						retTabSepStrBuff.append("<cheque_date>").append("<![CDATA["+sdf.format(currDate)+"]]>").append("</cheque_date>");
					}
					else
					{
						//retTabSepStrBuff.append(sdf.format(rs.getTimestamp(7))).append("\t");
						retTabSepStrBuff.append("<cheque_date>").append("<![CDATA["+sdf.format(rs.getTimestamp(7))+"]]>").append("</cheque_date>");
					}
					
					//CHEQUE_NO
					if(rs.getString(8)==null || rs.getString(8).trim().length() == 0) //change done by Kunal on 19/10/12 
					{
						//retTabSepStrBuff.append(filterChqNo).append("\t");
						retTabSepStrBuff.append("<cheque_no>").append("<![CDATA[" +filterChqNo +"]]>").append("</cheque_no>");
					}
					else
					{
						//retTabSepStrBuff.append((rs.getString(8)==null?"  ":rs.getString(8).trim())).append("\t");
						retTabSepStrBuff.append("<cheque_no>").append("<![CDATA[" +(rs.getString(8)==null?"  ":rs.getString(8).trim()) +"]]>").append("</cheque_no>");
					}
					//retTabSepStrBuff.append(rs.getString(8)).append("\t");
					
					//CHQ_AMOUNT
					//retTabSepStrBuff.append(rs.getDouble(9)).append("\t");
					retTabSepStrBuff.append("<chq_amount>").append("<![CDATA["+rs.getDouble(9)+"]]>").append("</chq_amount>");
					
					//cust_ref_date
					if(rs.getDate("CUST_REF_DATE") == null)
					{
						//retTabSepStrBuff.append("").append("\t");
						retTabSepStrBuff.append("<cust_ref_date>").append("<![CDATA[]]>").append("</cust_ref_date>");
					}
					else
					{
			 			//retTabSepStrBuff.append(rs.getDate("CUST_REF_DATE")).append("\t");
						//retTabSepStrBuff.append(sdf.format(rs.getTimestamp("CUST_REF_DATE"))).append("\t");
						retTabSepStrBuff.append("<cust_ref_date>").append("<![CDATA["+sdf.format(rs.getTimestamp("CUST_REF_DATE"))+"]]>").append("</cust_ref_date>");
					}			
					
					
					//due_date
					if(rs.getDate("DUE_DATE") == null)
					{
						//retTabSepStrBuff.append("").append("\t");
						retTabSepStrBuff.append("<due_date>").append("<![CDATA[]]>").append("</due_date>");
					}
					else
					{
						//retTabSepStrBuff.append(sdf.format(rs.getTimestamp("DUE_DATE"))).append("\t");
						retTabSepStrBuff.append("<due_date>").append("<![CDATA[" +sdf.format(rs.getTimestamp("DUE_DATE")) +"]]>").append("</due_date>");
					}
					
					//reas_CODE
					if (rs.getString("REAS_CODE") == null || rs.getString("REAS_CODE").trim().length() == 0)
					{
						//retTabSepStrBuff.append("").append("\t");
						retTabSepStrBuff.append("<reas_code>").append("<![CDATA[]]>").append("</reas_code>");
					}
					else
					{
						//retTabSepStrBuff.append(rs.getString("REAS_CODE")).append("\t");
						retTabSepStrBuff.append("<reas_code>").append("<![CDATA["+rs.getString("REAS_CODE")+"]]>").append("</reas_code>");
					}
					//reas_detail
					if (rs.getString("REAS_DETAIL") == null || rs.getString("REAS_DETAIL").trim().length() == 0)
					{
						//retTabSepStrBuff.append("").append("\t");
						retTabSepStrBuff.append("<reas_detail>").append("<![CDATA[]]>").append("</reas_detail>");
					}
					else
					{
						//retTabSepStrBuff.append(rs.getString("REAS_DETAIL")).append("\t");
						retTabSepStrBuff.append("<reas_detail>").append("<![CDATA["+rs.getString("REAS_DETAIL")+"]]>").append("</reas_detail>");
					}
					
					
					//cust_ref_amt
					//retTabSepStrBuff.append(rs.getDouble("CUST_REF_AMT")).append("\t");
					retTabSepStrBuff.append("<cust_ref_amt>").append("<![CDATA["+rs.getDouble("CUST_REF_AMT")+"]]>").append("</cust_ref_amt>");
					//retTabSepStrBuff.append(remarks).append("\t");
					retTabSepStrBuff.append("<remarks>").append("<![CDATA["+remarks+"]]>").append("</remarks>");
					
					
					
					
					System.out.println("INVOICE_ID :::::::: "+rs.getString(1));
					writeLog(filePtr,"%%%%%%%%% INVOICE_ID :::."+rs.getString(1),true);
					writeLog(filePtr,"%%%%%%%%% CHEQUE_DATE :::."+rs.getString(7),true);
					writeLog(filePtr,"%%%%%%%%% CHQ_AMOUNT :::."+rs.getDouble(9),true);
					writeLog(filePtr,"%%%%%%%%% CHEQUE_DATE :::."+rs.getString(6),true);
					
					retTabSepStrBuff.append("</Detail2>");


				}//while
				rs.close();
				pstmt.close();
				retTabSepStrBuff.append("</Header0>");
				retTabSepStrBuff.append("</group0>");
				retTabSepStrBuff.append("</DocumentRoot>");
				
				System.out.println("xml string::::"+retTabSepStrBuff);

			//*********
			}//try
			catch (SQLException e)
			{
				writeLog(filePtr,e,true);
				System.out.println("SQLException ::GenerateReceiptPrcEJB :" +sql+ e.getMessage() + ":");
				throw new ITMException(e);
			}
			catch(Exception ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception []::GenerateReceiptPrcEJB :"+ex.getMessage());
				ex.printStackTrace();
				throw new ITMException(ex);
			}

			resultString = retTabSepStrBuff.toString();
			writeLog(filePtr,resultString,true);
			if (!errCode.equals(""))
			{
				resultString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				System.out.println("resultString.........: " + resultString);
			}
		}//outer try
		catch (SQLException e)
		{
			writeLog(filePtr,e,true);
			System.out.println("SQLException ::GenerateReceiptPrcEJB :" +sql+ e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch(Exception ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception []::GenerateReceiptPrcEJB :"+ex.getMessage());
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		finally
		{
			try
			{
				retTabSepStrBuff = null;
				conn.close();
				conn = null;
				if(rs!=null)
					rs.close();
				if(pstmt!=null)
					pstmt.close();

			}
			catch(Exception e)
			{
				writeLog(filePtr,e,true);
				e.printStackTrace();

			}
		}
		return resultString;
	}//process()		
	
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		try
		{
			writeLog(filePtr,"P R O C E S S FX I N P R O C E S S :::.",true);
			writeLog(filePtr,"Generating  Receipt............... ",true);
			writeLog(filePtr,"xmlString :::."+xmlString,true);
			writeLog(filePtr,"xmlString :::."+xmlString2,true);

		}catch(Exception e){
		System.out.println(e.getMessage());}
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception :GenerateReceiptPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}		    
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
	    amtFlag = true;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();

		ArrayList receiptList = new ArrayList();
		ArrayList dtl2lList = new ArrayList();

		java.sql.Timestamp tranDate = new java.sql.Timestamp(System.currentTimeMillis());
		java.sql.Timestamp chgDate = new java.sql.Timestamp(System.currentTimeMillis());
		java.sql.Timestamp dueDate = null,refDate = null;
		String returnString = "",sql = "",sql2 = "",tranSer="";
		String tranId = "",rcpMode = "",custDet = "";
		String acctCodeAdv = "",cctrCodeAdv = "",finEntity = "",acctPrd = "",bankCode = "",bankName = "",acctCodeBal = "";
		String cctrCodeBal = "",acctCodeCf = "",cctrCodeCf = "",chgUser = "",chgTerm = "",custBankRef = "",acctCodeCfAr = "";
		String invoiceId = "",lineNo = "",chequeNo = "",schequeDate = "",schqAmount = "",refNo = "",cctrCodeCfAr = "";
		NodeList parentNodeList = null,parentNodeList2 = null;
		NodeList childNodeList = null,childNodeList2 = null;
		Node parentNode = null,parentNode2 = null;
		Node childNode = null,childNode2 = null;
		String childNodeName = "",childNodeName2 = "",sFilterChqAmt = "";
		double advAmount = 0,exchRate = 0,chqAmount = 0,filterChqAmt = 0;
		int parentNodeListLength = 0,parentNodeListLength2 = 0;
		int childNodeListLength = 0,childNodeListLength2 = 0,cntDet = 0;
		boolean flag = false;
		String searchKey = null;
		HashMap receiptMap = null;
		double adjAmt=0;
		String groupCode="";
		try
		{
			if(conn==null)
			{
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
			}

			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			
			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			//custCode = genericUtility.getColumnValue("cust_code",headerDom);
			sdueDate = genericUtility.getColumnValue("due_date",headerDom);
			
			System.out.println("siteCode in process()  "+siteCode);
			System.out.println("custCode in process()  "+custCode);
			writeLog(filePtr,"siteCode in process()  "+siteCode,true);
			//writeLog(filePtr,"custCode in process()  "+custCode,true);
			sFilterChqAmt = genericUtility.getColumnValue("cheque_amount",headerDom);
			//sFilterChqDate = genericUtility.getColumnValue("cheque_date",headerDom);
			if (sFilterChqAmt == null || sFilterChqAmt.trim().length() == 0)
			{
				sFilterChqAmt = "0.00";
			}
			filterChqAmt = Double.parseDouble(sFilterChqAmt);
			sdueDate = genericUtility.getValidDateString(sdueDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dueDate = java.sql.Timestamp.valueOf(sdueDate + " 00:00:00");
			
			System.out.println("dueDate in process()  "+dueDate);
			writeLog(filePtr,"dueDate in process()  "+dueDate,true);
			
			Object date = null;
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(tranDate.toString());
			tranDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
			System.out.println("TRAN DATE :::::-"+tranDate);
			writeLog(filePtr,"TRAN DATE :::::-"+tranDate,true);
			
			
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String trDate = sdf1.format(date).toString();
			
			System.out.println("TranDate ::::-"+trDate);
			writeLog(filePtr,"TranDate ::::-"+trDate,true);


			/*  try
			   {


				if(custCode != null)
				{
					sql = "SELECT CUST_NAME,ACCT_CODE__AR,CCTR_CODE__AR,CURR_CODE,RCP_MODE,ACCT_CODE__ADV,"
				 		+ "CCTR_CODE__ADV,BANK_NAME FROM CUSTOMER WHERE CUST_CODE = '"+custCode.trim()+"'";

					writeLog(filePtr,sql,true);
				 	pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						custName = rs.getString(1);
						acctCodeAr = rs.getString(2);
						cctrCodeAr = rs.getString(3);
						currCode = rs.getString(4);
						rcpMode = rs.getString(5);
						acctCodeAdv = rs.getString(6);
						cctrCodeAdv = rs.getString(7);
						custBankRef = rs.getString(8);
					}
					System.out.println("curr_code ::: "+currCode);
					if(rcpMode == null)
					{
						rcpMode = "";
					}
					receiptMap.put("cust_name",custName);
					receiptMap.put("acct_code__ar",acctCodeAr);
					receiptMap.put("cctr_code__ar",cctrCodeAr);
					receiptMap.put("curr_code",currCode);
					receiptMap.put("rcp_mode",rcpMode);
					receiptMap.put("acct_code__adv",acctCodeAdv);
					receiptMap.put("cctr_code__adv",cctrCodeAdv);
					receiptMap.put("cust_bank_ref",custBankRef);
					rs.close();
					pstmt.close();

				}
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			try
			{
				if(siteCode != null && currCode!=null)
				{
					sql = "SELECT C.STD_EXRT,S.FIN_ENTITY FROM CURRENCY C,SITE S "
						+ "WHERE C.CURR_CODE = '"+currCode.trim()+"' AND S.SITE_CODE = '"+siteCode.trim()+"'" ;
						writeLog(filePtr,sql,true);

					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						stdExchRate = rs.getDouble(1);
						finEntity = rs.getString(2);
					}
					System.out.println("STD_EXRT ::: "+stdExchRate);
					receiptMap.put("std_exrt",new Double(stdExchRate));

					System.out.println("FIN_ENTITY ::: "+finEntity);
					receiptMap.put("fin_entity",finEntity);
					rs.close();
					pstmt.close();

				}
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			if(rcpMode.equalsIgnoreCase("C"))
			{
				try
				{
					sql = "SELECT CASH_CODE FROM SITE WHERE SITE_CODE = '"+siteCode+"'";
					writeLog(filePtr,sql,true);
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						bankCode = rs.getString(1);
					}
					System.out.println("CASH_CODE ::: "+bankCode);
					receiptMap.put("bank_code",bankCode);
					rs.close();
					pstmt.close();

				}
				catch (SQLException ex)
				{
					writeLog(filePtr,ex,true);
					System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
					ex.printStackTrace();
					throw new ITMException(ex);
				}
				catch (Exception e)
				{
					writeLog(filePtr,e,true);
					System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
					e.printStackTrace();
					throw new ITMException(e);
				}
			}//if
			else if(!rcpMode.equalsIgnoreCase("C"))
			{
				try
				{
					sql = "SELECT BANK_CODE FROM SITE WHERE SITE_CODE = '"+siteCode+"'";
					writeLog(filePtr,sql,true);

					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						bankCode = rs.getString(1);
					}
					System.out.println("BANK_CODE ::: "+bankCode);
					receiptMap.put("bank_code",bankCode);
					rs.close();
					pstmt.close();

				}
				catch (SQLException ex)
				{
					writeLog(filePtr,ex,true);
					System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
					ex.printStackTrace();
					throw new ITMException(ex);
				}
				catch (Exception e)
				{
					writeLog(filePtr,e,true);
					System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
					e.printStackTrace();
					throw new ITMException(e);
				}
			}//if
			try
			{
				if(bankCode!=null)
				{
					sql = "SELECT BANK_NAME, ACCT_CODE__BAL, CCTR_CODE__BAL, ACCT_CODE__CF,"
						+ "CCTR_CODE__CF,ACCT_CODE__CF_AR, CCTR_CODE__CF_AR "
						+ "FROM BANK WHERE BANK_CODE = '"+bankCode+"'";
					writeLog(filePtr,sql,true);

					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						bankName = rs.getString(1);
						acctCodeBal = rs.getString(2);
						cctrCodeBal = rs.getString(3);
						acctCodeCf = rs.getString(4);
						cctrCodeCf = rs.getString(5);
						acctCodeCfAr = rs.getString(6);
						cctrCodeCfAr = rs.getString(7);
					}
					System.out.println("ACCT_CODE__BAL ::: "+acctCodeBal);
					receiptMap.put("acct_code__bal",acctCodeBal);
					receiptMap.put("cctr_code__bal",cctrCodeBal);

					if(acctCodeCfAr != null & acctCodeCfAr.trim().length() != 0)
					{
						acctCodeCf = acctCodeCfAr;
					}
					if(cctrCodeCfAr != null & cctrCodeCfAr.trim().length() != 0)
					{
						cctrCodeCf = cctrCodeCfAr;
					}
					receiptMap.put("acct_code__cf",acctCodeCf);
					receiptMap.put("cctr_code__cf",cctrCodeCf);
					rs.close();
					pstmt.close();

				}

			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}*/


			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();
			System.out.println("ParentNodeListLength....::-  "+parentNodeListLength);
			//System.out.println("(childNode.getFirstChild().getNodeValue()).trim()----"+(childNode.getFirstChild().getNodeValue()).trim());

			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();

				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					System.out.println("childNodeName---"+childNodeName); 
					//System.out.println("(childNode.getFirstChild().getNodeValue()).trim()----"+(childNode.getFirstChild().getNodeValue()).trim());
					if (childNodeName.equals("invoice_id"))
					{
						invoiceId = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						System.out.println("invoice_id:::::"+ invoiceId);
					}
					if (childNodeName.equals("cheque_no"))
					{
						//System.out.println("@@@@@@@@@@@@"+childNode.getFirstChild().getNodeValue()+"@@@@@@@@@");
						if(childNode!=null)
						{
							if(childNode.getFirstChild()!=null)
							{
								if(childNode.getFirstChild().getNodeValue()!=null)
								{
									chequeNo = checkNull(childNode.getFirstChild().getNodeValue());
								}
								else
								{
									chequeNo="";
								}
							}
							else
							{
								chequeNo="";
							}
						}
					
						
						if(chequeNo == null || chequeNo.equalsIgnoreCase("null"))
						{
							chequeNo = "";
						}
						
						System.out.println("cheque_no:::::"+ chequeNo);
					}
					if(childNodeName.equals("tran_ser"))
					{

						tranSer = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						System.out.println("tranSer:::::"+ tranSer);
					}
					if (childNodeName.equals("cheque_date"))
					{
						schequeDate = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						System.out.println("cheque_date:::::"+ schequeDate);
					}
					if (childNodeName.equals("chq_amount"))
					{
						schqAmount = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						if(schqAmount == null || schqAmount.equalsIgnoreCase("null"))
						{
							schqAmount = "";
						}
	 					chqAmount = Double.parseDouble(schqAmount);
						System.out.println("chq_amount :::::"+ chqAmount);
					}
					if (childNodeName.equals("cust_code"))
					{
						custCode = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						System.out.println("cust_code :::::"+ custCode);
					}
					if (childNodeName.equals("remarks"))//added by kunal on 19/10/12
					{
						remarks = checkNull(childNode.getFirstChild().getNodeValue()).trim();
						System.out.println("remarks :::::"+ remarks);
					}
					if (childNodeName.equals("adj_amt"))//added by kunal on 19/10/12
					{
						adjAmt = Double.parseDouble(checkNull(childNode.getFirstChild().getNodeValue()).trim());
						System.out.println("adjAmt :::::"+ adjAmt);
					}
				}//inner for
				sql = "SELECT GROUP_CODE FROM CUSTOMER WHERE CUST_CODE = ?";
				writeLog(filePtr,sql,true);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,custCode);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					groupCode = rs.getString(1);
				}
				System.out.println("Group Code ::: "+groupCode);
				rs.close();
				pstmt.close();
				
				
				//searchKey =  chequeNo + ":" + custCode;	//added by rajesh k to concate chequeNo and custCode
				searchKey=  chequeNo + ":" +		groupCode;//Added By Manoj dtd 26/11/2012 for Group Code
				writeLog(filePtr,"chequeNo::::: "+chequeNo,true);
				writeLog(filePtr,"custCode::::: "+custCode,true);
				writeLog(filePtr,"searchKey::::: "+searchKey,true);
			//	if(tranSer.equalsIgnoreCase("S-INV"))
				//{
				java.sql.Timestamp chequeDate = null;
				//schequeDate = schequeDate.substring(0,8);
				writeLog(filePtr,"schequeDate::::: "+schequeDate,true);
				if(schequeDate.indexOf("-")!=-1)
				{
					chequeDate = java.sql.Timestamp.valueOf(schequeDate+" 00:00:00");
				}
				else
				{
					schequeDate = genericUtility.getValidDateString(schequeDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
					writeLog(filePtr,"genericUtility.getValidDateString Return "+schequeDate,true);
					chequeDate = java.sql.Timestamp.valueOf(schequeDate+" 00:00:00");
				}
				receiptMap = new HashMap();
				receiptMap.put("chg_user",chgUser);
				receiptMap.put("chg_term",chgTerm);
				receiptMap.put("chg_date",chgDate);
				receiptMap.put("site_code",siteCode);
				receiptMap.put("due_date",dueDate);
				receiptMap.put("tran_date",tranDate);
				receiptMap.put("search_key",searchKey);//added by rajesh k to put serachkey in map
				receiptMap.put("ref_no",chequeNo);
				//receiptMap.put("cust_code",custCode);// added by rajesh k to put custcode in map
				receiptMap.put("cust_code",groupCode);//Added By Manoj dtd 26/11/2012 for Group Code
				receiptMap.put("ref_date",chequeDate);
				receiptMap.put("remarks",remarks); //added by Kunal on 19/10/12
				receiptMap.put("chq_amt",new Double(chqAmount));

				int ele = getListElement(receiptList, searchKey);
				//int ele = getListElement(receiptList, chequeNo);
				System.out.println("ele::::::::::"+ele);
				writeLog(filePtr,"ele::::::::::"+ele,true);

				ReceiptElements receiptElements;
				if (ele == -1)
				{
					receiptElements = new ReceiptElements();
					receiptElements.setSearchKey(searchKey);
					receiptElements.setChequeNo(chequeNo);
					//receiptElements.setCustCode(custCode);
					receiptElements.setCustCode(groupCode);//Added By Manoj dtd 26/11/2012 for Group Code
					//*********add on 25102006 by taranisen total cheque amt should be equals to invoice amt
					receiptElements.setChequeAmt(chqAmount);

					receiptList.add(receiptElements);
					//ele = receiptList.size() -1;
					ele = getListElement(receiptList, searchKey);
					System.out.println("The size of the element is "+ele);
					writeLog(filePtr,"The size of the element is "+ele,true);

				}
				else
				{
					receiptElements = (ReceiptElements)receiptList.get(ele);
				}


				ReceiptDetail receiptDetail = invoiceDetail(invoiceId,tranSer,adjAmt,conn);
				receiptElements.setReceiptMap(receiptMap);
				receiptElements.setInvoiceList(receiptDetail);
				receiptList.set(ele,receiptElements);
            }//Outer For
            
			System.out.println("@@@@ The size of receiptList is @@@@ "+receiptList.size());
			writeLog(filePtr,"@@@@ The ReceiptGenerated is @@@@ "+receiptList.size(),true);

		//	*****************************added on 25102006
			for (int Ctr = 0; Ctr < receiptList.size() ; Ctr++)
			{
				ReceiptElements receiptElements = (ReceiptElements)receiptList.get(Ctr);
				double chequeAmt = 0.0;
				chequeAmt = receiptElements.getChequeAmt();
				writeLog(filePtr,"Cheque No["+receiptElements.getChequeNo()+"]    TotalChequeAmt ["+chequeAmt+"]",true);
				invoiceList = receiptElements.getInvoiceList();
				custCode = receiptElements.getCustCode();//added by rajesh k to add custcode to receipt element
				chequeNo = receiptElements.getChequeNo();//added by rajesh k to add chequeno to receipt element
				double rcpAmount =0.0;
				int invSize = 0;
				invSize = invoiceList.size();
				writeLog(filePtr,"@@@@ The TotalInvoicewrrrrrrrrrrrrrrr  is @@@@ ["+invoiceList.size()+"]",true);
				writeLog(filePtr,"!!!!!!!! invSize " +invSize ,true);
				for (int Ctr1 = 0; Ctr1 < invSize ; Ctr1++)
				{
					ReceiptDetail receiptDetail = (ReceiptDetail)invoiceList.get(Ctr1);
					rcpAmount = rcpAmount +receiptDetail.getRcpAmt();
					rcpAmount = getRequiredDecimal(rcpAmount,3); // Added by rajesh k to convert number format
					writeLog(filePtr,"rcpAmount**********[ "+rcpAmount+"]",true);
				}
				writeLog(filePtr,"rcpAmount:-[ "+rcpAmount+"]",true);
				writeLog(filePtr,"chequeAmt:-[ "+chequeAmt+"]",true);
				
				//if(chequeAmt != rcpAmount)	//	*********
				
				if(chequeAmt != rcpAmount && chequeAmt != 0 && rcpAmount != 0)	//	*********
				{
					amtFlag = false;
					writeLog(filePtr,"MITCH MATCH AMOUNT Cheque No["+receiptElements.getChequeNo()+"]    TotalChequeAmt ["+chequeAmt+"]",true);
					writeLog(filePtr,"RcpAmount:-"+rcpAmount,true);
				}
				if (filterChqAmt != chequeAmt && chequeAmt != 0)
				{
					amtFlag = false;
					writeLog(filePtr,"MITCH MATCH AMOUNT Cheque No["+receiptElements.getChequeNo()+"]    TotalChequeAmt ["+chequeAmt+"]",true);
					writeLog(filePtr,"RcpAmount:-"+rcpAmount,true);
				}

				writeLog(filePtr,"TotalReceiptAmount:::-["+rcpAmount+"]",true);

			}
			//******************************
			writeLog(filePtr,"amtFlag:::-["+amtFlag+"]",true);



			if(amtFlag)
			{
				writeLog(filePtr,"[===>R E C E I P T G E N E R A T I N G I N P R O G R E S S<=== ]",true);
				for (int Ctr = 0; Ctr < receiptList.size() ; Ctr++)
				{
					ReceiptElements receiptElements = (ReceiptElements)receiptList.get(Ctr);
					double amountcheque = receiptElements.getChequeAmt();
					receiptMap = (HashMap) receiptElements.getReceiptMap();
					custCode = receiptElements.getCustCode();
					System.out.println("1187---custCode----"+custCode);
					receiptMap = CustDetail(custCode, receiptMap,siteCode);//added by rajeshk  to call method CustDetail
				    //tranId = generateTranTd("w_receipt_adv",trDate,siteCode);
					tranId = generateTranTd("w_receivables_jv",trDate,siteCode);
					System.out.println("TranId :::::::::::::::::;  "+tranId);
					writeLog(filePtr,"TranId ["+tranId+"]",true);
					receiptMap.put("tran_id",tranId);
					try
					{
						cntHdr = 0;
						writeLog(filePtr,"AMOUNTCHEQUE GOING TO HEADER:::["+amountcheque+"]",true);

						cntHdr = insertReceiptHdr(receiptMap,amountcheque,conn);
						writeLog(filePtr,"Cheque No["+receiptMap.get("ref_no")+"]",true);
						if(cntHdr == 0)
						{
							conn.rollback();
							returnString= itmDBAccessEJB.getErrorString("","VTRCPGN0","","",conn);
							return returnString;
						}
						else
						{
							writeLog(filePtr,"Record Success fully inserted in header["+tranId+"]",true);
							ArrayList invoiceList = receiptElements.getInvoiceList();
							writeLog(filePtr,"No Of Invoice for receipt ["+tranId+"]"+invoiceList.size(),true);
							insertReceiptDtl(tranId,invoiceList,conn);
						}
					}
					catch (Exception e)
					{
						writeLog(filePtr,e,true);
						System.out.println("Exception ::" + e.getMessage() + ":");
						e.printStackTrace();
						throw new ITMException(e);
					}
					try
					{
						int cnt = updateReceipt(netAmtHdr,billAmt,billDiscAmt,tranId,conn);
						writeLog(filePtr,"[UPDATE AMT]netAmtHdr["+netAmtHdr+"]billAmt["+billAmt+"]billDiscAmt["+billDiscAmt+"]",true);
						
						if(cnt > 0)
						{
							writeLog(filePtr,"Update Successfully in header["+tranId+"]",true);
							netAmtHdr = 0;
							billAmt = 0;
							billDiscAmt = 0;
						}
						if(cnt == 0)
						{
							conn.rollback();
							returnString= itmDBAccessEJB.getErrorString("","VTRCPGN0","","",conn);
							return returnString;
						}
					}
					catch (Exception e)
					{
						writeLog(filePtr,e,true);
						System.out.println("Exception ::" + e.getMessage() + ":");
						e.printStackTrace();
						throw new ITMException(e);
					}
					conn.commit();
					returnString= itmDBAccessEJB.getErrorString("","VTSUCC","","",conn); // 19/07/12 MANOHARAN
					System.out.println("Transaction commited...............");
			     }//for
		    }
			else
			{
				writeLog(filePtr,"AMTMITCHMATCH........",true);
				returnString= itmDBAccessEJB.getErrorString("","AMTMITCHMATCH","","",conn);
				return returnString;
			}


		/*	if(receiptList.size()>0)
			{
				writeLog(filePtr,"There is a cheque.........",true);
				writeLog(filePtr,"LaseTranId:::[[["+tranId+"]]]",true);
				insertReceiptDtlDtl(tranId,dtl2lList, conn);
				int cnt = updateReceipt(advAdjAmtHdr,diffAmtExcHdr,tranId ,conn);
				writeLog(filePtr,"[UPDATE AMT]advAdjAmtHdr["+advAdjAmtHdr+"]diffAmtExcHdr["+diffAmtExcHdr+"]",true);
				if(cnt>=1)
				{
					writeLog(filePtr,"Receipt update for LaseTranId:::["+tranId+"]",true);
				}
			}
			else
			{
				writeLog(filePtr,"Only transer not [s-inv] Selected",true);
			}*/

		/*	try
			{
				String XMLData = serializeDom(detailDom);
				sendMail(XMLData,siteCode,custCode,dueDate,parentNodeListLength,conn);
				returnString= itmDBAccessEJB.getErrorString("","VTRCPGN1","","",conn);
			}
			catch (Exception e)
			{
				writeException(e);
				System.out.println("Exception :::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			try
			{
				String XMLData = serializeDom(detailDom);
				sendMail(XMLData,siteCode,custCode,dueDate,parentNodeListLength,conn);
				returnString= itmDBAccessEJB.getErrorString("","VTRCPGN1","","",conn);
			}
			catch (Exception e)
			{
				//writeException(e);
				System.out.println("Exception :::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}*/


		}//outer try
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::GenerateReceiptPrcEJB ::process():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			writeLog(filePtr,"Finally Closing Connection....",true);
			System.out.println("Closing Connection2....");
			try
			{
				//fw.flush();
				//fw.close();
				conn.close();
				conn = null;
			}
			catch(Exception se){}
		}//
		writeLog(filePtr,"Finally Return String"+returnString,true);
		return returnString;

	}//process()
	// for check null
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	
	
	// added this method by rajesh k
    private HashMap CustDetail(String custCode, HashMap rcpMap,String siteCode )throws ITMException
    {
		writeLog(filePtr," coming siteCode Return String"+siteCode,true);

		String custDetail = "";
		String sql = "";
		//String siteCode = "";
		String custName = "",acctCodeAr = "",cctrCodeAr = "",currCode = "",rcpMode = "";
		String acctCodeAdv = "",cctrCodeAdv = "",finEntity = "",bankCode = "",bankName = "",acctCodeBal = "";
		String cctrCodeBal = "",acctCodeCf = "",cctrCodeCf = "",custBankRef = "",acctCodeCfAr = "";
		String lineNo = "",cctrCodeCfAr = "";
		boolean flag = false;
		try
		{
			if(custCode != null)
			{
			sql = "SELECT CUST_NAME,ACCT_CODE__AR,CCTR_CODE__AR,CURR_CODE,RCP_MODE,ACCT_CODE__ADV,"
			    + "CCTR_CODE__ADV,BANK_NAME FROM CUSTOMER WHERE CUST_CODE = '"+custCode.trim()+"'";
			
			writeLog(filePtr,sql,true);
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				custName = rs.getString(1);
				acctCodeAr = rs.getString(2);
				cctrCodeAr = rs.getString(3);
				currCode = rs.getString(4);
				rcpMode = rs.getString(5);
				acctCodeAdv = rs.getString(6);
				cctrCodeAdv = rs.getString(7);
				custBankRef = rs.getString(8);
			}
			System.out.println("curr_code ::: "+currCode);
			if(rcpMode == null)
			{
				rcpMode = "";
			}
			rcpMap.put("cust_name",custName);
			rcpMap.put("acct_code__ar",acctCodeAr);
			rcpMap.put("cctr_code__ar",cctrCodeAr);
			rcpMap.put("curr_code",currCode);
			rcpMap.put("rcp_mode",rcpMode);
			rcpMap.put("acct_code__adv",acctCodeAdv);
			rcpMap.put("cctr_code__adv",cctrCodeAdv);
			rcpMap.put("cust_bank_ref",custBankRef);
			rs.close();
			pstmt.close();
			}
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		try
		{
			if(siteCode != null && currCode!=null)
			{
				
				sql = "SELECT C.STD_EXRT,S.FIN_ENTITY FROM CURRENCY C,SITE S "
					+ "WHERE C.CURR_CODE = '"+currCode.trim()+"' AND S.SITE_CODE = '"+siteCode.trim()+"'" ;
				writeLog(filePtr,sql,true);
		
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					stdExchRate = rs.getDouble(1);
					finEntity = rs.getString(2);
				}
				System.out.println("STD_EXRT ::: "+stdExchRate);
				rcpMap.put("std_exrt",new Double(stdExchRate));
		
				System.out.println("FIN_ENTITY ::: "+finEntity);
				rcpMap.put("fin_entity",finEntity);
				rs.close();
				pstmt.close();
			}
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		if(rcpMode.equalsIgnoreCase("C"))
		{
			try
			{
				sql = "SELECT CASH_CODE FROM SITE WHERE SITE_CODE = '"+siteCode+"'";
				writeLog(filePtr,sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					bankCode = rs.getString(1);
				}
				System.out.println("CASH_CODE ::: "+bankCode);
				rcpMap.put("bank_code",bankCode);
				rs.close();
				pstmt.close();
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
		 }//if
		else if(!rcpMode.equalsIgnoreCase("C"))
		{
			try
			{
				sql = "SELECT BANK_CODE FROM SITE WHERE SITE_CODE = '"+siteCode+"'";
				writeLog(filePtr,sql,true);

				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					bankCode = rs.getString(1);
				}
				System.out.println("BANK_CODE ::: "+bankCode);
				rcpMap.put("bank_code",bankCode);
				rs.close();
				pstmt.close();

			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
		}//elseif
		try
		{
			if(bankCode!=null)
			{
				sql = "SELECT BANK_NAME, ACCT_CODE__BAL, CCTR_CODE__BAL, ACCT_CODE__CF,"
				+ "CCTR_CODE__CF,ACCT_CODE__CF_AR, CCTR_CODE__CF_AR "
				+ "FROM BANK WHERE BANK_CODE = '"+bankCode+"'";
				writeLog(filePtr,sql,true);
		
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					bankName = rs.getString(1);
					acctCodeBal = rs.getString(2);
					cctrCodeBal = rs.getString(3);
					acctCodeCf = rs.getString(4);
					cctrCodeCf = rs.getString(5);
					acctCodeCfAr = rs.getString(6);
					cctrCodeCfAr = rs.getString(7);
				}
				System.out.println("ACCT_CODE__BAL ::: "+acctCodeBal);
		
				rcpMap.put("acct_code__bal",acctCodeBal);
				rcpMap.put("cctr_code__bal",cctrCodeBal);
		
				if(acctCodeCfAr != null & acctCodeCfAr.trim().length() != 0)
				{
					acctCodeCf = acctCodeCfAr;
				}
				if(cctrCodeCfAr != null & cctrCodeCfAr.trim().length() != 0)
				{
					cctrCodeCf = cctrCodeCfAr;
				}
				rcpMap.put("acct_code__cf",acctCodeCf);
				rcpMap.put("cctr_code__cf",cctrCodeCf);
				rs.close();
				pstmt.close();
			}
		
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::process():" +sql+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return rcpMap;
	}// END OF HASH MAP CustDetail


	private int getListElement(ArrayList receiptList,String searchKey)
	{
		int ctr = 0;
		int retVal = -1;
		ReceiptElements receiptElements;
		for (ctr = 0;ctr < receiptList.size();ctr++)
		{
			receiptElements = (ReceiptElements)receiptList.get(ctr);
			if (receiptElements.getSearchKey().trim().equals(searchKey.trim()))
			{
				retVal = ctr;
				break;
			}
		}
		return retVal;
	}


   /* private int getListElement(ArrayList receiptList,String chqNo)
	{
		int ctr = 0;
		int retVal = -1;
		ReceiptElements receiptElements;
		for (ctr = 0;ctr < receiptList.size();ctr++)
		{
			receiptElements = (ReceiptElements)receiptList.get(ctr);
			if (receiptElements.getChequeNo().trim().equals(chqNo.trim()))
			{
				retVal = ctr;
				break;
			}
		}
		return retVal;
	}*/




	private int insertReceiptHdr(HashMap insertMap ,double chequeAmtToHdr ,Connection conn) throws ITMException
	{
		String sql = "";
		PreparedStatement pstmt = null;
		java.sql.Timestamp tranDate = null,dueDate = null,chgDate = null,refDate = null;
		String tranId = "",siteCode = "",custCode = "",custName = "",acctCodeAr = "",cctrCodeAr = "",currCode = "",rcpMode = "";
		String acctCodeAdv = "",cctrCodeAdv = "",finEntity = "",acctPrd = "",bankCode = "",bankName = "",acctCodeBal = "";
		String cctrCodeBal = "",acctCodeCf = "",cctrCodeCf = "",chgUser = "",chgTerm = "",custBankRef = "",refNo = "";
		//String remarks = "AUTO-RECEIPT GENERATION";
		String remarks = "";
		double advAmt = 0,exchRate = 0,chqAmt = 0;
		int count = 0;
		double initialValue=0.0;
		try
		{
			System.out.println("The values in HashMap for RECEIPT are : "+insertMap.toString());
			tranDate = java.sql.Timestamp.valueOf(insertMap.get("tran_date").toString());
			chgDate = java.sql.Timestamp.valueOf(insertMap.get("chg_date").toString());
			dueDate = java.sql.Timestamp.valueOf(insertMap.get("due_date").toString());
			refDate = java.sql.Timestamp.valueOf(insertMap.get("ref_date").toString());
			tranId 	  	= (String)insertMap.get("tran_id");
			refNo 	  	= (String)insertMap.get("ref_no");
			siteCode  	= (String)insertMap.get("site_code");
			custCode  	= (String)insertMap.get("cust_code");
			acctCodeAr 	= (String)insertMap.get("acct_code__ar");
			cctrCodeAr 	= (String)insertMap.get("cctr_code__ar");
			currCode  	= (String)insertMap.get("curr_code");
			rcpMode  	= (String)insertMap.get("rcp_mode");
			acctCodeAdv	= (String)insertMap.get("acct_code__adv");
			cctrCodeAdv	= (String)insertMap.get("cctr_code__adv");
			finEntity	= (String)insertMap.get("fin_entity");
			acctPrd		= (String)insertMap.get("acct_prd");
			bankCode	= (String)insertMap.get("bank_code");
			bankName	= (String)insertMap.get("bank_name");
			acctCodeBal	= (String)insertMap.get("acct_code__bal");
			cctrCodeBal	= (String)insertMap.get("cctr_code__bal");
			acctCodeCf	= (String)insertMap.get("acct_code__cf");
			cctrCodeCf	= (String)insertMap.get("cctr_code__cf");
			chgUser		= (String)insertMap.get("chg_user");
			chgTerm		= (String)insertMap.get("chg_term");
			custBankRef = (String)insertMap.get("cust_bank_ref");
			exchRate	= ((Double)insertMap.get("std_exrt")).doubleValue();
			remarks		= (String)insertMap.get("remarks");//added by Kunal
			System.out.println("remarks:::"+remarks);
			chqAmt		= chequeAmtToHdr;//((Double)insertMap.get("chq_amt")).doubleValue();
			
			System.out.println("The TranId while inserting the record :::::::: "+tranId);
			try
			{
				sql = "INSERT INTO RECEIPT ( TRAN_ID,TRAN_DATE,CUST_CODE,RCP_MODE,BANK_CODE,REF_NO,REF_DATE,"
					+ "EFF_DATE,SITE_CODE,CHG_DATE,CHG_USER,CHG_TERM,ACCT_CODE__AR,CCTR_CODE__AR,"
					+ "CURR_CODE,ACCT_CODE__ADV,CCTR_CODE__ADV,CUST_BANK_REF,EXCH_RATE,EXCH_RATE_SPOT,"
					+ "FIN_ENTITY,ACCT_CODE__BAL,CCTR_CODE__BAL,ACCT_CODE__CF,CCTR_CODE__CF,REMARKS,CHQ_AMT, CONFIRMED, OTH_AMT,ADV_AMT,"
					+" ADVADJ_AMT,NET_AMT,NET_AMT__BC,TRAN_TYPE   ) "
					+ "VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'N',?,?,?,?,? ,'J')";

				System.out.println("Insert SQL ::- "+sql);
				writeLog(filePtr,"Insert SQL ::- "+sql,true);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,tranId);
				pstmt.setTimestamp(2,tranDate);
				pstmt.setString(3,custCode);
				pstmt.setString(4,rcpMode);
				pstmt.setString(5,bankCode);
				pstmt.setString(6,refNo);
				pstmt.setTimestamp(7,refDate);
				pstmt.setTimestamp(8,tranDate);
				pstmt.setString(9,siteCode);
				pstmt.setTimestamp(10,chgDate);
				pstmt.setString(11,chgUser);
				pstmt.setString(12,chgTerm);
				pstmt.setString(13,acctCodeAr);
				pstmt.setString(14,cctrCodeAr);
				pstmt.setString(15,currCode);
				pstmt.setString(16,acctCodeAdv);
				pstmt.setString(17,cctrCodeAdv);
				pstmt.setString(18,custBankRef);
				pstmt.setDouble(19,exchRate);
				pstmt.setDouble(20,exchRate);
				pstmt.setString(21,finEntity);
				pstmt.setString(22,acctCodeBal);
				pstmt.setString(23,cctrCodeBal);
				pstmt.setString(24,acctCodeCf);
				pstmt.setString(25,cctrCodeCf);
				pstmt.setString(26,remarks);
				pstmt.setDouble(27,chqAmt);
				pstmt.setDouble(28,initialValue);
				pstmt.setDouble(29,initialValue);
				pstmt.setDouble(30,initialValue);
				pstmt.setDouble(31,initialValue);
				pstmt.setDouble(32,initialValue);

				count = pstmt.executeUpdate();
				System.out.println("No of records inserted successfully in RECEIPT are : "+count);

				pstmt.close();
				pstmt = null;
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return (count);
	}//insertReceiptHdr()

	//////////////

	// added method by rajesh k to take searchkey,transer
   /* private ReceiptDetail invoiceDetail(String searchKey,String tranSer,Connection conn) throws ITMException
	{
		FinCommon finCommon = new FinCommon();
		ReceiptDetail receiptDetail = new ReceiptDetail();
		java.sql.Timestamp refDate = null,dueDate = null;
		Statement stmt = null,stmt2 = null;
		ResultSet rs = null,rs2 = null;
		String sql = "",sql2 = "",lineNo = "",currCode = "",acctCode = "",cctrCode = "",billDisc = "",bdFluctuation = "";
		String custCode ="";
		double exchRateRcv = 0,discount = 0,taxAmt = 0,totAmt = 0,adjAmt = 0,badDebtAmt = 0;
		double exprtExchRate = 0,rcpAmt = 0,exchRate = 0,amtDiffExchRate = 0;
		boolean flag = false;
		int count = 0;
		try
		{
			//sql2 = "SELECT LINE_NO FROM INVDET WHERE INVOICE_ID = '"+invoiceId+"'";
			//stmt2 = conn.createStatement();
			//rs2 = stmt2.executeQuery(sql2);
			//System.out.println("SQL2  :::  "+sql2);
			//if(rs2.next())
			//{
			//	int line_no = rs2.getInt(1);
			//	System.out.println("Line No : "+line_no);
			//
			//	lineNo = Integer.toString(line_no);
			//	//lineNo = (("    "+lineNo).substring(("    "+lineNo).length()-3));
				try
				{

					searchKey = searchKey.substring(searchKey.length()-10);

					sql = "SELECT REF_DATE, CURR_CODE, EXCH_RATE, ACCT_CODE,CCTR_CODE,"
						+ "DUE_DATE, CUST_CODE, DISCOUNT, TAX_AMT, TOT_AMT, ADJ_AMT,"
						+ "CASE WHEN BAD_DEBT_AMT IS NULL THEN 0 ELSE BAD_DEBT_AMT END,LINE_NO__REF  "
						+ "FROM RECEIVABLES "
						+ "WHERE TRAN_SER = '"+tranSer+"'"
						+ "AND REF_NO = '"+searchKey+"' ";
						//+ "AND LINE_NO__REF = '"+lineNo+"'";

					System.out.println("Receivables SQL : "+sql);
					writeLog(filePtr,"Receivables SQL : "+sql,true);
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sql);
					if(rs.next())
					{
						flag = true;
						refDate = rs.getTimestamp(1);
						currCode = rs.getString(2);
						writeLog(filePtr,"SETTING CURRCODE IN BEAN FOR DETAIL:::"+currCode,true);
						exchRateRcv = rs.getDouble(3);
						acctCode = rs.getString(4);
						cctrCode = rs.getString(5);
						dueDate = rs.getTimestamp(6);
						custCode = rs.getString(7);
						discount = rs.getDouble(8);
						taxAmt = rs.getDouble(9);
						totAmt = rs.getDouble(10);
						adjAmt = rs.getDouble(11);
						badDebtAmt = rs.getDouble(12);
						lineNo = rs.getString(13);

					}
					System.out.println("REF_DATE :: "+refDate);

					receiptDetail.setInvoiceId(invoiceId);
					receiptDetail.setLineNo(lineNo);
					receiptDetail.setRefDate(refDate);
					receiptDetail.setCurrCode(currCode);


					receiptDetail.setExchRateRcv(exchRateRcv);
					receiptDetail.setAcctCode(acctCode);
					receiptDetail.setCctrCode(cctrCode);
					receiptDetail.setDueDate(dueDate);
					receiptDetail.setCustCode(custCode);
					receiptDetail.setDiscount(discount);
					receiptDetail.setTaxAmt(taxAmt);
					receiptDetail.setTotAmt(totAmt);
					receiptDetail.setAdjAmt(adjAmt);
					receiptDetail.setBadDebtAmt(badDebtAmt);
					receiptDetail.setRefSer(tranSer);

					stmt.close();
					stmt = null;
				}
				catch (SQLException ex)
				{
					writeLog(filePtr,ex,true);
					System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
					ex.printStackTrace();
					throw new ITMException(ex);
				}
				catch (Exception e)
				{
					writeLog(filePtr,e,true);
					System.out.println("Exception ::" + e.getMessage() + ":");
					e.printStackTrace();
					throw new ITMException(e);
				}
				try
				{
					sql = "SELECT BILL_DISC FROM RECEIVABLES WHERE TRAN_SER = '"+tranSer+"' AND REF_NO = '"+searchKey+"'";
					writeLog(filePtr,sql,true);

					stmt = conn.createStatement();
					rs = stmt.executeQuery(sql);
					if(rs.next())
					{
						billDisc = rs.getString(1);
					}
					if(billDisc == null || billDisc.trim().length() == 0)
					{
						billDisc = "N";
					}
					receiptDetail.setBillDisc(billDisc);
					stmt.close();
					stmt = null;
				}
				catch (SQLException ex)
				{
					writeLog(filePtr,ex,true);
					System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
					ex.printStackTrace();
					throw new ITMException(ex);
				}
				catch (Exception e)
				{
					writeLog(filePtr,e,true);
					System.out.println("Exception ::" + e.getMessage() + ":");
					e.printStackTrace();
					throw new ITMException(e);
				}
				if(billDisc.equalsIgnoreCase("Y"))
				{
					try
					{
						sql = "SELECT EXPORT_FUND.EXCH_RATE FROM EXPORT_FUND, EXPORT_FUNDET "
							+ "WHERE ( EXPORT_FUND.TRAN_ID = EXPORT_FUNDET.TRAN_ID ) AND "
							+ "( EXPORT_FUND.CONFIRMED = 'Y' ) AND "
							+ "( ( EXPORT_FUNDET.REF_SER = '"+tranSer+"' ) AND "
							+ "( EXPORT_FUNDET.REF_NO = '"+searchKey+"') ) ";
							writeLog(filePtr,sql,true);

						stmt = conn.createStatement();
						rs = stmt.executeQuery(sql);
						if(rs.next())
						{
							exprtExchRate = rs.getDouble(1);
						}
					}
					catch (SQLException ex)
					{
						writeLog(filePtr,ex,true);
						System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
						ex.printStackTrace();
						throw new ITMException(ex);
					}
					catch (Exception e)
					{
						writeLog(filePtr,e,true);
						System.out.println("Exception ::" + e.getMessage() + ":");
						e.printStackTrace();
						throw new ITMException(e);
					}
				}//if
				rcpAmt = (totAmt - adjAmt);

				bdFluctuation = finCommon.getFinparams("999999","BD_FLUCTUATION_CF",conn);
				writeLog(filePtr,"bdFluctuation:::"+bdFluctuation,true);

				if(bdFluctuation.equals("NULLFOUND"))
				{
					 bdFluctuation = "Y";
				}
				exchRate = stdExchRate;
				if(billDisc.equals("Y") &&  bdFluctuation.equals("Y"))
				{
					exchRate = exprtExchRate;
					amtDiffExchRate = ((rcpAmt * exchRateRcv) - (rcpAmt * exprtExchRate));
				}
				else
				{
					amtDiffExchRate = ((rcpAmt * exchRateRcv) - (rcpAmt * exchRate));
				}
				receiptDetail.setRcpAmt(rcpAmt);
				receiptDetail.setExchRate(exchRate);
				receiptDetail.setAmtDiffExchRate(amtDiffExchRate);
			//}//
			//stmt2.close();
			//stmt2 = null;
		}//try
		//catch (SQLException ex)
		//{
		//	////writeException(ex);
		//	System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
		//	ex.printStackTrace();
		//	throw new ITMException(ex);
		//}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return receiptDetail;
	}//invoiceDetail()*/




	private ReceiptDetail invoiceDetail(String invoiceId,String tranSer,double adjustAmt,Connection conn) throws ITMException
	{
		FinCommon finCommon = new FinCommon();
		ReceiptDetail receiptDetail = new ReceiptDetail();
		java.sql.Timestamp refDate = null,dueDate = null;
		Statement stmt = null,stmt2 = null;
		ResultSet rs = null,rs2 = null;
		String sql = "",sql2 = "",lineNo = "",currCode = "",acctCode = "",cctrCode = "",billDisc = "",bdFluctuation = "";
		double exchRateRcv = 0,discount = 0,taxAmt = 0,totAmt = 0,adjAmt = 0,badDebtAmt = 0;
		double exprtExchRate = 0,rcpAmt = 0,exchRate = 0,amtDiffExchRate = 0;
		boolean flag = false;
		int count = 0;
		try
		{
			//sql2 = "SELECT LINE_NO FROM INVDET WHERE INVOICE_ID = '"+invoiceId+"'";
			//stmt2 = conn.createStatement();
			//rs2 = stmt2.executeQuery(sql2);
			//System.out.println("SQL2  :::  "+sql2);
			//if(rs2.next())
			//{
			//	int line_no = rs2.getInt(1);
			//	System.out.println("Line No : "+line_no);
			//
			//	lineNo = Integer.toString(line_no);
			//	//lineNo = (("    "+lineNo).substring(("    "+lineNo).length()-3));
			try
			{
				sql = "SELECT REF_DATE, CURR_CODE, EXCH_RATE, ACCT_CODE,CCTR_CODE,"
					+ "DUE_DATE, CUST_CODE, DISCOUNT, TAX_AMT, TOT_AMT, ADJ_AMT,"
					+ "CASE WHEN BAD_DEBT_AMT IS NULL THEN 0 ELSE BAD_DEBT_AMT END,LINE_NO__REF  "
					+ "FROM RECEIVABLES "
					+ "WHERE TRAN_SER = '"+tranSer+"'"
					+ "AND REF_NO = '"+invoiceId+"' ";
					//+ "AND LINE_NO__REF = '"+lineNo+"'";

				System.out.println("Receivables SQL : "+sql);
				writeLog(filePtr,"Receivables SQL : "+sql,true);
				stmt = conn.createStatement();
				rs = stmt.executeQuery(sql);
				if(rs.next())
				{
					flag = true;
					refDate = rs.getTimestamp(1);
					currCode = rs.getString(2);
					writeLog(filePtr,"SETTING CURRCODE IN BEAN FOR DETAIL:::"+currCode,true);
					exchRateRcv = rs.getDouble(3);
					acctCode = rs.getString(4);
					cctrCode = rs.getString(5);
					dueDate = rs.getTimestamp(6);
					custCode = rs.getString(7);
					discount = rs.getDouble(8);
					taxAmt = rs.getDouble(9);
					totAmt = rs.getDouble(10);
					adjAmt = rs.getDouble(11);
					badDebtAmt = rs.getDouble(12);
					lineNo = rs.getString(13);
				}
					System.out.println("REF_DATE :: "+refDate);

					receiptDetail.setInvoiceId(invoiceId);
					receiptDetail.setLineNo(lineNo);
					receiptDetail.setRefDate(refDate);
					receiptDetail.setCurrCode(currCode);
					receiptDetail.setExchRateRcv(exchRateRcv);
					receiptDetail.setAcctCode(acctCode);
					receiptDetail.setCctrCode(cctrCode);
					receiptDetail.setDueDate(dueDate);
					receiptDetail.setCustCode(custCode);
					receiptDetail.setDiscount(discount);
					receiptDetail.setTaxAmt(taxAmt);
					receiptDetail.setTotAmt(totAmt);
					receiptDetail.setAdjAmt(adjAmt);
					receiptDetail.setBadDebtAmt(badDebtAmt);
					receiptDetail.setRefSer(tranSer);

					stmt.close();
					stmt = null;
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			try
			{
				sql = "SELECT BILL_DISC FROM RECEIVABLES WHERE TRAN_SER = '"+tranSer+"' AND REF_NO = '"+invoiceId+"'";
				writeLog(filePtr,sql,true);
				
				stmt = conn.createStatement();
				rs = stmt.executeQuery(sql);
				if(rs.next())
				{
					billDisc = rs.getString(1);
				}
				if(billDisc == null || billDisc.trim().length() == 0)
				{
					billDisc = "N";
				}
				receiptDetail.setBillDisc(billDisc);
				stmt.close();
				stmt = null;
			}
			catch (SQLException ex)
			{
				writeLog(filePtr,ex,true);
				System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			if(billDisc.equalsIgnoreCase("Y"))
			{
				try
				{
					sql = "SELECT EXPORT_FUND.EXCH_RATE FROM EXPORT_FUND, EXPORT_FUNDET "
						+ "WHERE ( EXPORT_FUND.TRAN_ID = EXPORT_FUNDET.TRAN_ID ) AND "
						+ "( EXPORT_FUND.CONFIRMED = 'Y' ) AND "
						+ "( ( EXPORT_FUNDET.REF_SER = '"+tranSer+"' ) AND "
						+ "( EXPORT_FUNDET.REF_NO = '"+invoiceId+"') ) ";
					writeLog(filePtr,sql,true);
					
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sql);
					if(rs.next())
					{
						exprtExchRate = rs.getDouble(1);
					}
				}
				catch (SQLException ex)
				{
					writeLog(filePtr,ex,true);
					System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
					ex.printStackTrace();
					throw new ITMException(ex);
				}
				catch (Exception e)
				{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
				}
			}//if
			//Manoj dtd 26/11/2012 to adjust Partial Amount
			if(adjustAmt==0)
				rcpAmt = (totAmt - adjAmt);
			else
				rcpAmt=adjustAmt;
			System.out.println("adjustAmt----"+adjustAmt);
			System.out.println("rcpAmt----"+rcpAmt);
			
			bdFluctuation = finCommon.getFinparams("999999","BD_FLUCTUATION_CF",conn);
			writeLog(filePtr,"bdFluctuation:::"+bdFluctuation,true);
			
			if(bdFluctuation.equals("NULLFOUND"))
			{
				bdFluctuation = "Y";
			}
			exchRate = stdExchRate;
			if(billDisc.equals("Y") &&  bdFluctuation.equals("Y"))
			{
				exchRate = exprtExchRate;
				amtDiffExchRate = ((rcpAmt * exchRateRcv) - (rcpAmt * exprtExchRate));
			}
			else
			{
				amtDiffExchRate = ((rcpAmt * exchRateRcv) - (rcpAmt * exchRate));
			}
			receiptDetail.setRcpAmt(rcpAmt);
			receiptDetail.setExchRate(exchRate);
			receiptDetail.setAmtDiffExchRate(amtDiffExchRate);
			//}//
			//stmt2.close();
			//stmt2 = null;
		}//try
		//catch (SQLException ex)
		//{
		//	////writeException(ex);
		//	System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
		//	ex.printStackTrace();
		//	throw new ITMException(ex);
		//}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return receiptDetail;
	}// end of invoiceDetail()

	//******added on 28092006 by taranisen
/*	private Receipt2Detail invoiceDetailDetail(String invoiceId,String transer,Connection conn)throws ITMException
	{
		writeLog(filePtr,"[invoiceDetailDetail]START:::",true);

		Receipt2Detail receipt2Detail = new Receipt2Detail();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		double  diffAmtExch =0.0;
		double	exchrateVouch = 0.0;
		double	totAmt =0.0;
		double	adjAmt  = 0.0;
		String currCode = "";
		String acctCode = "";
		String 	cctrCode = "";
		String refSer = "";
		//exch rate from header (receipt)

		double exchRate	= ((Double)receiptMap.get("std_exrt")).doubleValue();
		writeLog(filePtr,"exch rate from header (receipt):::"+exchRate,true);
		try
		{

			 sql = "	select curr_code, exch_rate, acct_code, cctr_code, tot_amt, tot_amt - adj_amt"
			+" from receivables 	where tran_ser = '"+transer+"' and  ref_no = '"+invoiceId+"'";
			writeLog(filePtr,"[invoiceDetailDetail]"+sql,true);
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				currCode = rs.getString(1);
				exchrateVouch = rs.getDouble(2);
				acctCode = rs.getString(3);
				cctrCode = rs.getString(4);
				totAmt =rs.getDouble(5);
				adjAmt  = rs.getDouble(6);


				diffAmtExch =  (adjAmt * exchrateVouch) - (adjAmt * exchRate);
				receipt2Detail.setddCurrCode(currCode);
				receipt2Detail.setddAcctCode(acctCode);
				receipt2Detail.setddCctrCode(cctrCode);
				receipt2Detail. setddExchrateVouch(exchrateVouch);
				receipt2Detail.setddTotAmt(totAmt);
				receipt2Detail.setddAdjAmt(adjAmt);
				receipt2Detail.setddDiffAmtExch(diffAmtExch);
				receipt2Detail.setRefSer(transer);
				receipt2Detail.setInvoiceId(invoiceId);
			}

		}
		catch(Exception ee)
		{
			writeLog(filePtr,"Exception In (invoiceDetailDetail) ===>>>",true);
			writeLog(filePtr,ee,true);
			System.out.println("EECEPTION IN (invoiceDetailDetail) ===>>>");
			ee.printStackTrace();
		}
		writeLog(filePtr,"[invoiceDetailDetail]END:::",true);
		return receipt2Detail;

	}*/

	private void insertReceiptDtl(String tranId,ArrayList invoiceList,Connection conn)throws ITMException
	{
		writeLog(filePtr,"[insertReceiptDtl]START:::",true);
		java.sql.Timestamp refDate = null,dueDate = null;
		String lineNo = "",refNo = "",currCode = "",custCode = "",acctCodeAr = "";
		String cctrCodeAr = "",billDisc = "",refSer="";
		double exchRateRcv = 0,discount = 0,badDebtAmt = 0,exchRate = 0,diffAmtExch = 0;
		double taxAmt = 0,netAmt = 0,adjAmt = 0,rcpAmt = 0;
		int count = 0;
		PreparedStatement pstmt =null;

		String sql = "INSERT INTO RCPDET ( TRAN_ID,REF_SER,REF_NO,REF_DATE,CURR_CODE,EXCH_RATE__RCV,"
					+ "DISC_AMT,TAX_AMT,EXCH_RATE,NET_AMT,RCP_AMT,DIFF_AMT__EXCH,CUST_CODE,DUE_DATE,"
					+ "ACCT_CODE__AR,CCTR_CODE__AR,BAD_DEBT_AMT,BILL_DISC,LINE_NO__REF ) "
					+ "VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )";
		writeLog(filePtr,"[RCPDET SQL]:::"+sql,true);

		try
		{
			pstmt = conn.prepareStatement(sql);
			for(int invlCtr = 0; invlCtr < invoiceList.size(); invlCtr++)
			{
					ReceiptDetail receiptDetail = (ReceiptDetail)invoiceList.get(invlCtr);


					refNo = receiptDetail.getInvoiceId();
					writeLog(filePtr,"[INVOICE]"+refNo,true);
					lineNo = receiptDetail.getLineNo();
					refDate = receiptDetail.getRefDate();
					currCode = receiptDetail.getCurrCode();
					writeLog(filePtr,"[CURRCODE GOING]:::"+currCode,true);

					exchRateRcv = receiptDetail.getExchRateRcv();
					acctCodeAr = receiptDetail.getAcctCode();
					cctrCodeAr = receiptDetail.getCctrCode();
					dueDate = receiptDetail.getDueDate();
					custCode = receiptDetail.getCustCode();
					discount = receiptDetail.getDiscount();
					taxAmt = receiptDetail.getTaxAmt();
					netAmt = receiptDetail.getTotAmt();
					adjAmt = receiptDetail.getAdjAmt();
					badDebtAmt = receiptDetail.getBadDebtAmt();
					billDisc = receiptDetail.getBillDisc();
					rcpAmt = receiptDetail.getRcpAmt();
					exchRate = receiptDetail.getExchRate();
					diffAmtExch = receiptDetail.getAmtDiffExchRate();
					refSer = receiptDetail.getRefSer();
					writeLog(filePtr,"[REFSER]"+refSer,true);


					netAmtHdr = (netAmtHdr + netAmt);
					billAmt = (billAmt + rcpAmt);
					if(billDisc.equalsIgnoreCase("Y"))
					{
					billDiscAmt = (billDiscAmt +  rcpAmt);
					}

					pstmt.setString(1,tranId);

					pstmt.setString(2,refSer);
					//pstmt.setString(2,"S-INV");
					pstmt.setString(3,refNo);
					pstmt.setTimestamp(4,refDate);
					pstmt.setString(5,currCode);
					pstmt.setDouble(6,exchRateRcv);
					pstmt.setDouble(7,discount);
					pstmt.setDouble(8,taxAmt);
					pstmt.setDouble(9,exchRate);
					pstmt.setDouble(10,netAmt);
					pstmt.setDouble(11,rcpAmt);
					pstmt.setDouble(12,diffAmtExch);
					pstmt.setString(13,custCode);
					pstmt.setTimestamp(14,dueDate);
					pstmt.setString(15,acctCodeAr);
					pstmt.setString(16,cctrCodeAr);
					pstmt.setDouble(17,badDebtAmt);
					pstmt.setString(18,billDisc);
					pstmt.setString(19,lineNo);
					pstmt.addBatch();

				}
				pstmt.executeBatch();
				writeLog(filePtr,"[billAmt TO BE + UPDATE ]:::"+billAmt,true);
				writeLog(filePtr,"[billDiscAmt TO BE + UPDATE ]:::"+billDiscAmt,true);
				writeLog(filePtr,"[insertReceiptDtl]END:::",true);
			}
			catch (SQLException Se)
			{
				writeLog(filePtr,Se,true);
				System.out.println("Exception ::" + Se.getMessage() + ":");
				Se.printStackTrace();
				throw new ITMException(Se);
			}

			catch (Exception e)
			{
				writeLog(filePtr,e,true);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
		}//insertReceiptDtl()


		//******added on 28092006 by taranisen
	/*private void insertReceiptDtlDtl(String tranId,ArrayList dtl2lList,Connection conn)throws ITMException
	{

		writeLog(filePtr,"[insertReceiptDtlDtl]START:::",true);
		PreparedStatement pstmt = null;
		String sql = null;
		double  diffAmtExch =0.0;
		double	exchrateVouch = 0.0;
		double	totAmt =0.0;
		double	adjAmt  = 0.0;

		String currCode = "";
		String acctCode = "";
		String 	cctrCode = "";
		String refSer = "";
		String refNo = "";
		sql = "INSERT INTO RCPADV ( TRAN_ID , REF_SER,REF_NO, ADJ_AMT , TOT_AMT, CURR_CODE , EXCH_RATE__VOUCH ,"
			+" DIFF_AMT__EXCH , ACCT_CODE , CCTR_CODE ) VALUES ( ?,?,?,?,?,?,?,?,?,? )";
		int count = 0;
		try
		{
			pstmt = conn.prepareStatement(sql);
			for(int invlCtr = 0; invlCtr < dtl2lList.size(); invlCtr++)
			{
				Receipt2Detail receipt2Detail = (Receipt2Detail)dtl2lList.get(invlCtr);


				refNo = receipt2Detail.getInvoiceId();
				writeLog(filePtr,"[INVOICEID NOT S-INV]"+refNo,true);
				currCode = receipt2Detail.getddCurrCode();
				acctCode =receipt2Detail.getddAcctCode();
				cctrCode=receipt2Detail.getddCctrCode();
				refSer=receipt2Detail.getRefSer();
				diffAmtExch =receipt2Detail.getddDiffAmtExch();
				exchrateVouch = receipt2Detail.getddExchrateVouch();
				totAmt =receipt2Detail.getddTotAmt();
				adjAmt  =receipt2Detail.getddAdjAmt();

				System.out.println("Insert SQL ::- "+sql);

				pstmt.setString(1,tranId);
				pstmt.setString(2,refSer);
				pstmt.setString(3,refNo);
				pstmt.setDouble(4,adjAmt);
				pstmt.setDouble(5,totAmt);
				pstmt.setString(6,currCode);
				pstmt.setDouble(7,exchrateVouch);
				pstmt.setDouble(8,diffAmtExch);
				pstmt.setString(9,acctCode);
				pstmt.setString(10,cctrCode);
				pstmt.addBatch();

				double adv_amt_old = 0.0;
				advAdjAmtHdr = advAdjAmtHdr+adv_amt_old - adjAmt;
				diffAmtExcHdr=diffAmtExcHdr+ diffAmtExch;
			}
			pstmt.executeBatch();
			writeLog(filePtr,"[insertReceiptDtlDtl]END:::",true);
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}

	}//insertReceiptDtlDtl()*/
//	******************************
	private String generateTranTd(String windowName,String tranDate,String siteCode)throws ITMException
	{
		ConnDriver connDriver = new ConnDriver();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		String tranId = "";
		String newKeystring = "";
		try
	 	{
		 	conn = connDriver.getConnectDB("DriverITM");
			sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = '"+windowName+"'";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			System.out.println("keyString :"+rs.toString());
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);
			}
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			String xmlValues = "";
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +	"<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues + "<tran_date>"+ tranDate + "</tran_date>";
			xmlValues = xmlValues + "<tran_type>"+"U"+"</tran_type>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", commonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);

			System.out.println("tranId ::"+tranId);
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			System.out.println("Closing Connection3...");
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception se){}
		}//
		return tranId;
	}//generateTranTd()

	private int updateReceipt(double netAmt,double billAmt,double billDiscAmt,String tranId,Connection conn)throws ITMException
	{
		Statement stmt = null;
		String sql = "";
		int cnt = 0;
		try
		{
			// 15-09-2006 manoharan net_amt should not be updated
			//sql = "UPDATE RECEIPT SET NET_AMT = (CASE WHEN NET_AMT IS NULL THEN 0 ELSE NET_AMT END  + ("+netAmt+")), "
			//	+ "BILL_AMT = (CASE WHEN BILL_AMT IS NULL THEN 0 ELSE BILL_AMT END  + ("+billAmt+")), "
			//	+ "BILL_DISC_AMT = (CASE WHEN BILL_DISC_AMT IS NULL THEN 0 ELSE BILL_DISC_AMT END  + ("+billDiscAmt+")) WHERE TRAN_ID = '"+tranId.trim()+"'";
			sql = "UPDATE RECEIPT SET BILL_AMT = (CASE WHEN BILL_AMT IS NULL THEN 0 ELSE BILL_AMT END  + ("+billAmt+")), "
				+ "BILL_DISC_AMT = (CASE WHEN BILL_DISC_AMT IS NULL THEN 0 ELSE BILL_DISC_AMT END  + ("+billDiscAmt+")) WHERE TRAN_ID = '"+tranId.trim()+"'";
					writeLog(filePtr,"UPDATE SQL FOR RECEIPT(S-INV)"+sql,true);

			stmt = conn.createStatement();
			cnt = stmt.executeUpdate(sql);
			System.out.println("No of records updated in RECEIPT is : "+cnt);
			System.out.println("Update SQL : "+sql);

			stmt.close();
			stmt = null;
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return cnt;
	}//updateReceipt()

	//******added on 28092006 by taranisen
/*private int updateReceipt(double advAdjAmtHdr,double diffAmtExcHdr,String tranId ,Connection conn)throws ITMException
{
		Statement stmt = null;
		String sql = "";
		int cnt = 0;
		try
		{
			sql = "UPDATE RECEIPT SET ADVADJ_AMT = (CASE WHEN ADVADJ_AMT IS NULL THEN 0 ELSE BILL_AMT END  + ("+advAdjAmtHdr+")), "
				+ "DIFF_AMT__EXCH = (CASE WHEN DIFF_AMT__EXCH IS NULL THEN 0 ELSE DIFF_AMT__EXCH END  + ("+diffAmtExcHdr+")) WHERE TRAN_ID = '"+tranId.trim()+"'";
					writeLog(filePtr,"UPDATE SQL FOR RECEIPT(S-INV)"+sql,true);


			stmt = conn.createStatement();
			cnt = stmt.executeUpdate(sql);
			System.out.println("No of records updated in RECEIPT is : "+cnt);
			System.out.println("Update SQL : "+sql);

			stmt.close();
			stmt = null;
		}
		catch (SQLException ex)
		{
			writeLog(filePtr,ex,true);
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return cnt;

}*/



/*	private void ////writeException(Exception e)
	{
		try
		{
			fw.write(e.getMessage() + "\r\n");
			PrintStream t = new PrintStream(new FileOutputStream(new File("C:\\pb10\\log\\pbnitrace.log"),true));
			e.printStackTrace(t);
		}
		catch(Exception t){}
	}*/
	private static void writeLog(File f,Exception ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			ex.printStackTrace(pw);
			pw.close();
		}
		catch(Exception exWe){exWe.printStackTrace();}
	}
	private static void writeLog(File f,String ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			pw.println(ex);
			pw.close();
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}
	public double getRequiredDecimal(double actVal, int prec)	// this metod added by rajesh k to change number format
    {
        NumberFormat numberFormat = NumberFormat.getIntegerInstance ();
        Double DoubleValue = new Double (actVal);
        numberFormat.setMaximumFractionDigits(prec);
        String strValue = numberFormat.format(DoubleValue);
        strValue = strValue.replaceAll(",","");
        double reqVal = Double.parseDouble(strValue);
        return reqVal;
    }

	/*	private void sendMail(String XMLData,String siteCode,String custCode,Timestamp dueDate,int pnodeListLength, Connection conn)throws ITMException
	{
		CommunicationComp communicationComp = new CommunicationComp();
		PreparedStatement pstmt = null;
		ResultSet mrs = null;
		String msql = "", commFormat = "",eventContext = "";
		int dbcount = 0,commLineNo = 0;
		try
		{
			msql = "SELECT COUNT(*) AS COUNT FROM INVOICE A,SORDER B "
				+ "WHERE A.SALE_ORDER = B.SALE_ORDER "
				+ "AND A.SITE_CODE = '"+siteCode.trim()+"' "
				+ "AND A.CUST_CODE = '"+custCode.trim()+"' "
				+ "AND A.DUE_DATE = ? ";

			pstmt = conn.prepareStatement(msql);
			pstmt.setTimestamp(1,dueDate);

			System.out.println("The SQL for mail is ..............:"+msql);
			mrs = pstmt.executeQuery();

   			while (mrs.next())
			{
				dbcount = mrs.getInt("COUNT");
				System.out.println("$$$$$ The no. of records from database are $$$$$ "+dbcount);
			}
			pstmt.close();
			pstmt = null;
		}
		catch (SQLException ex)
		{
			////writeException(ex);
			System.out.println("Exception ::" +msql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			////writeException(e);
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("$$$$ The no. of records selected are $$$$ "+pnodeListLength);
		if( pnodeListLength < dbcount )
		{
			try
			{
				msql = "SELECT COMM_FORMAT FROM SYSTEM_EVENTS "
					 + "WHERE OBJ_NAME = 'generate_receipt' AND EVENT_CONTEXT = 'process' ";

				pstmt = conn.prepareStatement(msql);
				mrs = pstmt.executeQuery();
				if(mrs.next())
				{
					commFormat = mrs.getString(1);
					if(commFormat == null)
					{
						commFormat = "";
					}
					System.out.println("COMM_FORMAT is "+commFormat);
				}
				pstmt.close();
				pstmt = null;
			}
			catch (SQLException ex)
			{
				////writeException(ex);
				System.out.println("Exception ::" +msql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				////writeException(e);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			try
			{
				msql = "SELECT LINE_NO FROM COMM_FORMAT WHERE COMM_FORMAT = '"+commFormat+"'";

				pstmt = conn.prepareStatement(msql);
				mrs = pstmt.executeQuery();
				while (mrs.next())
				{
					commLineNo = mrs.getInt(1);
					System.out.println("COMM_FORMAT LINE No is "+commLineNo);
					   String cmmInfo = "";
					   cmmInfo = "<Root>~r~n";
					   cmmInfo = cmmInfo + "<OBJ_NAME><![CDATA[generate_receipt]]></OBJ_NAME>~r~n";
					   cmmInfo = cmmInfo + "<REF_SER><![CDATA[RCP]]></REF_SER>~r~n";
					   cmmInfo = cmmInfo + "<REF_ID><![CDATA[]]></REF_ID>~r~n";
					   cmmInfo = cmmInfo + "<LINE_NO><![CDATA[" + commLineNo + "]]></LINE_NO>~r~n";
					   cmmInfo = cmmInfo + "<COMM_FORMAT><![CDATA[" + commFormat.trim() + "]]></COMM_FORMAT>~r~n";
					   cmmInfo = cmmInfo + "<MAIL_INFO_TYPE><![CDATA[ITM]]></MAIL_INFO_TYPE>~r~n";
					   cmmInfo = cmmInfo + "</Root>~r~n";

					   String errCode = communicationComp.communicate(cmmInfo,XMLData);
					   System.out.println("ERROR WHILE SENDING THE MAIL "+errCode);
				}
				pstmt.close();
				pstmt = null;
			}
			catch (SQLException ex)
			{
				////writeException(ex);
				System.out.println("Exception ::" +msql+ ex.getMessage() + ":");
				ex.printStackTrace();
				throw new ITMException(ex);
			}
			catch (Exception e)
			{
				////writeException(e);
				System.out.println("Exception ::" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
		}//if
	}//sendMail()
	private String serializeDom(Node dom)
	{
		String retString = null;
		try
		{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Transformer serializer = TransformerFactory.newInstance().newTransformer();
			serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			serializer.transform(new DOMSource(dom), new javax.xml.transform.stream.StreamResult(out));
			retString = out.toString();
			out.flush();
			out.close();
			out = null;
		}
		catch (Exception e)
		{
			System.out.println("Exception : In : serializeDom :"+e);

		}
		return retString;
	}	*/


 }//class

//LHL22
//AD018
//28/12/2005

