/*
* PURPOSE : Generate Receipt through web browser
* AUTHOR : Mahendra Jadhav[F14ISUN011] 
*/  
package ibase.webitm.ejb.fin;

import ibase.system.config.*;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;

import org.w3c.dom.*;

@javax.ejb.Stateless
public class GenReceiptIC extends ValidatorEJB implements GenReceiptICLocal, GenReceiptICRemote//implements SessionBean
{
	/**
	 * The public method is used for validation of required fields which inturn called overloded method
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currXmlDataStr contains the current form data in XML format
	 * @param hdrXmlDataStr contains always header form data in XML format
	 * @param allXmlDataStr contains all forms data in XML format 
	 * @param objContext represents form no
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contais additional information such as loginEmpCode,loginCode,chgTerm etc
	 */ 
	GenericUtility genericUtility = GenericUtility.getInstance();
	String winName = null;
	FinCommon finCommon = null;
	ValidatorEJB validator = null;
	String allXmlDataStr1="";
	

	E12GenericUtility e12GenericUtility = new E12GenericUtility();
	

	public String wfValData(String currXmlDataStr, String hdrXmlDataStr,String allXmlDataStr,String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			 allXmlDataStr1=allXmlDataStr;
			if(currXmlDataStr != null && currXmlDataStr.trim().length()!= 0)
			{
				//System.out.println ( "currXmlDataStr: " + currXmlDataStr);
				currDom = genericUtility.parseString(currXmlDataStr); 
			}
			if(hdrXmlDataStr != null && hdrXmlDataStr.trim().length()!= 0)
			{
				hdrDom = genericUtility.parseString(hdrXmlDataStr);
				//System.out.println("hdrXmlDataStr:"+hdrXmlDataStr);
			}
			if(allXmlDataStr != null && allXmlDataStr.trim().length()!= 0)
			{
				allDom = genericUtility.parseString(allXmlDataStr);
				//System.out.println("allXmlDataStr:"+allXmlDataStr);
			}
			errString = wfValData( currDom, hdrDom,allDom,objContext, editFlag, xtraParams );
			System.out.println ( "ErrString: " + errString);
		}
		catch(Exception e)
		{

			System.out.println ( "Exception: CRemittanceTrEJB: wfValData(String currXmlDataStr): " + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);

		}
		System.out.println ( "Returning from CRemittanceTrEJB wfValData" );
		return ( errString ); 
	}

	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException {
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		StringBuffer valueXmlString = new StringBuffer();
		String siteCode = "";
		String custCode = "";
		String userId = "";
		String sql = "";
		String errCode = "";
		String errorType = "";
		String errString = "";
		String bankCode = "";
		String prdCode = "",refNo="",refSer="",lineNo="";
		java.util.Date tranDate = null;
		int ctr = 0;
		int currentFormNo = 0;
		int cnt = 0;
		ArrayList errList = new ArrayList();
		ArrayList errFields = new ArrayList();
		SimpleDateFormat dateFormat2 = null; //new SimpleDateFormat(genericUtility.getApplDateFormat());
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		Document domAll = null;
		ConnDriver connDriver = new ConnDriver();
		//String custrefNo="";
		int countCustRef=0,refSerCnt=0;
		int childNodeListLength=0;
		double rcpAmt=0.0,chqAmt=0.0,rcpAmtVal=0.0;
		boolean isValidcustRef=false;
		ArrayList<String> refNoList = new ArrayList<String>();
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>");
		try
		{
			System.out.println("validation called!!!!");
			dateFormat2 = new SimpleDateFormat(genericUtility.getApplDateFormat());
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			if ((objContext != null) && (objContext.trim().length() > 0))
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
			valueXmlString.append(editFlag).append("</editFlag> </header>");
			switch (currentFormNo)
			{
			case 1:
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				//valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				for (ctr = 0; ctr < childNodeListLength; ctr++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equalsIgnoreCase("site_code"))
					{
						siteCode = this.genericUtility.getColumnValue("site_code", dom);
						if(siteCode != null && siteCode.trim().length() > 0 )
						{
							sql = "select count(*) from site where site_code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, siteCode.trim());
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}
							if (cnt == 0)
							{
								errCode = "VMSITE1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if(genericUtility.getColumnValue("eff_date", dom) == null)
							{
								tranDate = null;
							}
							else
							{
								tranDate = dateFormat2.parse(genericUtility.getColumnValue("eff_date",dom));

								System.out.println("Check for site period ");
								sql = "select code from period where ?  between fr_date and to_date";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setDate(1,new java.sql.Date(tranDate.getTime()));
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									prdCode =  rs.getString(1);

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

								sql = "select count(*) from period_stat where site_code = ? and prd_code = ? ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,siteCode);
								pstmt.setString(2,prdCode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt =  rs.getInt(1);

								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								if(cnt == 0)
								{
									errCode = "VTSITEPD";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								errCode = nfCheckPeriod("FIN",tranDate,siteCode);
								if(errCode != null && errCode.trim().length() > 0)
								{
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
							}
						}

						else
						{
							errCode = "VMSITENUL";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					else if (childNodeName.equalsIgnoreCase("cust_code"))
					{
						custCode = this.genericUtility.getColumnValue("cust_code", dom);
						if(custCode != null && custCode.trim().length() > 0 )
						{
							sql = "SELECT COUNT(*) AS COUNT FROM CUSTOMER WHERE CUST_CODE = ? " ;
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,custCode);
							rs = pstmt.executeQuery();
							if( rs.next())
							{
								cnt = rs.getInt("COUNT");
							}
							if( cnt == 0 )
							{
								errCode = "VTCUSTCD1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							rs.close(); 
							rs = null;
							pstmt.close();
							pstmt = null;
						}

						else
						{
							errCode = "VMCUSTCD1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					else if (childNodeName.equalsIgnoreCase("bank_code"))
					{
						bankCode = this.genericUtility.getColumnValue("bank_code", dom);
						if(bankCode != null && bankCode.trim().length() > 0)
						{
							sql = "SELECT COUNT(*) AS COUNT FROM BANK WHERE BANK_CODE = ? " ;
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,bankCode);
							rs = pstmt.executeQuery();
							if( rs.next())
							{
								cnt = rs.getInt("COUNT");
							}
							if( cnt == 0 )
							{
								errCode = "VMBANKMIS1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
						else
						{
							errCode = "VMBANKCD1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					else if (childNodeName.equalsIgnoreCase("chq_amt"))
					{
						 if(!(isNumeric(this.genericUtility.getColumnValue("chq_amt", dom))))
					     {
					    	    errCode = "VTCHQATEMP";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
								System.out.println("cheque amount not valid");
					     }
						 else
						 {
							 chqAmt=doublevalue(this.genericUtility.getColumnValue("chq_amt", dom));
						 }
						
						System.out.println("chqAmt---"+chqAmt);
					     if(chqAmt < 0)
					     {
					    	 errCode = "VTCHQATEMP";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					     }
					     System.out.println("!!"+this.genericUtility.getColumnValue("chq_amt", dom));
					    
						
						
					}
					
				}
				//valueXmlString.append("</Detail1>");
				break;

			case 2:
				domAll= parseString(allXmlDataStr1);
				System.out.println("###allXmlDataStr1:"+allXmlDataStr1);
				parentNodeList = domAll.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				//valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength :"+childNodeListLength);
				for (ctr = 0; ctr < childNodeListLength; ctr++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					
					
					if(childNodeName.equalsIgnoreCase("ref_ser"))
					{
						refSer=this.genericUtility.getColumnValue("ref_ser", domAll);
						System.out.println("refSer---"+refSer);
					     if(refSer == null)
					     {
					    	 errCode = "VTREFSREMP";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					     }
					     else
					     {
					    	 refSer=refSer.trim();
								sql="select count(*) from receivables where tran_ser=?";
								pstmt1=conn.prepareStatement(sql);
								pstmt1.setString(1,refSer);
								rs1=pstmt1.executeQuery();
								if(rs1.next())
								{
									refSerCnt = rs1.getInt(1);
								}
								rs1.close();  
								rs1 = null;
								pstmt1.close();
								pstmt1 = null;
					    	 
					    	 System.out.println("refSerCnt :"+refSerCnt);
					    	 if(refSerCnt == 0)
					    	 {
					    		    errCode = "VTREFSRINV";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
					    	 }
					    	 
					     }
					     
					}
					else if (childNodeName.equalsIgnoreCase("ref_no"))
					{
						refNo=this.genericUtility.getColumnValue("ref_no", domAll);
						//siteCode=this.genericUtility.getColumnValue("site_code", domAll);
						siteCode=this.genericUtility.getColumnValue("site_code", dom1);
						String siteCode1=this.genericUtility.getColumnValue("site_code", domAll);
						lineNo = genericUtility.getColumnValue("line_no",domAll);
						refSer=this.genericUtility.getColumnValue("ref_ser", domAll);
						System.out.println("Ref No---"+refNo);
						System.out.println("siteCode---"+siteCode);
						System.out.println("siteCode1---"+siteCode1);
						System.out.println("lineNo---"+lineNo);
						System.out.println("refSer---"+refSer);
						
						 if(refNo == null)
					     {
					    	 errCode = "VTREFNOEMP";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					     }
						 else
						 {
							    refNo=refNo.trim();
								sql="select count(*) from receivables where ref_no=?";
								pstmt1=conn.prepareStatement(sql);
								pstmt1.setString(1,refNo);
								rs1=pstmt1.executeQuery();
								if(rs1.next())
								{
									if(rs1.getInt(1)>0)
									{
										isValidcustRef=true;
									}
									else
									{
										errCode = "VTREFVLD";
										errList.add(errCode);
										errFields.add(childNodeName.toLowerCase());
									}
								}
								rs1.close(); // added By akhilesh on 10/01/13 to close the statement 
								rs1 = null;
								pstmt1.close();
								pstmt1 = null;
						 }
						if(isValidcustRef)
						{
							 refNo=refNo.trim();
							sql="select count(*) from receivables where ref_no=? and site_code=?";
							pstmt=conn.prepareStatement(sql);
							pstmt.setString(1,refNo);
							pstmt.setString(2,siteCode);
							rs=pstmt.executeQuery();
							if(rs.next())
							{
								countCustRef=rs.getInt(1);
							}
							rs.close();
							rs=null;
							pstmt.close();
							pstmt=null;
							if(countCustRef==0)
							{
								errCode = "INVREFSITE";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							
						}
						
						if (isDulplicateFrmDom())
						{
							errCode = "VTDUPREFNO";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						

					}
					else if(childNodeName.equalsIgnoreCase("rcp_amt"))
					{
						
						
						  System.out.println("rcp_amt!! "+this.genericUtility.getColumnValue("rcp_amt", domAll));
						  if(!(isNumeric(this.genericUtility.getColumnValue("rcp_amt", domAll))))
						  {
						    	    errCode = "VTRCPATVLD";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
									System.out.println("Receipt amount not valid");
						  }
						  else
						  {
							  rcpAmt=doublevalue(this.genericUtility.getColumnValue("rcp_amt", domAll)); 
						  }
						
						System.out.println("rcpAmt---"+rcpAmt);
					     if(rcpAmt == 0)
					     {
					    	 errCode = "VRCPAMTEMP";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					     }
					     if(rcpAmt < 0)
					     {
					    	 errCode = "VTRCPATVLD";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					     }
					  					   
					     
					     if(checkAmtvalidation(dom1))
					     {
					    	 errCode = "VTCHQATINV";
							 errList.add(errCode);
							 errFields.add(childNodeName.toLowerCase());
					    	 
					     }
					     
					     System.out.println("ref_ser :"+genericUtility.getColumnValue("ref_ser",domAll));
					     System.out.println("ref_no :"+genericUtility.getColumnValue("ref_no",domAll));
					     System.out.println("custCode :"+genericUtility.getColumnValue("cust_code", dom1));
					     System.out.println("site_code :"+genericUtility.getColumnValue("site_code", dom1));
					
					 	sql = "SELECT (TOT_AMT - ADJ_AMT) AS AMT FROM RECEIVABLES WHERE TRAN_SER = ? AND REF_NO = ?  AND cust_code = ? and site_code=? " ;
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,checkNull(genericUtility.getColumnValue("ref_ser",domAll)));
						pstmt.setString(2,checkNull(genericUtility.getColumnValue("ref_no",domAll)));
						pstmt.setString(3,checkNull(genericUtility.getColumnValue("cust_code",dom1)));
						pstmt.setString(4,checkNull(genericUtility.getColumnValue("site_code",dom1)));
						rs = pstmt.executeQuery();
						if( rs.next())
						{
							rcpAmtVal=rs.getDouble(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						System.out.println("rcpAmtVal>>>["+rcpAmtVal+"]rcpAmt["+rcpAmt+"]");
						if(rcpAmtVal < rcpAmt)
						{
							errCode = "VTINVTLAMT";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					     
					     
					}
					
					
					
				}
				break;

			}
			int errListSize = errList.size();
			cnt = 0;
			String errFldName = null;
			if ((errList != null) && (errListSize > 0))
			{
				for (cnt = 0; cnt < errListSize; cnt++)
				{
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					errString = getErrorString(errFldName, errCode, userId);
					errorType = errorType(conn, errCode);
					if (errString.length() > 0)
					{
						String bifurErrString = errString.substring(errString.indexOf("<Errors>") + 
								8, errString.indexOf("<trace>"));
						bifurErrString = bifurErrString + 
								errString.substring(errString.indexOf("</trace>") + 
										8, errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						errString = "";
					}
					if (errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}

				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (rs != null)
					{
						rs.close();
						rs = null;
					}
					if (pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}

					conn.close();
				}
				conn = null;
			}
			catch (Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		return errString;
	}





	public String itemChanged() throws RemoteException, ITMException
	{
		return "";
	}

	/**
	 * The public method is used for itemchange of required fields which inturn called overloded method
	 * Returns itemchange string in XML format
	 * @param currXmlDataStr contains the current form data in XML format
	 * @param hdrXmlDataStr contains always header form data in XML format
	 * @param allXmlDataStr contains all forms data in XML format 
	 * @param objContext represents form no
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contais additional information such as loginEmpCode,loginCode,chgTerm etc
	 */
	public String itemChanged(String currXmlDataStr, String hdrXmlDataStr, String allXmlDataStr, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if (currXmlDataStr != null && currXmlDataStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currXmlDataStr); 
			}
			if (hdrXmlDataStr != null && hdrXmlDataStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrXmlDataStr); 
			}
			if (allXmlDataStr != null && allXmlDataStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :CRemittanceTrEJB :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);

		}
		System.out.println ( "returning from CRemittanceTrEJB itemChanged" );
		return errString;
	}//
	/**
	 * The public overloded method is used for itemchange of required fields 
	 * Returns itemchange string in XML format
	 * @param currDom contains the current form data 
	 * @param hdrDom contains always header form data
	 * @param allDom contains all forms data 
	 * @param objContext represents form no
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contais additional information such as loginEmpCode,loginCode,chgTerm etc
	 */
	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String sql = "",refSer1="";		
		String loginCode = "";
		String loginSite = "";
		String loginSiteDesc = "";
		String custCodeValue = "";
		String custName = "";
		String bankNameValue = "";	
		String siteCodeDesc = "";
		String siteCodeValue = "";		
		String bankName = "";
		String rcpMode = "";
		String refNo = "";
		String chqAmtStr = "";
		String refNoDr = "";
		String refNoCust = "";
		StringBuffer valueXmlString = new StringBuffer();
		String tranIdRcp = "";
		String tranIdAdj = "",bankCode="";
		String guid = "";
		String refDate = "";
		int currentFormNo = 0;
		SimpleDateFormat dateFormat2 = null;


		Connection connObject = null;
		PreparedStatement pstmt = null,pstmt1 = null;
		ResultSet rSet = null , rs1 = null;
		//Timestamp discDate=null;
		java.util.Date discountDate = null, tranDate = null;
		double discAmt=0;
		double chequeAmt = 0,rcpAmt = 0,commAmt = 0; 
		DistCommon distCommon = new DistCommon();
		double custDocAmt=0,discAppr=0,finChg=0;
		String updateFlag="";
		GenericUtility genericUtility = GenericUtility.getInstance();
		boolean isFound=false;
		String balAmtReqd="";
		int parentNodeListLength=0;
		try
		{
			dateFormat2=new SimpleDateFormat(genericUtility.getApplDateFormat());
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			connObject = connDriver.getConnectDB("DriverValidator");

			loginCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginEmpCode" ));
			System.out.println("loginCode =["+loginCode+"]");

			DateFormat dtFormat = new SimpleDateFormat(getApplDateFormat());
			java.util.Date date = new java.util.Date(); 
			String currDate = dtFormat.format( date );

			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}





			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
			valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n" );
			switch ( currentFormNo )
			{
			case 1:
			{
				valueXmlString.append( "<Detail1>\r\n" );			
				System.out.println("Enter in case 1");

				if ( currentColumn.trim().equalsIgnoreCase( "itm_default" ))
				{
					System.out.println("Enter in itm default");
					loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSite");

					sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ?";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, loginSite);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						loginSiteDesc = rSet.getString( "DESCR" );
					}
					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;
					
					
					
					sql = "select bank_code from site where site_code= ? ";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, loginSite);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						bankCode = rSet.getString("bank_code");
					}
					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;
					
					
					sql = " select bank_name from bank where bank_code=? ";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, bankCode);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						bankName = rSet.getString("bank_name");
					}
					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;
					
					valueXmlString.append("<tran_date><![CDATA[" ).append( checkNull( currDate ) ).append( "]]></tran_date>\r\n" );
					valueXmlString.append("<tran_type protect = \"0\"><![CDATA[" ).append("L").append( "]]></tran_type>\r\n");
					valueXmlString.append("<eff_date><![CDATA[" ).append( checkNull( currDate ) ).append( "]]></eff_date>\r\n" );
					valueXmlString.append("<ref_date><![CDATA[" ).append( checkNull( currDate ) ).append( "]]></ref_date>\r\n" );
					valueXmlString.append("<rcp_mode><![CDATA[" ).append("C").append( "]]></rcp_mode>\r\n");
					valueXmlString.append("<site_code><![CDATA[" ).append(loginSite).append( "]]></site_code>\r\n");
					valueXmlString.append("<descr><![CDATA[" ).append(loginSiteDesc).append( "]]></descr>\r\n");
					valueXmlString.append("<bank_code><![CDATA[" ).append(bankCode).append( "]]></bank_code>\r\n");
					valueXmlString.append("<bank_name><![CDATA[" ).append(bankName).append( "]]></bank_name>\r\n");
					valueXmlString.append("<verify_flag><![CDATA[" ).append("N").append( "]]></verify_flag>\r\n");

					System.out.println("Itm default Rohan" + valueXmlString.toString());

				}
				else if (currentColumn.trim().equalsIgnoreCase("itm_defaultedit"))
				{
					tranIdRcp = checkNull(genericUtility.getColumnValue("tran_id__rcp",currDom));
					System.err.println("tranIdRcp value in edit "+tranIdRcp);
					if(tranIdRcp != null && tranIdRcp.trim().length() > 0)
					{
						bankNameValue = checkNull(genericUtility.getColumnValue("bank_code",currDom));
						custCodeValue = checkNull(genericUtility.getColumnValue("cust_code",currDom));
						//siteCodeValue = checkNull(genericUtility.getColumnValue("site_code",currDom));
						rcpMode = checkNull(genericUtility.getColumnValue("rcp_mode",currDom));
						chqAmtStr = checkNull(genericUtility.getColumnValue("chq_amt",currDom));
						tranIdRcp = checkNull(genericUtility.getColumnValue("tran_id__rcp",currDom));
						tranIdAdj = checkNull(genericUtility.getColumnValue("tran_id__adj",currDom));
						refNo = checkNull(genericUtility.getColumnValue("ref_no",currDom));
						refDate = genericUtility.getColumnValue("ref_date",currDom);
						guid = checkNull(genericUtility.getColumnValue("guid",currDom));

						valueXmlString.append("<bank_code protect = \"1\">").append("<![CDATA["+bankNameValue+"]]>").append("</bank_code>");
						valueXmlString.append("<cust_code protect = \"1\">").append("<![CDATA["+custCodeValue+"]]>").append("</cust_code>");
						//valueXmlString.append("<site_code protect = \"1\">").append("<![CDATA["+siteCodeValue+"]]>").append("</site_code>");
						valueXmlString.append("<rcp_mode protect = \"1\">").append("<![CDATA["+rcpMode+"]]>").append("</rcp_mode>");
						valueXmlString.append("<ref_no protect = \"1\">").append("<![CDATA["+refNo+"]]>").append("</ref_no>");
						if(refDate != null && refDate.trim().length() > 0)
						{

							valueXmlString.append("<ref_date protect = \"1\">").append("<![CDATA["+refDate.trim()+"]]>").append("</ref_date>");
						}

						valueXmlString.append("<chq_amt protect = \"1\">").append("<![CDATA["+chqAmtStr+"]]>").append("</chq_amt>");
						valueXmlString.append("<tran_id__rcp protect = \"1\">").append("<![CDATA["+tranIdRcp+"]]>").append("</tran_id__rcp>");
						valueXmlString.append("<tran_id__adj protect = \"1\">").append("<![CDATA["+tranIdAdj+"]]>").append("</tran_id__adj>");
						valueXmlString.append("<guid protect = \"1\">").append("<![CDATA["+guid+"]]>").append("</guid>");
					}
				}

				else if( currentColumn.trim().equalsIgnoreCase( "bank_code" ) )
				{  
					System.out.println("Enter in bank code");
					bankNameValue = checkNull(genericUtility.getColumnValue("bank_code",currDom));

					sql = "SELECT BANK_NAME FROM BANK WHERE BANK_CODE =?";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, bankNameValue);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						bankName = checkNull(rSet.getString( "BANK_NAME" ));

					}
					valueXmlString.append("<bank_name>").append("<![CDATA["+bankName+"]]>").append("</bank_name>\r\n");

					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;
				}

				else if( currentColumn.trim().equalsIgnoreCase( "cust_code" ) )
				{  
					System.out.println("Enter in cust_code");
					custCodeValue = checkNull(genericUtility.getColumnValue("cust_code",currDom));
					sql = "SELECT CUST_NAME FROM CUSTOMER WHERE CUST_CODE = ?";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, custCodeValue);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						custName = checkNull(rSet.getString( "CUST_NAME" ));
					}					
					valueXmlString.append("<cust_name><![CDATA[").append(custName).append("]]></cust_name>\r\n");			  						

					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;

				}

				else if( currentColumn.trim().equalsIgnoreCase( "site_code" ) )
				{
					System.out.println("Enter in site code");
					siteCodeValue = checkNull(genericUtility.getColumnValue("site_code",currDom));

					sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ? ";
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1, siteCodeValue);
					rSet = pstmt.executeQuery();
					if( rSet.next() )
					{
						siteCodeDesc = checkNull(rSet.getString( "DESCR" ));

					}
					valueXmlString.append("<descr><![CDATA[").append(siteCodeDesc).append("]]></descr>\r\n");

					rSet.close(); // added By akhilesh on 10/01/13 to close the statement 
					rSet = null;
					pstmt.close();
					pstmt = null;
				}

				valueXmlString.append( "</Detail1>\r\n" );		 	 
			}
			break;		
			case 2:
			{
				//
				NodeList parentNodeList = null;
				NodeList childNodeList = null;
				Node parentNode = null;
				Node childNode = null;
				int childNodeListLength,ctr2=0;
				String childNodeName = null,updateFlag1=null;
				for(int i =0; i< currDom.getElementsByTagName("Detail2").getLength();i++)
				{
					updateFlag = getCurrentUpdateFlag(currDom.getElementsByTagName("Detail2").item(i));
					// System.out.println("@@@@@@@  updateFlag in :["+updateFlag+"]");
				}

				System.out.println("!!!!!!!!!!!!!final  updateFlag :["+updateFlag+"]");
				valueXmlString.append( "<Detail2>\r\n");
				
				
				/*	
				//else if ( currentColumn.trim().equalsIgnoreCase( "line_no__ref" ) || currentColumn.trim().equalsIgnoreCase( "ref_no" ) ||currentColumn.trim().equalsIgnoreCase( "ref_ser" ))
				/*else if (  currentColumn.trim().equalsIgnoreCase( "ref_no" ) )
				{
					
				}*/
				// added by cpatil on 21/12/12 start
				System.out.println("currentColumn ::"+currentColumn);
				if ( ( currentColumn.trim().equalsIgnoreCase( "line_no__ref" ) || currentColumn.trim().equalsIgnoreCase( "ref_no" ) || currentColumn.trim().equalsIgnoreCase( "ref_ser" ))  &&  ( "A".equalsIgnoreCase( updateFlag )) )  
				{
					
					refNo = genericUtility.getColumnValue("ref_no",currDom);
					System.out.println("refNo :"+refNo);
					
					
					if(genericUtility.getColumnValue("tran_date", hdrDom) == null)
					{
						tranDate = null;
					}
					else
					{
						tranDate =  dateFormat2.parse(genericUtility.getColumnValue("tran_date", hdrDom));
					}
					System.out.println("refNo= "+refNo+"    tranDate="+tranDate);

					sql ="select (tot_amt - adj_amt) as amt , tran_ser,tran_date,ref_no,ref_date,curr_code,exch_rate,acct_code,   cctr_code,due_date,tax_amt,tot_amt,cust_code,adj_amt,   case when bad_debt_amt is null then 0 else bad_debt_amt end,discount_dt,DISCOUNT     from receivables  "
							+ "  where tran_ser = ? and ref_no = ?     and line_no__ref = ?  " ;
					pstmt = connObject.prepareStatement(sql);
					pstmt.setString(1,checkNull(genericUtility.getColumnValue("ref_ser",currDom)));
					pstmt.setString(2,checkNull(genericUtility.getColumnValue("ref_no",currDom)));
					pstmt.setString(3,checkNull(genericUtility.getColumnValue("line_no__ref",currDom)));
					rSet = pstmt.executeQuery();
					if (rSet.next())
					{
						
						rcpAmt=rSet.getDouble(1);
						isFound=true;
					}
					rSet.close();
					rSet=null;
					pstmt.close();
					pstmt=null;
					System.out.println("rcpAmt= "+rcpAmt);
					HashMap discountMap = calcDiscount( refNo,  tranDate,rcpAmt, connObject);
					discAmt = (Double)discountMap.get("disc_amt");
					discountDate = (java.util.Date)discountMap.get("discount_dt");
					if(discountDate !=null)
					{
						valueXmlString.append("<discount_dt><![CDATA[").append(dateFormat2.format(discountDate)).append("]]></discount_dt>\r\n");
					}
					
/*					if(discDate!=null)
					{
						valueXmlString.append("<discount_dt><![CDATA[").append(dateFormat2.format(discDate)).append("]]></discount_dt>\r\n");
					}*/
					
					//Added By manoj on 07/02/2013 to reset value while ref_no found valid
					if(isFound)
					{
						System.out.println("isFound set value from receivables ..");
						//change done by kunal on 09/05/13 round 2 decimeal
						
						valueXmlString.append("<rcp_amt><![CDATA[").append(round(rcpAmt, 2)).append("]]></rcp_amt>\r\n");
						valueXmlString.append("<disc_amt><![CDATA[").append(round(discAmt, 2)).append("]]></disc_amt>\r\n");

						valueXmlString.append("<cust_doc_amt><![CDATA[").append(round(rcpAmt, 2)).append("]]></cust_doc_amt>\r\n");
						valueXmlString.append("<disc_appr><![CDATA[").append(round(discAmt, 2)).append("]]></disc_appr>\r\n");
						valueXmlString.append("<fin_chg><![CDATA[").append(round(discAmt, 2)).append("]]></fin_chg>\r\n");
					}
					//Added By manoj on 07/02/2013 to reset value while ref_no found null
					System.out.println("Set net Amount=0");
					if(!isFound)
					{
						System.out.println("isFound set value zero");
						valueXmlString.append("<tot_amt><![CDATA[").append(0).append("]]></tot_amt>\r\n");
						//valueXmlString.append("<cust_doc_amt><![CDATA[").append(0).append("]]></cust_doc_amt>\r\n");
						valueXmlString.append("<fin_chg><![CDATA[").append(0).append("]]></fin_chg>\r\n");
						valueXmlString.append("<rcp_amt><![CDATA[").append(0).append("]]></rcp_amt>\r\n");
						valueXmlString.append("<bal_amt><![CDATA[").append(0).append("]]></bal_amt>\r\n");
						
					}

				}
				else if ( currentColumn.trim().equalsIgnoreCase( "rcp_amt" ) &&  ( "A".equalsIgnoreCase( updateFlag )  ) )
				{
					custDocAmt = Double.parseDouble(genericUtility.getColumnValue("rcp_amt",currDom)==null?"0":genericUtility.getColumnValue("rcp_amt",currDom));
					valueXmlString.append("<cust_doc_amt><![CDATA[").append(round(custDocAmt, 3)).append("]]></cust_doc_amt>\r\n");

				}
				else if ( currentColumn.trim().equalsIgnoreCase( "fin_chg" ) &&  ( "A".equalsIgnoreCase( updateFlag )  ) )
				{
					discAppr = Double.parseDouble(genericUtility.getColumnValue("fin_chg",currDom)==null?"0":genericUtility.getColumnValue("fin_chg",currDom));
					valueXmlString.append("<disc_appr><![CDATA[").append(round(discAppr, 3)).append("]]></disc_appr>\r\n");
				}
				else if ( currentColumn.trim().equalsIgnoreCase( "rcp_amt" ) &&  ( "E".equalsIgnoreCase( updateFlag )  ) )
				{
					custDocAmt = Double.parseDouble(genericUtility.getColumnValue("cust_doc_amt",currDom)==null?"0":genericUtility.getColumnValue("cust_doc_amt",currDom));
					rcpAmt = Double.parseDouble(genericUtility.getColumnValue("rcp_amt",currDom)==null?"0":genericUtility.getColumnValue("rcp_amt",currDom));
					discAppr = Double.parseDouble(genericUtility.getColumnValue("disc_appr",currDom)==null?"0":genericUtility.getColumnValue("disc_appr",currDom));

					finChg =   custDocAmt + discAppr -rcpAmt  ;

					System.out.println("@@@@@3 :finChg["+finChg+"] = custDocAmt["+custDocAmt+"] + discAppr["+discAppr+" - rcpAmt["+rcpAmt+"]");
					valueXmlString.append("<fin_chg><![CDATA[").append(round(finChg, 3)).append("]]></fin_chg>\r\n");
				}
				else if ( currentColumn.trim().equalsIgnoreCase( "fin_chg" ) &&  ( "E".equalsIgnoreCase( updateFlag )  ) )
				{
					discAppr = Double.parseDouble(genericUtility.getColumnValue("disc_appr",currDom)==null?"0":genericUtility.getColumnValue("disc_appr",currDom));
					finChg = Double.parseDouble(genericUtility.getColumnValue("fin_chg",currDom)==null?"0":genericUtility.getColumnValue("fin_chg",currDom));
					custDocAmt = Double.parseDouble(genericUtility.getColumnValue("cust_doc_amt",currDom)==null?"0":genericUtility.getColumnValue("cust_doc_amt",currDom));

					rcpAmt = custDocAmt  + discAppr - finChg;

					System.out.println("@@@@@4 :rcpAmt["+rcpAmt+"] = custDocAmt["+custDocAmt+"] + discAppr["+discAppr+" - finChg["+finChg+"]");		
					valueXmlString.append("<rcp_amt><![CDATA[").append(round(rcpAmt, 3)).append("]]></rcp_amt>\r\n");

				}
				else if(currentColumn.trim().equalsIgnoreCase( "bal_amt_reqd" ))
				{
					System.out.println("Setting Cumulative Balance Amount to xml"); 
					balAmtReqd=checkNull(genericUtility.getColumnValue("bal_amt_reqd",currDom));
					if("Y".equalsIgnoreCase(balAmtReqd))
					{
						chequeAmt = Double.parseDouble(genericUtility.getColumnValue("chq_amt",hdrDom)== null? "0":genericUtility.getColumnValue("chq_amt",hdrDom));

						System.out.println("cheq amt="+chequeAmt);

						parentNodeList = allDom.getElementsByTagName("Detail2");
						parentNodeListLength = parentNodeList.getLength();
						//Commented by Manoj dtd 08/02/2013 not to calculate comm bal amt 
						for(int ctr = 0; ctr < parentNodeListLength ; ctr++ )
						{
							System.out.println("TEST LENGTH="+parentNodeListLength);
							parentNode = parentNodeList.item(ctr);
							//
							childNodeList = parentNode.getChildNodes();
							childNodeListLength = childNodeList.getLength();
							for(ctr2 = 0; ctr2 < childNodeListLength; ctr2++)
							{
								childNode = childNodeList.item(ctr2);
								if( childNode != null )
								{
									childNodeName = childNode.getNodeName();
									if ("attribute".equalsIgnoreCase(childNodeName)) 
									{
										updateFlag1 = childNode.getAttributes().getNamedItem("updateFlag").getNodeValue()== null ? "":childNode.getAttributes().getNamedItem("updateFlag").getNodeValue();
										break;
									}
								}
							}

							//
							//rcpAmt = Double.parseDouble(genericUtility.getColumnValue("rcp_amt", allDom, "2")== null?"0":genericUtility.getColumnValue("rcp_amt", allDom, "2"));
							//discAmt = Double.parseDouble(genericUtility.getColumnValue("fin_chg", allDom, "2")== null?"0":genericUtility.getColumnValue("fin_chg", allDom, "2"));
							rcpAmt = Double.parseDouble(genericUtility.getColumnValueFromNode("rcp_amt",allDom.getElementsByTagName("Detail2").item(ctr))== null?"0":genericUtility.getColumnValueFromNode("rcp_amt",allDom.getElementsByTagName("Detail2").item(ctr)));
							discAmt = Double.parseDouble(genericUtility.getColumnValueFromNode("fin_chg",allDom.getElementsByTagName("Detail2").item(ctr)) == null?"0":genericUtility.getColumnValueFromNode("fin_chg",allDom.getElementsByTagName("Detail2").item(ctr)));

							if(!("D".equalsIgnoreCase(updateFlag1)))
							{
								chequeAmt = chequeAmt - (rcpAmt + discAmt);
							}
							System.out.println("@@@@ cheq amt="+chequeAmt+"  rcp amt="+rcpAmt+"  disc amt="+discAmt+"      updateFlag1="+updateFlag1);

						}
						commAmt = chequeAmt;
						//commAmt = chequeAmt - (rcpAmt - discAmt);
						System.out.println("comm amt="+commAmt);
						System.out.println("in decimeal="+round(commAmt, 3));

						valueXmlString.append("<comm_bal_amt><![CDATA[").append(round(commAmt, 3)).append("]]></comm_bal_amt>\r\n");
					}
				}
				// added by cpatil on 21/12/12 end

				
				valueXmlString.append( "</Detail2>\r\n" );
				System.out.println("valueXmlString---"+valueXmlString);
			}
			break;

			}

		}//End of TRY itemChanged 
		catch(Exception e)
		{
			System.out.println( "Exception :CRemittanceTrEJB :itemChanged(Document,String):" + e.getMessage() + ":" );
			valueXmlString = valueXmlString.append( genericUtility.createErrorString( e ) );
			throw new ITMException(e);

		}//End of Catch
		finally
		{
			try
			{
				if( rSet != null )
				{
					rSet.close();
					rSet = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( connObject != null && ! connObject.isClosed() )
				{
					connObject.close();
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :CRemittanceTrEJB:itemChanged :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}//End of Finally
		valueXmlString.append( "</Root>\r\n" );	
		System.out.println(valueXmlString.toString()+"  Parsing String");
		Document tempdom=genericUtility.parseString(valueXmlString.toString());
		System.out.println( "\n****ValueXmlString :" + valueXmlString.toString() + ":********" );
		return valueXmlString.toString();
	}

	private String errorType(Connection conn, String errorCode) throws ITMException
	{
		String msgType = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String sql = "SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, errorCode);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}

		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return msgType;
	}
	//To check Null String
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	
	private double round(double round,int scale) throws ITMException
	{
		return Math.round(round*Math.pow(10, scale))/Math.pow(10, scale);
	}
	private String getCurrentUpdateFlag(Node currDetail)
	{
		NodeList currDetailList = null;
		String updateStatus = "",nodeName = "";
		int currDetailListLength = 0;

		currDetailList = currDetail.getChildNodes();
		currDetailListLength = currDetailList.getLength();
		for (int i=0;i< currDetailListLength;i++)
		{
			nodeName = currDetailList.item(i).getNodeName();
			if (nodeName.equalsIgnoreCase("Attribute"))
			{
				updateStatus =currDetailList.item(i).getAttributes().getNamedItem("updateFlag").getNodeValue();
				break;
			}
		}
		return updateStatus;
	}
	private int calcDiff(java.util.Date a,java.util.Date b)
	{
		int tempDifference = 0;
		int difference = 0;
		Calendar earlier = Calendar.getInstance();
		Calendar later = Calendar.getInstance();
		try
		{
			if (a.compareTo(b) < 0)
			{
				earlier.setTime(a);
				later.setTime(b);
			}
			else
			{
				earlier.setTime(b);
				later.setTime(a);
			}

			while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
			{
				tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
				difference += tempDifference;

				earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
			}

			if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
			{
				tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
				difference += tempDifference;

				earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return difference;
	}
	public double doublevalue(String str) {
		
		if (str == null || str.trim().length() == 0) { return 0.0D; }
		else
		{
			return Double.parseDouble(str);
		}
	}
	
	

	private HashMap calcDiscount( String refNo , java.util.Date tranDate ,double receiptAmount, Connection conn) throws  ITMException, RemoteException
	{

		PreparedStatement pstmt = null ,pstmt1 = null;
		ResultSet rs = null ,rs1 = null; 
		String sql = "";
		String crTerm = "";
		int dayDiff = 0;
		double discount = 0, discAmt = 0;
		java.util.Date discountDate = null;
		java.util.Date  effDate = null;
		java.util.Date refDate1 = null;
		HashMap map = new HashMap() ;
		try
		{			
			/*if(refNoCust != null && refNoCust.trim().length()  > 0)
			{
				temprefNo = refNoCust;
			} else if(refNo != null && refNo.trim().length()  > 0)
			{
				temprefNo = refNo;
			}*/
			if(refNo != null && refNo.trim().length()  > 0)
			{
				sql ="SELECT TRAN_SER,discount_dt, discount,eff_date,cr_term, ref_date FROM RECEIVABLES WHERE  ref_no = ?" ;
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1,refNo);
				rs = pstmt.executeQuery();
				if( rs .next() )
				{
					discountDate = rs.getDate( "discount_dt" );
					refDate1 = rs.getDate( "ref_date" );
					effDate = rs.getDate( "eff_date" );
					crTerm = rs.getString( "cr_term" )==null?"":rs.getString("cr_term");
					//refNo = rs.getString( "ref_no" )==null?"":rs.getString("ref_no");
					
					if(effDate==null)
						effDate = refDate1;

					if(discountDate == null)
						discountDate = refDate1;
					dayDiff = calcDiff(discountDate,new java.util.Date());


					//System.out.println("dayDiff----"+dayDiff);
					sql = "select FIN_CHG from crtermfc where "+dayDiff+" between min_day and max_day and cr_term=? ";
					pstmt1 = conn.prepareStatement(sql);
					pstmt1.setString(1,crTerm);
					rs1= pstmt1.executeQuery();
					if( rs1.next() )
					{
						discount = rs1.getDouble("FIN_CHG");
					}
					rs1.close();
					rs1=null;
					pstmt1.close();
					pstmt1 = null;

					System.out.println("@@@@@@@@@@@receiptAmount["+receiptAmount+"]::::::discount["+discount+"]multply:::["+ (receiptAmount* discount)/100+"]");
					System.err.println("value of dates "+tranDate+"@@@"+effDate+"@@@"+discountDate);
					//if(tranDate != null  && tranDate.compareTo(discountDate) <= 0 )//change done by kunal 13/04/13,remove cond. for effDate as per KB Sir.
					//{
						//System.err.println("pass dates condition "+tranDate+""+effDate+""+discountDate);
						if(discount > 0.0)
						{
							discAmt =  (receiptAmount* discount)/100;
							//discAmt=roundVal(discAmt,2);
						}
					//}
					discAmt=-1*discAmt;
					
				}
				rs.close();
				rs=null;
				pstmt.close();
				pstmt=null;
			}
			map.put("disc_amt", discAmt);
			map.put("discount_dt", discountDate);       
			
		}
		catch(Exception e)
		{
			System.out.println("Exception in calcDiscount ");
			e.printStackTrace();
			throw new ITMException(e); 
		}
		System.out.println("returning String from calcDiscount "+map.toString());
		return map;
	}
	
	
	
	/*
	private boolean isDulplicateFrmDom(Document dom,String refNo, String lineNo,String refSer) throws ITMException
    {
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;

		String lineNoDom = "";
		boolean isDulplicate = false;
		String refNoDom= "",refSerDom="";
		System.out.println("---inside isDulplicateFrmDom--");
		try
		{

			parentList = dom.getElementsByTagName("Detail2");
			int parentNodeListLength = parentList.getLength();
			System.out.println("parentNodeListLength :"+parentNodeListLength);
			for (int prntCtr = parentNodeListLength; prntCtr > 0; prntCtr-- )
			{	
				parentNode = parentList.item(prntCtr-1);
				childList = parentNode.getChildNodes();
				System.out.println("child length :"+childList.getLength());
				for (int ctr = 0; ctr < childList.getLength(); ctr++)
				{
					childNode = childList.item(ctr);
					
					if(childNode != null &&  childNode.getNodeName().equalsIgnoreCase("attribute"))
					{
						String updateFlag = "";
						updateFlag = childNode.getAttributes().getNamedItem("updateFlag").getNodeValue();
						if (updateFlag.equalsIgnoreCase("D"))
						{
							System.out.println("Break from here as the record is deleted");
							break;
						}
					}	
					if ( childNode != null && childNode.getFirstChild() != null &&  
					childNode.getNodeName().equalsIgnoreCase("line_no") )
					{
						lineNoDom = childNode.getFirstChild().getNodeValue().trim();
						System.out.println("lineNo["+lineNo+"]lineNoDom["+lineNoDom+"]");
						if (lineNo.equalsIgnoreCase(lineNoDom))
						{
							System.out.println("Break from here as line No match");
							refNo="";
							refSer="";
							break;
						}	
					}

					if ( childNode != null && childNode.getFirstChild() != null &&  
					childNode.getNodeName().equalsIgnoreCase("REF_NO") )
					{
						refNoDom = childNode.getFirstChild().getNodeValue().trim();
						System.out.println("refNoDom :"+refNoDom);
					}
					if ( childNode != null && childNode.getFirstChild() != null &&  
							childNode.getNodeName().equalsIgnoreCase("ref_ser") )
							{
								refSerDom = childNode.getFirstChild().getNodeValue().trim();
								System.out.println("refSerDom :"+refSerDom);
							}
					
				}
				System.out.println("refSer :"+refSer+"&refSerDom :"+refSerDom);
				System.out.println("refNo :"+refNo+"&refNoDom :"+refNoDom);
				if (refSer.trim().equalsIgnoreCase(refSerDom.trim())  && refNo.trim().equalsIgnoreCase(refNoDom.trim()) )
				{
					System.out.println("inside!!!!!!");
					isDulplicate = true;
					break;
				}
				
			}//for loop
			
		
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}	
		System.out.println("isDulplicate>>>>>> ["+isDulplicate+"]");
		return isDulplicate;
	}
	
	*/
	public boolean isDulplicateFrmDom() throws ITMException
    {
		boolean isDulplicate=false;
		String refNoDom="";
		Node childNode = null;
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		String refNo1="";
		 Document domTest = null;
		 int detailsLen=0;
		 String ref3="",lineNo1="",updateFlag="";
		
		try
		{
			System.out.println("===========isDulplicateFrmDom=!!!===============");
		
			ArrayList<String> refList =  new ArrayList<String>();
			System.out.println("@@@@@@@@@@@@@@@@"+allXmlDataStr1);
			domTest = parseString(allXmlDataStr1);
			detailsLen=domTest.getElementsByTagName("Detail2").getLength(); 
			System.out.println("detailsLen "+detailsLen);
			for(int i=0 ; i<detailsLen ; i++)
			{
				
				ref3=e12GenericUtility.getColumnValueFromNode("ref_no", domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("ref3 :"+ref3 + " i "+i);
				lineNo1=e12GenericUtility.getColumnValueFromNode("line_no", domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("lineNo1 :"+lineNo1);
				updateFlag = getCurrentUpdateFlag(domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("updateFlag :"+updateFlag+" i :"+i);
				System.out.println(ref3.length());
				if("D".equalsIgnoreCase(updateFlag))
				{
					refList.remove(ref3.trim());
				}
				else
				{
					refList.add(ref3.trim());	
				}
				
				
				
			}
			
			for (String value : refList) {
			      System.out.println("Value = " + value);
			    } 
			boolean flag = checkDuplicate(refList);
			if(flag)
			{
				isDulplicate=false;
			}
			else
			{
				isDulplicate=true;
			}
			System.out.println("flag !!"+isDulplicate);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			isDulplicate=false;
		}
		System.out.println("isDulplicate :"+isDulplicate);
		return isDulplicate;
		
    }
	
	//checkAccValidation
	
	
    /*--------------------------------------------------------------------------------------*/
	
/*	public boolean checkAccValidation(Connection conn) throws ITMException
	{
		boolean flag=false;
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Document domTest = null;
		int detailsLen=0;
		PreparedStatement pstmt = null;
		ResultSet rSet = null;
		double rcpAmt=0.0,chqAmt=0.0,totRcpAmt=0.0;
		String updateFlag="",refNo="",refSer="",sql="";
			
		try
		{
			System.out.println("========checkAccValidation========");
			domTest = parseString(allXmlDataStr1);
			detailsLen=domTest.getElementsByTagName("Detail2").getLength(); 
			System.out.println("detailsLen "+detailsLen);
			for(int i=0 ; i<detailsLen ; i++)
			{
				updateFlag = getCurrentUpdateFlag(domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("updateFlag :"+updateFlag+" i :"+i);
				refNo=e12GenericUtility.getColumnValueFromNode("ref_no", domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("refNo :"+refNo);
				refSer=e12GenericUtility.getColumnValueFromNode("ref_ser", domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("refSer :"+refSer);
				refSer=e12GenericUtility.getColumnValueFromNode("line_no_ref", domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("refSer :"+refSer);
				
				sql ="select (tot_amt - adj_amt) as amt , tran_ser,tran_date,ref_no,ref_date,curr_code,exch_rate,acct_code,   cctr_code,due_date,tax_amt,tot_amt,cust_code,adj_amt,   case when bad_debt_amt is null then 0 else bad_debt_amt end,discount_dt,DISCOUNT     from receivables  "
						+ "  where tran_ser = ? and ref_no = ?     and line_no__ref = ?  " ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,checkNull(refSer));
				pstmt.setString(2,checkNull(refNo));
				pstmt.setString(3,checkNull());
				rSet = pstmt.executeQuery();
				if (rSet.next())
				{
					
					rcpAmt=rSet.getDouble(1);
					isFound=true;
				}
				rSet.close();
				rSet=null;
				pstmt.close();
				pstmt=null;
				
				
				
				
				
				rcpAmt= Double.parseDouble(e12GenericUtility.getColumnValueFromNode("rcp_amt", domTest.getElementsByTagName("Detail2").item(i)));
				System.out.println("rcpAmt :"+rcpAmt);
				
				
				
				
				
				
				
				if("D".equalsIgnoreCase(updateFlag))
				{
					totRcpAmt=totRcpAmt-rcpAmt;
				}
				else
				{
					totRcpAmt = totRcpAmt + rcpAmt;
				}
			}
			System.out.println("totRcpAmt :"+totRcpAmt);
			
			if(chqAmt < totRcpAmt)
			{
				flag=true;
			}
			
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
		return flag;
		
	}*/

	
	
	/*---------------------------------------------------------------------------------------*/
	
	
	
	public boolean checkAmtvalidation(Document dom1) throws ITMException
	{
		boolean flag=false;
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		 Document domTest = null;
		 int detailsLen=0;
		 double rcpAmt=0.0,chqAmt=0.0,totRcpAmt=0.0;
		 String updateFlag="";
			
		try
		{
			System.out.println("========checkAmtvalidation========");
			domTest = parseString(allXmlDataStr1);
			detailsLen=domTest.getElementsByTagName("Detail2").getLength(); 
			System.out.println("detailsLen "+detailsLen);
			chqAmt=Double.parseDouble(this.genericUtility.getColumnValue("chq_amt", dom1));
			System.out.println("chqAmt :"+chqAmt);
			for(int i=0 ; i<detailsLen ; i++)
			{
				updateFlag = getCurrentUpdateFlag(domTest.getElementsByTagName("Detail2").item(i));
				System.out.println("updateFlag :"+updateFlag+" i :"+i);
				rcpAmt= Double.parseDouble(e12GenericUtility.getColumnValueFromNode("rcp_amt", domTest.getElementsByTagName("Detail2").item(i)));
				System.out.println("rcpAmt :"+rcpAmt);
				if("D".equalsIgnoreCase(updateFlag))
				{
					totRcpAmt=totRcpAmt-rcpAmt;
				}
				else
				{
					totRcpAmt = totRcpAmt + rcpAmt;
				}
			}
			System.out.println("totRcpAmt :"+totRcpAmt);
			
			if(chqAmt < totRcpAmt)
			{
				flag=true;
			}
			
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
		return flag;
		
	}

	
	public boolean checkDuplicate(ArrayList list) {
		 HashSet set = new HashSet();
		 for (int i = 0; i < list.size(); i++) {
		  boolean val = set.add(list.get(i));
		  if (val == false) {
		  	return val;
		  }
		 }
		 return true;
		}
	
	 public static boolean isNumeric(String str)  
	 {  
	   try  
	   {  
	     double d = Double.parseDouble(str);  
	   }  
	   catch(NumberFormatException nfe)  
	   {  
	     return false;  
	   }  
	   return true;  
	 }
	
}


