package ibase.webitm.ejb.fin;


import java.util.*;
import java.util.Date;
import java.rmi.RemoteException;
import java.sql.*;


import org.w3c.dom.*;

import java.text.SimpleDateFormat;

import javax.naming.InitialContext;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;

import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.dis.adv.CreatePoVoucherAdvance;
import ibase.webitm.utility.TransIDGenerator;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;

public class MilestonePayGen 
{
	
	String xmlString = "";
	E12GenericUtility e12GenericUtility = new E12GenericUtility();

	public String getXmlData(String xmlString1,HashMap chgMap)throws ITMException
	{
		Document dom = null;
		String xmldata="";
		System.out.println("MilestonePayGen EJB called...");
		try
		{
			System.out.println("getXmlData (MilestonePayGen) xmlString1::::::["+xmlString1+"]@@@@@@@");
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				xmldata = getXmlData(dom,chgMap);
				System.out.println("xmldata :"+xmldata);
			}			
		}
		catch(Exception e)
		{
			System.out.println("Exception :MilestonePayGen ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}

		System.out.println("return xmldata[["+xmldata+"]]");

		return xmldata;
	}


	private String getXmlData(Document dom,HashMap drcrMap)throws ITMException
	{
		PreparedStatement pstmt = null;
		String sql = "",errString="",xtraParams="";  
		GenericUtility genericUtility = GenericUtility.getInstance();
		NodeList hdrDom = null;
		int cnt=0,i=0,domCnt=0;
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver(); 
		String  purcOrder ="",tranIdForVoucher="",relAgnstTerm="",lineNoTerm="", lineNo ="",type ="",relAgnst ="",amtType ="",relAmt ="",relAfter ="",retString1="";
		String  vouchCreated ="",taskCode ="",dueDate ="",adjMethod ="",acctCode ="",cctrCode ="",taxClass ="";
		String  taxChap ="",taxEnv ="",retentionPerc ="",siteCodeAdv ="",adjPerc ="",processDate="",resultString="",chgUser="",chgTerm="";
		boolean issError = false;
		ResultSet rs = null;
		double odtAmt=0.0,totAmt=0.0,calRelAmt=0.0;
		String task[] = null;
		//ArrayList<String> taskList = new ArrayList<String>();
		//ArrayList<String> relAginstList = new ArrayList<String>();
		//ArrayList<String> lineList = new ArrayList<String>();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		
		Date dueDate1=null,processDate1=null;
		long diff=0,datediff=0;
		
		try
		{
			System.out.println("getXmlData inside dom !!!!!!!!");
			SimpleDateFormat sdf1 = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
			conn = connDriver.getConnectDB("DriverITM");

			NodeList hdrDommList = dom.getElementsByTagName("Detail2");
			System.out.println("length of details 2 xml===>["+hdrDommList.getLength()+"]");

			for (int dtlCtr = 0; dtlCtr < hdrDommList.getLength(); dtlCtr++)
			{
				System.out.println("dtlCtr :::"+dtlCtr);
				Node detailListNode = hdrDommList.item(dtlCtr);
				if("Detail2".equalsIgnoreCase(detailListNode.getNodeName()))
				{
					NodeList refrenceList= detailListNode.getChildNodes();
					System.out.println("refrenceList.getLength() :"+refrenceList.getLength());
					for (int cntr1 = 0; cntr1 < refrenceList.getLength(); cntr1++) 
					{
						Node	refrenceNode = refrenceList.item(cntr1); 
						System.out.println("cntr1 :"+cntr1);
						System.out.println("@@@@@@@@ detail2 node :::  refrenceNode.getNodeName()["+ refrenceNode.getNodeName()+"]");

						if("purc_order".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							purcOrder =  refrenceNode.getTextContent();
							System.out.println("purcOrder :"+purcOrder);
						}
						if("line_no".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							lineNo =  refrenceNode.getTextContent();
							System.out.println("lineNo :"+lineNo);
							//lineList.add(lineNo);
						}		
						if("type".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							type =  refrenceNode.getTextContent();
							System.out.println("type :"+type);
						}		
						if("rel_agnst".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							relAgnst =  refrenceNode.getTextContent();
							System.out.println("relAgnst :"+relAgnst);
							//relAginstList.add(relAgnst);
						}		
						if("amt_type".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							amtType =  refrenceNode.getTextContent();
							System.out.println("amtType :"+amtType);
						}		
						if("rel_amt".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							relAmt =  refrenceNode.getTextContent();
							System.out.println("relAmt :"+relAmt);
						}		
						if("rel_after".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							relAfter =  refrenceNode.getTextContent();
							System.out.println("relAfter :"+relAfter);
						}		
						if("vouch_created".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							vouchCreated =  refrenceNode.getTextContent();
							System.out.println("vouchCreated :"+vouchCreated);
						}		
						if("task_code".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							taskCode =  refrenceNode.getTextContent();
							System.out.println("taskCode :"+taskCode);
							//taskList.add(taskCode);
						}		
						if("due_date".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							dueDate =  refrenceNode.getTextContent();
							System.out.println("dueDate :"+dueDate);
						}		
						if("adj_method".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							adjMethod =  refrenceNode.getTextContent();
							System.out.println("adjMethod :"+adjMethod);
						}		
						if("acct_code".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							acctCode =  refrenceNode.getTextContent();
							System.out.println("acctCode :"+acctCode);
						}		
						if("cctr_code".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							cctrCode =  refrenceNode.getTextContent();
							System.out.println("cctrCode :"+cctrCode);
						}		
						if("tax_class".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							taxClass =  refrenceNode.getTextContent();
							System.out.println("taxClass :"+taxClass);
						}		
						if("tax_chap".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							taxChap =  refrenceNode.getTextContent();
							System.out.println("taxChap :"+taxChap);
						}		
						if("tax_env".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							taxEnv =  refrenceNode.getTextContent();
							System.out.println("taxEnv :"+taxEnv);
						}		
						if("retention_perc".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							retentionPerc =  refrenceNode.getTextContent();
							System.out.println("retentionPerc :"+retentionPerc);
						}		
						if("site_code__adv".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							siteCodeAdv =  refrenceNode.getTextContent();
							System.out.println("siteCodeAdv :"+siteCodeAdv);
						}		
						if("adj_perc".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							adjPerc =  refrenceNode.getTextContent();
							System.out.println("adjPerc :"+adjPerc);
						}
						if("process_date".equalsIgnoreCase( refrenceNode.getNodeName()))
						{
							processDate =  refrenceNode.getTextContent();
							System.out.println("adjPerc :"+adjPerc);
						}
					}
					
					
					
				}	//end of IF for 
				
				
				/*----------release amt  based on amt_type---------------*/
				
		
				
				
				sql = "select ord_amt,tot_amt from porder where purc_order= ? " ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, purcOrder);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					odtAmt = rs.getDouble("ord_amt");
					totAmt = rs.getDouble("tot_amt");
				}	
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				
				System.out.println("odtAmt :"+odtAmt);
				System.out.println("tot_amt :"+totAmt);
				/*
				amount=Double.parseDouble(relAmt);
				pentlyAmt=(finChrge * amount)/100;
				System.out.println("Calculated pentlyAmt :"+pentlyAmt);*/
				
				System.out.println("amtType :"+amtType);
				
				if(amtType.equalsIgnoreCase("01"))
				{
					calRelAmt=(odtAmt * Double.parseDouble(relAmt))/100;
				}
				else if(amtType.equalsIgnoreCase("02"))
				{
					calRelAmt=(totAmt * Double.parseDouble(relAmt))/100;
				}
				else
				{
					calRelAmt=Double.parseDouble(relAmt);
				}
				
				System.out.println("calRelAmt :"+calRelAmt);
				
				/*---------------changes done 10-APR-2015------------------------------*/
				
				java.sql.Timestamp today = null;
				java.util.Date date = null;
				today = new java.sql.Timestamp(System.currentTimeMillis());
				java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(genericUtility.getDBDateFormat());
				date = sdf.parse(today.toString());
				today =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");

				System.out.println("purcOrder!!!!!!!!! :"+purcOrder);
				System.out.println("xtraParams!!!!!!!!!! :"+xtraParams);
				System.out.println("today :"+today);
				System.out.println("taskCode!!!!!!!!!!!! :"+taskCode);
				
				//System.out.println("taskList :"+taskList);
				CreatePoVoucherAdvance createVouc11 = new CreatePoVoucherAdvance();
				//System.out.println("taskList size() :"+taskList.size());
				/*-------------Changes done by mahendra dated 27-03-2015---------------------------*/
					
					System.out.println("taskCode :"+taskCode);
					System.out.println("relAgnstTerm :"+relAgnstTerm);
					System.out.println("lineNoTerm :"+lineNoTerm);
					chgUser=(String) drcrMap.get("chg_user");
					chgTerm=(String) drcrMap.get("chg_term");
					System.out.println("chgUser :"+chgUser);
					
					ibase.utility.UserInfoBean	userInfo = new ibase.utility.UserInfoBean();
					System.out.println("userInfo.getEmpCode() :"+userInfo.getEmpCode());
					
					
					//xtraParams = "loginEmpCode="+userInfo.getEmpCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
					xtraParams="loginEmpCode="+userInfo.getEmpCode()+"~~loginCode="+chgUser+"~~termId="+chgTerm+"~~loginSiteCode="+siteCodeAdv;
					//ibase.utility.UserInfoBean userInfo = new ibase.utility.UserInfoBean();
					//userInfo.setLoginCode(chgUser);
					//userInfo.setRemoteHost(chgTerm);
					System.out.println("xtraParams @@@@"+xtraParams);
					
					
					
					errString =  createVouc11.createPoVoucher(purcOrder,xtraParams,conn,"PR", 0,today ,taskCode,relAgnst,lineNo); 
					
					
					System.out.println("errString!!!!!!!!!!"+errString);
					
					if(errString.indexOf("Success") > -1)
					{
					    String[] arrayForTranId = errString.split("<TranID>");
					    int endIndex = arrayForTranId[1].indexOf("</TranID>");
					    tranIdForVoucher = arrayForTranId[1].substring(0,endIndex);
					    System.out.println("tranIdForVoucher-"+tranIdForVoucher);	
					
					    tranIdForVoucher=tranIdForVoucher==null ? "" : tranIdForVoucher.trim();
					    purcOrder=purcOrder==null ? "" : purcOrder.trim();
					    taskCode=taskCode==null ? "" : taskCode.trim();
					    dueDate=dueDate==null ? "" : dueDate.trim();
					    processDate=processDate==null ? "" : processDate.trim();
					  //  relAmt=relAmt==null ? "0.00" : relAmt.trim();
					
					
					    retString1 = confirmTranscation("voucher_adv",tranIdForVoucher,xtraParams,conn);
					    System.out.println("retString1!!!! :"+retString1);
					}
					else
					{
						System.out.println("Voucher not created sucessfully");
						return errString;
					}
					

					if(dueDate.length() > 0)
					{
						dueDate1 = sdf1.parse(dueDate);	
					}
					
					
					if(processDate.length() > 0)
					{
						processDate1 = sdf1.parse(processDate);
					}
					
					if(processDate1 != null && dueDate1 != null)
					{
						
						System.out.println("processDate.getTime() :"+processDate1.getTime());
						System.out.println("dueDate1.getTime() :"+dueDate1.getTime());

						diff = processDate1.getTime() - dueDate1.getTime();
						System.out.println("diff :"+diff);
						datediff = diff / (24 * 60 * 60 * 1000);
					}
					System.out.println("datediff :"+datediff);
					
					if(datediff > 0)
					{
						drcrMap.put("voucher_id", tranIdForVoucher);
						drcrMap.put("purc_order", purcOrder);
						drcrMap.put("task_code", taskCode);
						drcrMap.put("due_date", dueDate);
						drcrMap.put("process_date", processDate);
						drcrMap.put("rel_amt", String.valueOf(calRelAmt));
						drcrMap.put("date_diff", String.valueOf(datediff));
					
						resultString = createDebitNote(drcrMap,conn);
						System.out.println("result :"+resultString);
						
					}
					else
					{
						resultString=errString;
					}
					
					if(resultString.indexOf("Success") > -1)
					{
						System.out.println("Voucher created Successfully["+resultString+"]");
						conn.commit();
						String[] arrayForTranId = resultString.split("<TranID>");
						int endIndex = arrayForTranId[1].indexOf("</TranID>");
						String tranIdForDebit = arrayForTranId[1].substring(0,endIndex);
						System.out.println("-tranIdForDebit-"+tranIdForDebit);	
						
						tranIdForDebit=tranIdForDebit==null ? "" : tranIdForDebit.trim();
						
						
						
						retString1 = confirmTranscation("drcrpay_dr",tranIdForDebit,xtraParams,conn);
						System.out.println("for confirmed debit node :"+retString1);
					//	conn.commit();
						
						
					}
					else
					{
						System.out.println("@@@@@178 result["+resultString+"]");
						conn.rollback();
					}
				
				
			
			}
			
			
		}//try end
		catch (SQLException sqx)
		{
			System.out.println("The SQLException occurs in MilestonePayGen :"+sqx);
			sqx.printStackTrace();
			
			throw new ITMException(sqx);
		}
		catch(Exception e)
		{
			
			System.out.println("The Exception occurs in MilestonePayGen  : "+e);			
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally 
		{
			try
			{

				if (errString == null || errString.trim().length() == 0)
				{
					System.out.println("@@@@@@ errString :::"+ errString );
					//conn.commit();
					//return errString;
				}

				if (pstmt!= null)
				{
					pstmt = null;
				}
				if( conn != null )
				{
					conn.close();
					conn=null;
				}
			}
			catch(Exception e)
			{
				System.out.println("The Exception occurs in MilestonePayGen  :"+e);			
				e.printStackTrace();
				throw new ITMException(e);
			}
		}



		//return errString;
		return resultString;
	}



