/**
 DEVELOPED BY RITESH TIWARI ON 09/12/13 
 PURPUSE : GENERATE CONFIRM JV FROM AUTO ACCT BALANCE TRF(FI2LSUN010) */

package ibase.webitm.ejb.fin;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class AcctBalTransPrc extends ProcessEJB implements AcctBalTransPrcLocal,AcctBalTransPrcRemote 
{
	static
	{
		System.out.println("-- AcctBalTransPrc compiled -- ");
	}
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retStr = "";
		try
		{				
			System.out.println("xmlString[process]::::::::::;;;"+xmlString);
			System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
			System.out.println("windowName[process]::::::::::;;;"+windowName);
			System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		try
		{	
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :WoTransferPrc :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
		}
		return retStr;
	
	} //end of confirm method
	public String process(Document dom, Document dom2, String windowName,String xtraParams) throws RemoteException, ITMException 
	{
		System.out.println("AcctBalTransPrc process called........");
		String errString = "";
		Connection conn = null;
		ConnDriver connDriver = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		GenericUtility genericUtility = null;
		String empCode="",trandate="",siteCodeFr="",siteCodeTo="";
		String finEntity="",sql="",siteCodeAcct="";
		int cnt=0;
		try
		{
			genericUtility = new GenericUtility();
			itmDBAccessEJB = new ITMDBAccessEJB();
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;            			
			conn.setAutoCommit(false);
			empCode = checkNull(genericUtility.getColumnValue("emp_code", dom));
			trandate = checkNull(genericUtility.getColumnValue("eff_date", dom));
			siteCodeFr = checkNull(genericUtility.getColumnValue("site_code__fr", dom));
			siteCodeTo = checkNull(genericUtility.getColumnValue("site_code__to", dom));
			if(empCode ==null || empCode.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VPEMPCD1    ","","",conn);
				return errString;
			}
			if(trandate ==null || trandate.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VPDATE1    ","","",conn);
				return errString;
			}
			if(siteCodeFr ==null || siteCodeFr.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VPSTCDFR1    ","","",conn);
				return errString;
			}
			if(siteCodeTo ==null || siteCodeTo.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VPSTCDTO1    ","","",conn);
				return errString;
			}
			if(empCode !=null && empCode.trim().length() > 0)
			{
				sql = "select count(1) from employee where emp_code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, empCode);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt = rs.getInt(1);
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				if(cnt==0)
				{
					errString = itmDBAccessEJB.getErrorString("","VPEMPCD2    ","","",conn);
					return errString;
				}
			}
			if(siteCodeFr !=null && siteCodeFr.trim().length() > 0)
			{
				sql = "select COUNT(1) from site where site_code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, siteCodeFr);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt = rs.getInt(1);
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				if(cnt==0)
				{
					errString = itmDBAccessEJB.getErrorString("","VPSTCDFR2    ","","",conn);
					return errString;
				}
			}
			if(siteCodeTo !=null && siteCodeTo.trim().length() > 0)
			{
				sql = "select COUNT(1) from site where site_code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, siteCodeTo);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt = rs.getInt(1);
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				if(cnt==0)
				{
					errString = itmDBAccessEJB.getErrorString("","VPSTCDTO2    ","","",conn);
					return errString;
				}
			}
			if(siteCodeFr.trim().length() > 0 && siteCodeTo.trim().length() > 0)
			{
				sql = "select fin_entity,site_code__acct from site where site_code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, siteCodeFr);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					finEntity = rs.getString("fin_entity");
					siteCodeAcct = rs.getString("site_code__acct");
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				
				sql = "select COUNT(1) from site where site_code = ? AND fin_entity = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, siteCodeTo);
				pstmt.setString(2, finEntity);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt = rs.getInt(1);
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				if(cnt==0)
				{
					errString = itmDBAccessEJB.getErrorString("","VTSTCD1","","",conn);
					return errString;
				}
				sql = "select COUNT(1) from site where site_code = ? AND site_code__acct = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, siteCodeTo);
				pstmt.setString(2, siteCodeAcct);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt = rs.getInt(1);
 				}
				if(rs != null)
					rs.close();
				rs = null;
				if(pstmt != null)
					pstmt.close();
				pstmt = null;
				if(cnt > 0)
				{
					//errString = itmDBAccessEJB.getErrorString("","VTSTCD2","","",conn);
					//return errString;
				}
			}
			if(errString == null || errString.trim().length() == 0)
			{
				System.out.println(" method calling ....");
				errString = createJurnalVouchar(empCode,siteCodeFr,siteCodeTo,trandate,finEntity,xtraParams,conn);
			}
			if((errString != null ) &&  (errString.indexOf("Success") > -1 || errString.indexOf("confirmed") >-1))
			{
				conn.commit();
				System.out.println("--process completed--");
				errString = itmDBAccessEJB.getErrorString("","VPSUCC1    ","","",conn);
			}
			else 
			{
				conn.rollback();
				System.out.println("--process not completed--");
				errString = itmDBAccessEJB.getErrorString("","VTPRCERR ","","",conn);
			}
		}
		catch( Exception e)
		{			
				try 
				{
					conn.rollback();
				} 
				catch (SQLException ex) 
				{
					Logger.getLogger(AcctBalTransPrc.class.getName()).log(Level.SEVERE, null, ex);
				}
				e.printStackTrace();
		}
		finally
		{		
				try
				{
					if(errString != null && errString.trim().length() > 0)
					{
						if(errString.indexOf("VPSUCC1") > -1 )
						{
							conn.commit();
							System.out.println("--transaction commited--");
						}
						else
						{
							conn.rollback();
							System.out.println("--transaction rollback--");
						}
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;					
					}		
					if( conn != null && ! conn.isClosed() )
					{
						conn.close();
						conn = null;
					}
					
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
				}
				catch(Exception e)
				{
					System.out.println("Exception : "+e);e.printStackTrace();
					throw new ITMException(e);
				}
			}
		return errString;
	}
	private String createJurnalVouchar(String empCode,String siteCodeFr,String siteCodeTo,String trandate,String finEntity,String xtraParams,Connection conn) throws RemoteException, ITMException
	{	
		String  userId = "";
		String  termId = "";
		String chgTerm="",chgUser="",linkType="";
		String sql = "", currCode ="";
		String acctCodePay= "", cctrCodePay="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		GenericUtility genericUtility = null;
		Timestamp currDate = null;
		String retString  = null;
		String balanceTRf="";
		String xmlString = "";
		StringBuffer xmlBuff = null;
		int lineNo=0;
		double amount =0,totAmt=0;
		String linenostr="";
		String prdCode = "",acctPrd = "";
		java.util.Date dateFr = null;
		try   
		{
			System.out.println("@@@@@@@ wostock trans.  function called::");
			xmlBuff = new StringBuffer();
			genericUtility = GenericUtility.getInstance();
			FinCommon finCom = new FinCommon();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
			currDate =  java.sql.Timestamp.valueOf(sdf1.format(new java.util.Date()).toString() + " 00:00:00.0");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");  System.out.println("--login code--"+userId);
			chgTerm =  genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId"); System.out.println("--term id--"+termId);
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");System.out.println("--term id--"+termId);
			dateFr = genericUtility.getDateObject(trandate);
		
			sql = "select  curr_code from finent where fin_entity = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, finEntity);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				currCode = checkNull(rs.getString("curr_code"));
				}
			if(rs != null)
				rs.close();
			rs = null;
			if(pstmt != null)
				pstmt.close();
			pstmt = null;
			
			sql =" select acct_code__pay, cctr_code__pay,link_type  "
					+" from ibca_pay_ctrl "
					+" where site_code__from 	= ? "
					+" and	site_code__to  = ? " ; 
			
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1,siteCodeFr);
			pstmt.setString(2,siteCodeTo);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				acctCodePay = checkNull(rs.getString(1));
				cctrCodePay = checkNull(rs.getString(2));
				linkType = checkNull(rs.getString(3));
			}
			
			if(rs != null)
				rs.close();
			rs = null;
			if(pstmt != null)
				pstmt.close();
			pstmt = null;
			
		    System.out.println("::: XML Cretation::::");
			
			xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
			xmlBuff.append("<DocumentRoot>");
			xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
			xmlBuff.append("<group0>");
			xmlBuff.append("<description>").append("Group0 description").append("</description>");
			xmlBuff.append("<Header0>");
			xmlBuff.append("<objName><![CDATA[").append("journal").append("]]></objName>");  
			xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlBuff.append("<description>").append("Header0 members").append("</description>");		
			xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"journal\" objContext=\"1\">");  
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<tran_id/>");
			
			xmlBuff.append("<tran_date><![CDATA["+ trandate+"]]></tran_date>");
			
			xmlBuff.append("<eff_date><![CDATA[" + trandate +"]]></eff_date>");
			
			xmlBuff.append("<tran_type><![CDATA[TRF]]></tran_type>");
			
			xmlBuff.append("<site_code><![CDATA["+ siteCodeFr +"]]></site_code>");
			
			xmlBuff.append("<site_code__rev><![CDATA[" + siteCodeTo  +"]]></site_code__rev>");
			
			xmlBuff.append("<remarks><![CDATA["+ empCode+" balance TRF "+ siteCodeFr +" to "+ siteCodeTo+"]]></remarks>");
			
			xmlBuff.append("<reversible><![CDATA[Y]]></reversible>");
			
			xmlBuff.append("<curr_code><![CDATA["+ currCode +"]]></curr_code>");
			
			xmlBuff.append("<rev_date><![CDATA[" + trandate+ "]]></rev_date>");
			
			xmlBuff.append("<auto_rev><![CDATA[Y]]></auto_rev>");
			
			xmlBuff.append("<status><![CDATA[A]]></status>");

			xmlBuff.append("<fin_entity><![CDATA["+ finEntity +"]]></fin_entity>");
			
			xmlBuff.append("<chg_date><![CDATA["+ sdf.format(currDate).toString() +"]]></chg_date>");

			xmlBuff.append("<chg_user><![CDATA["+ chgUser +"]]></chg_user>");

			xmlBuff.append("<chg_term><![CDATA["+ chgTerm +"]]></chg_term>");
			
			xmlBuff.append("<link_type><![CDATA["+ linkType +"]]></link_type>");
			xmlBuff.append("<site_code__for><![CDATA[]]></site_code__for>");
			xmlBuff.append("</Detail1>");
		
			sql = "select acct_prd as acct_prd ,code  as prd_code from period where ? between fr_date and to_date ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setDate(1,new java.sql.Date(dateFr.getTime()));
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				acctPrd = checkNull(rs.getString("acct_prd"));
				prdCode = checkNull(rs.getString("prd_code"));
			}
			if(rs != null)
				rs.close();
			rs = null;
			if(pstmt != null)
				pstmt.close();
			pstmt = null;
			//sql = "select ACCT_CODE,CCTR_CODE,CR_AMT__BASE,DR_AMT__BASE,DR_AMT,CR_AMT,ADV_AMT,SITE_CODE from sundrybal where sundry_code = ? and sundry_type ='E'";
		    sql = "SELECT SITE_CODE, ACCT_CODE, ACCT_DESCR, "+
		           " CASE WHEN ((SUM(OP_DR_AMT) + SUM(PRD_DR_AMT)) - (SUM(OP_CR_AMT) + SUM(PRD_CR_AMT))) IS NULL THEN 0 ELSE ((SUM(OP_DR_AMT) + SUM(PRD_DR_AMT)) - (SUM(OP_CR_AMT) + SUM(PRD_CR_AMT))) END AS NET_BAL, "+
		           " ACCT_PRD,PRD_CODE_UPTO,CITY,finent,rtrim(SUNDRY_TYPE) AS SUNDRY_TYPE, SUNDRY_CODE,cctr_code "+
				   " FROM "+
				   " ( "+
				   		" SELECT  SUNDRYBAL.SITE_CODE AS SITE_CODE, "+
		                   " SUNDRYBAL.ACCT_CODE AS ACCT_CODE, "+
		                   " ACCOUNTS.DESCR AS ACCT_DESCR, "+
		                   " CASE WHEN SUM(NVL(SUNDRYBAL.DR_AMT__BASE,0)) - SUM(NVL(SUNDRYBAL.CR_AMT__BASE,0)) > 0 THEN SUM(NVL(SUNDRYBAL.DR_AMT__BASE,0)) - SUM(NVL(SUNDRYBAL.CR_AMT__BASE,0)) ELSE 0 END AS OP_DR_AMT, "+
		                   " CASE WHEN SUM(NVL(SUNDRYBAL.DR_AMT__BASE,0)) - SUM(NVL(SUNDRYBAL.CR_AMT__BASE,0)) < 0 THEN (SUM(NVL(SUNDRYBAL.DR_AMT__BASE,0)) - SUM(NVL(SUNDRYBAL.CR_AMT__BASE,0))) * -1 ELSE 0 END AS OP_CR_AMT, "+
		                   " 0 AS PRD_DR_AMT, "+
		                   " 0 AS PRD_CR_AMT, "+
		                   " SUNDRYBAL.ACCT_PRD AS ACCT_PRD, "+
		                   " SUNDRYBAL.PRD_CODE AS PRD_CODE_UPTO, "+
		                   " SITE.CITY, "+
		                   " finent.fin_entity as finent, "+
		                   " SUNDRYBAL.SUNDRY_TYPE AS SUNDRY_TYPE, "+
		                   " SUNDRYBAL.SUNDRY_CODE AS SUNDRY_CODE "+
	                       " ,SUNDRYBAL.cctr_code AS cctr_code "+
					                
				           " FROM " +
				           " SUNDRYBAL,SITE,ACCOUNTS,finent "+
				           
					       " WHERE " +
					       " SUNDRYBAL.SITE_CODE = SITE.SITE_CODE  AND SUNDRYBAL.ACCT_CODE = ACCOUNTS.ACCT_CODE  AND "+
		                   " finent.fin_entity = site.fin_entity and   SUNDRYBAL.ACCT_PRD = ? AND "+ 
		                   " SUNDRYBAL.PRD_CODE = '000000' AND   SUNDRYBAL.PRD_CODE <> 'ZZZZZZ' AND "+
		                   " SUNDRYBAL.SITE_CODE IN (?) AND ACCOUNTS.ACCT_TYPE <> 'O' AND "+
		                   " SUNDRYBAL.SUNDRY_TYPE IN ('E') AND  SUNDRYBAL.ACCT_CODE >= '00' AND "+
		                   " SUNDRYBAL.ACCT_CODE <= 'ZZ' AND "+
		                   " SUNDRYBAL.SUNDRY_CODE = ? "+
		                   
				           " GROUP BY " +
				           " SUNDRYBAL.SITE_CODE, "+
		                   " SUNDRYBAL.ACCT_CODE, "+
		                   " ACCOUNTS.DESCR, "+
		                   " SUNDRYBAL.ACCT_PRD,"+
		                   " SUNDRYBAL.PRD_CODE,"+
		                   " SITE.CITY,"+
		                   " finent.fin_entity,"+
		                   " SUNDRYBAL.SUNDRY_TYPE,"+
		                   " SUNDRYBAL.SUNDRY_CODE "+
		                   " ,SUNDRYBAL.cctr_code "+
		                   
					       "UNION ALL "+
					       "SELECT   SUNDRYBAL.SITE_CODE AS SITE_CODE, "+
		                   " SUNDRYBAL.ACCT_CODE AS ACCT_CODE,"+
		                   " ACCOUNTS.DESCR AS ACCT_DESCR,"+
		                   " 0 AS OP_DR_AMT,"+
		                   " 0 AS OP_CR_AMT,"+
		                   " SUM(NVL(SUNDRYBAL.DR_AMT__BASE,0)) AS PRD_DR_AMT,"+
		                   " SUM(NVL(SUNDRYBAL.CR_AMT__BASE,0)) AS PRD_CR_AMT,"+
		                   " SUNDRYBAL.ACCT_PRD AS ACCT_PRD,"+
		                   " SUNDRYBAL.PRD_CODE AS PRD_CODE_UPTO,"+
		                   " SITE.CITY,"+
		                   " finent.fin_entity as finent,"+
		                   " SUNDRYBAL.SUNDRY_TYPE AS SUNDRY_TYPE,"+
		                   " SUNDRYBAL.SUNDRY_CODE AS SUNDRY_CODE "+
		                   " ,SUNDRYBAL.cctr_code AS cctr_code "+
						  
		                   " FROM " +
						   "SUNDRYBAL,SITE,ACCOUNTS,finent "+
		                   
					       "WHERE " +
					       " SUNDRYBAL.SITE_CODE = SITE.SITE_CODE  AND "+
		                   " SUNDRYBAL.ACCT_CODE = ACCOUNTS.ACCT_CODE  AND "+
		                   " finent.fin_entity = site.fin_entity and  "+    
		                   " SUNDRYBAL.ACCT_PRD = ? AND "+ 
		                   " SUNDRYBAL.PRD_CODE <= ? AND "+
		                   " SUNDRYBAL.PRD_CODE not in ('000000','ZZZZZZ') AND "+
		                   " SUNDRYBAL.SITE_CODE IN (?) AND "+
		                   " ACCOUNTS.ACCT_TYPE <> 'O' AND "+
		                   " SUNDRYBAL.SUNDRY_TYPE IN ('E') AND "+
		                   " SUNDRYBAL.ACCT_CODE >= '00' AND "+
		                   " SUNDRYBAL.ACCT_CODE <= 'ZZ' AND "+
		                   " SUNDRYBAL.SUNDRY_CODE = ? "+
		                   
		                   " GROUP BY " +
		                   " SUNDRYBAL.SITE_CODE, "+
		                   " SUNDRYBAL.ACCT_CODE, SUNDRYBAL.cctr_code, "+
		                   " ACCOUNTS.DESCR, "+ 
		                   " SUNDRYBAL.ACCT_PRD,"+
		                   " SUNDRYBAL.PRD_CODE, "+ 
		                   " SITE.CITY, "+ 
		                   " finent.fin_entity, "+ 
		                   " SUNDRYBAL.SUNDRY_TYPE, "+ 
		                   " SUNDRYBAL.SUNDRY_CODE "+ 
		                   ",SUNDRYBAL.cctr_code "+ 
		             " ) "+ 
					" GROUP BY  "+ 
					" SITE_CODE,ACCT_CODE,ACCT_DESCR, "+ 
					" ACCT_PRD,PRD_CODE_UPTO,CITY,finent,SUNDRY_TYPE,SUNDRY_CODE  ,cctr_code "+ 
					" HAVING (SUM(OP_DR_AMT) <> 0 OR "+ 
					          "SUM(OP_CR_AMT) <> 0 OR "+ 
					          "SUM(PRD_DR_AMT) <> 0 OR "+ 
					          "SUM(PRD_CR_AMT) <> 0 ) "+ 
					" ORDER BY SUNDRY_TYPE,SUNDRY_CODE,ACCT_CODE,SITE_CODE ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, acctPrd);
			pstmt.setString(2, siteCodeFr);
			pstmt.setString(3, empCode);
			pstmt.setString(4, acctPrd);
			pstmt.setString(5, prdCode);
			pstmt.setString(6, siteCodeFr);
			pstmt.setString(7, empCode);
			rs = pstmt.executeQuery();
			boolean flag = false;
			while( rs.next() )
			{
				lineNo++;
				flag = true;
				linenostr = Integer.toString(lineNo);
				amount = rs.getDouble("NET_BAL") ;
				xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"journal\" objContext=\"2\">"); 
				xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				xmlBuff.append("<tran_id/>");
				
				xmlBuff.append("<line_no><![CDATA[" + linenostr +"]]></line_no>");

				xmlBuff.append("<acct_code><![CDATA["+ checkNull(rs.getString("ACCT_CODE")) +"]]></acct_code>");
				
				xmlBuff.append("<cctr_code><![CDATA[ ]]></cctr_code>");
				
				xmlBuff.append("<remarks><![CDATA["+ empCode+" balance TRF "+ siteCodeFr +" to "+ siteCodeTo+"]]></remarks>");
				
				if(amount > 0){
				xmlBuff.append("<drcr_flag><![CDATA[C]]></drcr_flag>");
				
				}else xmlBuff.append("<drcr_flag><![CDATA[D]]></drcr_flag>");	
				
				xmlBuff.append("<sundry_code><![CDATA[" + empCode +"]]></sundry_code>");
				
				xmlBuff.append("<emp_code><![CDATA["   + empCode +"]]></emp_code>");
				
				xmlBuff.append("<sundry_type><![CDATA[E]]></sundry_type>");
				
				xmlBuff.append("<amount><![CDATA["+ (amount < 0 ? -(amount) : amount)+"]]></amount>");

				xmlBuff.append("</Detail2>");	
				totAmt = totAmt + amount;
			}
			
			//for(int i = 0; i< count;i++)
			//{
			if(flag)
			{
				lineNo++;
				linenostr = Integer.toString(lineNo);
				xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"journal\" objContext=\"2\">"); 
				xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				xmlBuff.append("<tran_id/>");
				
				xmlBuff.append("<line_no><![CDATA[" + linenostr +"]]></line_no>");
				
				xmlBuff.append("<acct_code><![CDATA["+ acctCodePay +"]]></acct_code>");
				
				xmlBuff.append("<cctr_code><![CDATA[" + cctrCodePay +"]]></cctr_code>");
				
				xmlBuff.append("<remarks><![CDATA[" + empCode+" "+ balanceTRf +"]]></remarks>");
				
				if(totAmt > 0){
				xmlBuff.append("<drcr_flag><![CDATA[D]]></drcr_flag>");
				
				}else xmlBuff.append("<drcr_flag><![CDATA[C]]></drcr_flag>");	
				
				//xmlBuff.append("<sundry_code><![CDATA[" + empCode +"]]></sundry_code>");
				
				xmlBuff.append("<emp_code><![CDATA["   + empCode +"]]></emp_code>");
				
				xmlBuff.append("<sundry_type><![CDATA[O]]></sundry_type>");
				
				xmlBuff.append("<amount><![CDATA["+ (totAmt < 0 ? -(totAmt) : totAmt)+"]]></amount>");

				xmlBuff.append("</Detail2>");	
			}
			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			
			xmlString = xmlBuff.toString();
			System.out.println("@@@@@2: xmlString :::: "+xmlBuff.toString());
			System.out.println("...............just before savdata() ");
			String siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			System.out.println("== site code == @"+siteCode);
			retString = saveData(siteCode,xmlString,conn);
			System.out.println("@@@@@2: retString: @"+retString);
			System.out.println("--retString finished--");
			String finParm = finCom.getFinparams("999999","TRF_JV_CONF", conn); 
			System.out.println("finParmValue --"+finParm);
			
			if (retString.indexOf("Success") > -1 && "Y".equalsIgnoreCase(finParm.trim()))
			{
				conn.commit();
				System.out.println("@@@@@@3: retString @ ");
				String[] arrayForTranId = retString.split("<TranID>");
				int endIndex = arrayForTranId[1].indexOf("</TranID>");
				String tranIdForIssue = arrayForTranId[1].substring(0,endIndex);
				System.out.println("-tranIdForIssue-"+tranIdForIssue);
				retString = confirmJournalVoucher("journal",tranIdForIssue,xtraParams,conn);
				System.out.println("retString from confirmJV  :: @:: "+retString);//CONFSUCC
				String empCodeAprv  = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
				System.out.println("empCodeAprv : "+empCodeAprv);
				
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			retString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}	
			
			}
			catch(Exception e)
			{
				e.printStackTrace();
				retString = e.getMessage();
				throw new ITMException(e);
			}
		}
		System.out.println("Returning Result [" + retString + "]");
		return retString;
	}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
			System.out.println("--retString - -"+retString);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
	public String confirmJournalVoucher(String businessObj, String tranIdFr,String xtraParams,Connection conn) throws ITMException
	{
		String methodName = "";
		String compName = "";
		String retString = "";
		String serviceCode = "";
		String serviceURI = "";
		String actionURI = "";
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		//System.out.println("confirmJournalVoucher(String businessObj, String tranIdFr,String xtraParams, String forcedFlag, Connection conn) called >>><!@#>");

		try
		{
			//ConnDriver connDriver = new ConnDriver();
			//conn = connDriver.getConnectDB("DriverITM");

			methodName = "gbf_post";
			actionURI = "http://NvoServiceurl.org/" + methodName;

			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'pre_confirm' ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,businessObj);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceCode = rs.getString("SERVICE_CODE");
				compName = rs.getString("COMP_NAME");
			}
			System.out.println("serviceCode = "+serviceCode+" compName "+compName);
			sql = "SELECT SERVICE_URI FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,serviceCode);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceURI = rs.getString("SERVICE_URI");
			}
			System.out.println("serviceURI = "+serviceURI+" compName = "+compName);
			Service service = new Service();
			Call call = (Call)service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(serviceURI));
			call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(actionURI);
			Object[] aobj = new Object[4];

			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tran_id"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "forced_flag"), XMLType.XSD_STRING, ParameterMode.IN);

			aobj[0] = new String(compName);
			aobj[1] = new String(tranIdFr);
			aobj[2] = new String(xtraParams);
			//aobj[3] = new String(forcedFlag);
			//System.out.println("@@@@@@@@@@loginEmpCode:" +genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode")+":");
			System.out.println("@@@@@@ call.setReturnType(XMLType.XSD_STRING) executed........");
			call.setReturnType(XMLType.XSD_STRING);

			retString = (String)call.invoke(aobj);

			System.out.println("Confirm Complete @@@@@@@@@@@ Return string from NVO is:==>["+retString+"]");

		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{		
			try{


				if (pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				/*if( conn != null ){
					conn.close();
					conn = null;
				}*/
			}
			catch(Exception e)
			{
				System.out.println("Exception inCalling confirmed");
				e.printStackTrace();
				try{
					conn.rollback();

				}catch (Exception s)
				{
					System.out.println("Unable to rollback");
					s.printStackTrace();
				}
				throw new ITMException(e);
			}

		}
		return retString;
	}
}