	private String getWinName(Node node) throws Exception 
	{
		String objName = "";
		NamedNodeMap attrMap = node.getAttributes(); 
		objName = attrMap.getNamedItem("objName").getNodeValue(); 
		System.out.println(" Object Name is==>" + objName); 
		return "w_" + objName; 
	}

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


	public String createDebitNote(HashMap<String,String> drcrMap,Connection conn)
			throws RemoteException, ITMException {

		
		
		StringBuffer xmlBuff = null;
		String xmlString = null;
		// Connection conn = null;
		
		PreparedStatement pstmt = null,pstmt1 = null,pstmt2 = null,pstmt3 = null;
		ResultSet rs = null, rs1 = null,rs2 = null,rs3 = null;
		
		String retString = "",errString = "",siteCode="",chgUser="",chgTerm="",loginEmpCode="",acctCodeDr="",cctrCodeDr="";
		String 	suppCode="",currCode="",acctCode="",cctrCode="",tranSer="",bankCode="",finEntity="",vouchType="",projCode="";
		String dueDate="",processDate="",voucherId="",xtraParams="",lineNoStr = "", frtTerm = "";
		String noArticle="0",entityNameDlv="",relAmt="",purcOrder="",taskCode="",retString1="",sql="",fchgType="";
		String lineNoDet="",acctCdDet="",cctrCdDet="",exchRateDet="",analysisDet1="",analysisDet2="",analysisDet3="",taxClassDet="",taxChapDet="",taxEnvDet="",taxChepDet="";
		Date dispatchDate=null,processDate1=null,dueDate1=null;
		int cnt = 0,count=0,detailsCnt =0,shipmentleadTime=0,lineNo=0,minDays=0,maxDays=0;
		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessLocal itmDBAccessLocal = new ITMDBAccessEJB();
		long diff=0,datediff=0;
		double finChrge=0.0,minAmt=0.0,maxAmt=0.0,amtDet=0.0,taxAmtDet=0.0,amount=0.0,pentlyAmt=0.0;
		double exchRate = 0.0,billAmt=0.0,taxAmt=0.0,totAmt=0.0,netAMt=0.0;
		Date taxDate=null,effDate=null;
		HashMap<String,String> vocDetMap = new HashMap<String,String>();
		boolean flag=false;

		try 
		{
			System.out.println("createDebitNote called....");
			Date currentDate = new Date();
			xmlBuff = null;
			xmlBuff = new StringBuffer();
	
			SimpleDateFormat sdf = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
			SimpleDateFormat sdf1 = new SimpleDateFormat(e12GenericUtility.getDBDateFormat());
			
			System.out.println("application date format :"+e12GenericUtility.getApplDateFormat());
				
			dueDate=drcrMap.get("due_date");
			System.out.println("dueDate :"+dueDate);
			processDate=drcrMap.get("process_date");
			System.out.println("processDate :"+processDate);
			voucherId=drcrMap.get("voucher_id");
			purcOrder=drcrMap.get("purc_order");
			relAmt=drcrMap.get("rel_amt");
			taskCode=drcrMap.get("task_code");
			chgUser=drcrMap.get("chg_user");
			chgTerm=drcrMap.get("chg_term");
			System.out.println("date_diff!!! : "+drcrMap.get("date_diff"));
			datediff=Long.parseLong(drcrMap.get("date_diff"));
			
			System.out.println("dueDate :"+dueDate);
			System.out.println("processDate :"+processDate);
			System.out.println("voucherId :"+voucherId);
			System.out.println("purcOrder :"+purcOrder);
			System.out.println("relAmt :"+relAmt);
			System.out.println("taskCode :"+taskCode);
			System.out.println("dueDate :"+dueDate);
			System.out.println("chgUser :"+chgUser);
			System.out.println("chgTerm :"+chgTerm);
		
			
			System.out.println("processDate :"+processDate);
			System.out.println("dueDate1 :"+dueDate1);
			System.out.println("processDate1:"+processDate);
				
			System.out.println("datediff :"+datediff);
/*
			select * from TARODEV.pord_dlv_term where purc_order='718PNF0299'
			and min_day <=14 and max_day>=14
*/
			
			 
			/*	sql = "select * from (select min_day,max_day,fin_chg,fchg_type,min_amt,max_amt from pord_dlv_term where " +
						"purc_order=? and REF_CODE=?  ORDER BY ABS( min_day - ? ) ,ABS( max_day - ? ) ) where rownum <=1 ";*/
			
			    sql = " select min_day,max_day,fin_chg,fchg_type,min_amt,max_amt from pord_dlv_term where purc_order= ? " +
			    		" and REF_CODE=? and ? between min_day and max_day  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, purcOrder);
				pstmt.setString(2, taskCode);
				pstmt.setLong(3, datediff);
				//pstmt.setLong(4, datediff);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					
					//siteCode = rs.getString("SITE_CODE");
					minDays=rs.getInt("min_day");
					maxDays=rs.getInt("max_day");
					finChrge=rs.getDouble("fin_chg");
					fchgType=rs.getString("fchg_type");
					minAmt=rs.getDouble("min_amt");
					maxAmt=rs.getDouble("max_amt");
					
					fchgType=fchgType==null ? "" :fchgType;
					System.out.println("minDays :"+minDays);
					System.out.println("maxDays :"+maxDays);
					System.out.println("finChrge :"+finChrge);
					System.out.println("fchgType :"+fchgType);
					System.out.println("minAmt :"+minAmt);
					System.out.println("maxAmt :"+maxAmt);
			 
					System.out.println("========Penalty amount calculation=======");
					System.out.println("Purchase order :"+purcOrder);
					System.out.println("relAmt :"+relAmt);
					System.out.println("finChrge:"+finChrge);
					if(fchgType.equalsIgnoreCase("P"))
					{
						amount=Double.parseDouble(relAmt);
						System.out.println("Formula :pentlyAmt=(finChrge * amount)/100;");
						pentlyAmt=(finChrge * amount)/100;//finChrge conside as percentage
						System.out.println("Calculated pentlyAmt :"+pentlyAmt);
					}
					else if(fchgType.equalsIgnoreCase("Q"))
					{
						System.out.println("Formula :pentlyAmt=finChrge * amount");
						amount=Double.parseDouble(relAmt);
						pentlyAmt=finChrge * amount;//finChrge conside as Quantity
					}
					else
					{
						System.out.println("Formula:pentlyAmt=finChrge;");
						System.out.println("Formula :pentlyAmt=finChrge");
						pentlyAmt=finChrge;//finChrge conside as fixed amount
					}
					
					System.out.println("calculate penalaty amount :"+pentlyAmt);
					
					if(pentlyAmt > maxAmt)
					{
						pentlyAmt=maxAmt;
					}
					else if(pentlyAmt < minAmt)
					{
						pentlyAmt=minAmt;
					}
					flag=true;
					
				System.out.println("selected pentlyAmt from min to max amount:"+pentlyAmt);
				}
				else
				{
					System.out.println("data not found in pord_dlv_term for penalty calculation!!");
					flag=false;
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
		/*		
			if flag is true then only debit node generated.
			flag true means purc_order data exist in pord_dlv_term and penalty is greater than 0.	
		*/	
			if(flag)
			{
				
				sql = " select EFF_DATE,SUPP_CODE,PURC_ORDER,CURR_CODE,EXCH_RATE ,ACCT_CODE,CCTR_CODE,BANK_CODE," +
						" DUE_DATE,SITE_CODE,FIN_ENTITY ,BILL_AMT,TAX_AMT,TOT_AMT,TAX_DATE,VOUCH_TYPE ," +
						" PROJ_CODE,NET_AMT from voucher where TRAN_ID = ?" ;
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, voucherId);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					
					effDate = rs.getDate("EFF_DATE");
					suppCode = rs.getString("SUPP_CODE");
					purcOrder = rs.getString("PURC_ORDER");
					currCode = rs.getString("CURR_CODE");
					exchRate = rs.getDouble("EXCH_RATE");
					acctCode = rs.getString("ACCT_CODE");
					cctrCode = rs.getString("CCTR_CODE");
					bankCode = rs.getString("BANK_CODE");
				//	dueDate = rs.getDate("DUE_DATE");
					siteCode = rs.getString("SITE_CODE");
					finEntity = rs.getString("FIN_ENTITY");
					billAmt = rs.getDouble("BILL_AMT");
					taxAmt = rs.getDouble("TAX_AMT");
					totAmt = rs.getDouble("TOT_AMT");
					taxDate = rs.getDate("TAX_DATE");
					vouchType = rs.getString("VOUCH_TYPE");
					projCode = rs.getString("PROJ_CODE");
					netAMt = rs.getDouble("NET_AMT");
			
					
					
					suppCode=suppCode==null ? "" :suppCode.trim();
					purcOrder=purcOrder==null ? "" :purcOrder.trim();
					currCode=currCode==null ? "" :currCode.trim();
					acctCode=acctCode==null ? "" :acctCode.trim();
					cctrCode=cctrCode==null ? "" :cctrCode.trim();
					bankCode=bankCode==null ? "" :bankCode.trim();
					siteCode=siteCode==null ? "" :siteCode.trim();
					finEntity=finEntity==null ? "" :finEntity.trim();
					vouchType=vouchType==null ? "" :vouchType.trim();
					projCode=projCode==null ? "" :projCode.trim();
					
					
					
					System.out.println("effDate :"+effDate);
					System.out.println("suppCode :"+suppCode);
					System.out.println("purcOrder :"+purcOrder);
					System.out.println("finChrge :"+finChrge);
					System.out.println("fchgType :"+fchgType);
					System.out.println("currCode :"+currCode);
					System.out.println("exchRate :"+exchRate);
					System.out.println("acctCode :"+acctCode);
					System.out.println("cctrCode :"+cctrCode);
					System.out.println("bankCode :"+bankCode);
					System.out.println("dueDate :"+dueDate);
					System.out.println("siteCode :"+siteCode);
					System.out.println("finEntity :"+finEntity);
					System.out.println("netAMt :"+netAMt);
					
					
				
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				
				
				sql = " select acct_code__dr,cctr_code__dr from porddet where purc_order= ? ";
						
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,purcOrder);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					acctCodeDr = rs.getString("acct_code__dr");
					cctrCodeDr = rs.getString("cctr_code__dr");
					
					acctCodeDr=acctCodeDr==null ? "" :acctCodeDr.trim();
					cctrCodeDr=cctrCodeDr==null ? "" :cctrCodeDr.trim();
					
					System.out.println("acctCodeDr :"+acctCodeDr);
					System.out.println("cctCodeDr :"+cctrCodeDr);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				

				sql = "select LINE_NO,ACCT_CODE,CCTR_CODE,AMOUNT,TAX_AMT,EXCH_RATE ,ANALYSIS1 " +
						" ,ANALYSIS2,ANALYSIS3,TAX_CLASS,TAX_CHEP,TAX_ENV,TAX_CHAP " +
						" from vouchdet where TRAN_ID= ? " ;
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, voucherId);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					cnt++;
					lineNoDet = rs.getString("LINE_NO");
					acctCdDet = rs.getString("ACCT_CODE");
					cctrCdDet = rs.getString("CCTR_CODE");
					amtDet = rs.getDouble("AMOUNT");
					taxAmtDet = rs.getDouble("TAX_AMT");
					exchRateDet = rs.getString("exch_rate");
					analysisDet1 = rs.getString("analysis1");
					analysisDet2 = rs.getString("analysis2");
					analysisDet3 = rs.getString("analysis3");
					taxClassDet = rs.getString("tax_class");
					taxChepDet = rs.getString("tax_chep");
					taxEnvDet = rs.getString("tax_env");
					taxChapDet = rs.getString("tax_chap");
					
					
					
					lineNoDet=lineNoDet==null ? "" :lineNoDet.trim();
					acctCdDet=acctCdDet==null ? "" :acctCdDet.trim();
					cctrCdDet=cctrCdDet==null ? "" :cctrCdDet.trim();
					exchRateDet=exchRateDet==null ? "" :exchRateDet.trim();
					analysisDet1=analysisDet1==null ? "" :analysisDet1.trim();
					analysisDet2=analysisDet2==null ? "" :analysisDet2.trim();
					analysisDet3=analysisDet3==null ? "" :analysisDet3.trim();
					taxClassDet=taxClassDet==null ? "" :taxClassDet.trim();
					taxChapDet=taxChapDet==null ? "" :taxChapDet.trim();
					taxChepDet=taxChepDet==null ? "" :taxChepDet.trim();
					taxEnvDet=taxEnvDet==null ? "" :taxEnvDet.trim();
					System.out.println("taxEnvDet :"+taxEnvDet);
					
					System.out.println("lineNoDet :"+lineNoDet);
					System.out.println("acctCdDet :"+acctCdDet);
					System.out.println("cctrCdDet :"+cctrCdDet);
					System.out.println("exchRateDet :"+exchRateDet);
					System.out.println("analysisDet1 :"+analysisDet1);
					System.out.println("analysisDet2 :"+analysisDet2);
					System.out.println("analysisDet3 :"+analysisDet3);
					System.out.println("taxClassDet :"+taxClassDet);
					System.out.println("taxChapDet :"+taxChapDet);
					System.out.println("analysisDet2 :"+analysisDet2);
					
					vocDetMap.put("line_no"+cnt, lineNoDet);
					vocDetMap.put("acct_code"+cnt, acctCdDet);
					vocDetMap.put("cctr_code"+cnt, cctrCdDet);
					vocDetMap.put("amount"+cnt, String.valueOf(amtDet));
					vocDetMap.put("tax_amt"+cnt, String.valueOf(taxAmtDet));
					vocDetMap.put("exch_rate"+cnt, exchRateDet);
					vocDetMap.put("analysis1"+cnt, analysisDet1);
					vocDetMap.put("analysis2"+cnt, analysisDet2);
					vocDetMap.put("analysis3"+cnt, analysisDet3);
					vocDetMap.put("tax_class"+cnt, taxClassDet);
					vocDetMap.put("tax_chap"+cnt, taxChapDet);
					vocDetMap.put("tax_chep"+cnt, taxChepDet);
					vocDetMap.put("tax_env"+cnt, taxEnvDet);
					
					
					
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
		
				
			
			
			tranSer="DRNPAY";
			
			siteCode = siteCode == null ? "" : siteCode.trim();
			
			// create xml for track information
			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("drcrpay_dr").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>");

			System.out.println("details 1 start!!!!!");
			
			xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"drcrpay_dr\" objContext=\"1\">");
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<tran_id/>");
			xmlBuff.append("<tran_date><![CDATA["+ sdf.format(currentDate).toString() + "]]></tran_date>");
			xmlBuff.append("<tran_ser><![CDATA[" + tranSer.trim()+ "]]></tran_ser>");
			xmlBuff.append("<fin_entity><![CDATA[" + finEntity.trim()+ "]]></fin_entity>");
			xmlBuff.append("<supp_code><![CDATA[" + suppCode.trim()+ "]]></supp_code>");
			xmlBuff.append("<acct_code><![CDATA[" + acctCode.trim()+ "]]></acct_code>");
			xmlBuff.append("<cctr_code><![CDATA[" + cctrCode.trim()+ "]]></cctr_code>");
			if(effDate == null)
			{
				xmlBuff.append("<eff_date><![CDATA[]]></eff_date>");			
			}
			else
			{
				xmlBuff.append("<eff_date><![CDATA[" + sdf.format(effDate)+ "]]></eff_date>");
			}
			
			xmlBuff.append("<vouch_ser><![CDATA[]]></vouch_ser>");
			xmlBuff.append("<vouch_no><![CDATA[" + voucherId.trim()+ "]]></vouch_no>");
			xmlBuff.append("<amount><![CDATA[" + pentlyAmt + "]]></amount>");
			xmlBuff.append("<curr_code><![CDATA[" + currCode.trim()+ "]]></curr_code>");
			xmlBuff.append("<exch_rate><![CDATA[" + exchRate+ "]]></exch_rate>");
			xmlBuff.append("<remarks><![CDATA[]]></remarks>");
			xmlBuff.append("<chg_user><![CDATA[" + chgUser.trim()+ "]]></chg_user>");
			xmlBuff.append("<chg_date><![CDATA[" +  sdf.format(currentDate).toString() + "]]></chg_date>");
			xmlBuff.append("<chg_term><![CDATA[" + chgTerm.trim()+ "]]></chg_term>");
			xmlBuff.append("<site_code><![CDATA[" + siteCode.trim()+ "]]></site_code>");
			xmlBuff.append("<anal_code><![CDATA[]]></anal_code>");
			xmlBuff.append("<bill_no><![CDATA[]]></bill_no>");
			xmlBuff.append("<drcr_flag><![CDATA[D]]></drcr_flag>");
			xmlBuff.append("<tran_id__pay><![CDATA[]]></tran_id__pay>");
				
			xmlBuff.append("<confirmed><![CDATA[N]]></confirmed>");
			xmlBuff.append("<conf_date><![CDATA[]]></conf_date>");
			xmlBuff.append("<cr_term><![CDATA[]]></cr_term>");
	/*		if(dueDate1 == null)
			{
				xmlBuff.append("<due_date><![CDATA[]]></due_date>");
			}
			else
			{
				xmlBuff.append("<due_date><![CDATA[" + sdf.format(dueDate1) + "]]></due_date>");
			}
	*/		
			
			xmlBuff.append("<due_date><![CDATA[" + sdf.format(currentDate) + "]]></due_date>");
			xmlBuff.append("<emp_code__aprv><![CDATA[]]></emp_code__aprv>");
			xmlBuff.append("<amount__bc><![CDATA[]]></amount__bc>");
			xmlBuff.append("<bill_date><![CDATA[]]></bill_date>");
			xmlBuff.append("<vouch_adj><![CDATA[]]></vouch_adj>");
			xmlBuff.append("<parent__tran_id><![CDATA[]]></parent__tran_id>");
			xmlBuff.append("<rev__tran><![CDATA[]]></rev__tran>");
				
			xmlBuff.append("</Detail1>");
			lineNo = 0;

			

			System.out.println("end of details 1");
			
			for (int itemCtr = 1; itemCtr <= cnt; itemCtr++)
			{
				lineNo++;
				System.out.println("lineNo is " + lineNo);
				// tempMap = (HashMap)tempList.get(itemCtr);

				System.out.println("start of details 2");

				xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"drcrpay_dr\" objContext=\"2\">");
				xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<line_no>" + lineNo + "</line_no>");

							
				xmlBuff.append("<vouch_no><![CDATA["+voucherId+"]]></vouch_no>");
				xmlBuff.append("<line_no__vou><![CDATA["+vocDetMap.get("line_no" + itemCtr)+"]]></line_no__vou>");
				xmlBuff.append("<item_code><![CDATA[]]></item_code>");
				xmlBuff.append("<tax_class><![CDATA["+vocDetMap.get("tax_class" + itemCtr)+"]]></tax_class>");
				xmlBuff.append("<tax_chap><![CDATA["+vocDetMap.get("tax_chap" + itemCtr)+"]]></tax_chap>");
				xmlBuff.append("<tax_env><![CDATA["+vocDetMap.get("tax_env" + itemCtr)+"]]></tax_env>");
				xmlBuff.append("<drcr_amt><![CDATA["+pentlyAmt+"]]></drcr_amt>");
				xmlBuff.append("<tax_amt><![CDATA["+vocDetMap.get("tax_amt" + itemCtr)+"]]></tax_amt>");
				xmlBuff.append("<net_amt><![CDATA["+pentlyAmt+"]]></net_amt>");
				xmlBuff.append("<reas_code><![CDATA[]]></reas_code>");
				xmlBuff.append("<acct_code><![CDATA["+acctCodeDr.trim()+"]]></acct_code>");
				xmlBuff.append("<cctr_code><![CDATA["+cctrCodeDr.trim()+"]]></cctr_code>");
				xmlBuff.append("<amount><![CDATA["+pentlyAmt+"]]></amount>");
				xmlBuff.append("<analysis3><![CDATA["+vocDetMap.get("analysis3" + itemCtr)+"]]></analysis3>");
				xmlBuff.append("<analysis2><![CDATA["+vocDetMap.get("analysis2" + itemCtr)+"]]></analysis2>");
				xmlBuff.append("<analysis1><![CDATA["+vocDetMap.get("analysis1" + itemCtr)+"]]></analysis1>");
				xmlBuff.append("</Detail2>");

			}// end of for loop

			
			System.out.println("end of details 2");

			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			xmlString = xmlBuff.toString();
			System.out.println("@@@@@2: retString  :" + xmlString);
			
			
			errString = saveData(siteCode,xmlString,conn);

			System.out.println("Passed xml in  master State full  errString   " + errString);
			
			System.out.println("errString!!!!!!!!!!"+errString);
			
			
			
	
		}else
		{
			errString = itmDBAccessLocal.getErrorString("", "VTTRINERR", "");
			
		}
		

		} catch (Exception e)
		{

			e.printStackTrace();
			System.out.println("Exception ::" + e.getMessage());
			errString = itmDBAccessLocal.getErrorString("", "VTTRINERR", "");
			return errString;

		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
				}
				if(pstmt != null)
				{
					pstmt.close();
				}
				/*if(conn != null)
				{
					conn.close();
				}*/
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}

		return errString;
	}

	
	
	
	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);
		}
		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;
	}	
	
	
	
	
	
/*
	private String saveData(String siteCode,String xmlString,String xtraParams, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		ibase.utility.UserInfoBean userInfo;
		String chgUser="",chgTerm="";
		try
		{
			System.out.println("saveData@@@@@@");
			userInfo = new ibase.utility.UserInfoBean();
			chgUser = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgUser");
			chgTerm = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			userInfo.setLoginCode(chgUser);
			userInfo.setRemoteHost(chgTerm);
			System.out.println("chgUser :"+chgUser);
			System.out.println("chgTerm :"+chgTerm);
			
			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);
			retString = masterStateful.processRequest(userInfo,xmlString,true,conn);
		}
		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 confirmTranscation(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("confirmVoucher(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);
			System.out.println("aobj 0 :"+aobj[0]);
			System.out.println("aobj 1 :"+aobj[1]);
			System.out.println("aobj 2 :"+aobj[2]);
			//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;
	}
	

}