//w_claim_proc(update button)
package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import ibase.utility.CommonConstants;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.util.*;
import java.sql.*;
import java.io.*;
import org.w3c.dom.*; 
import javax.ejb.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import java.util.*;

import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class PerkVouchPrc extends ProcessEJB implements PerkVouchPrcLocal,PerkVouchPrcRemote //SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	Connection conn = null;
	String processErrString = null;
	String messagePrStr = null;
	AdmCommon admCommon = new AdmCommon();
	ArrayList supplierList = null;
	String acctCodeG = null;
	String cctrCodeG = null;
	StringBuffer masterXmlString = null;
	//Globle variable Declaration
	//process

	//view Data
	String chgUser = null;  
	String chgTerm  = null;
	String loginSite = null;
	String userId = null;
	String taxClass=null;
	String taxChap=null;
	String taxEnv=null;
	String prdCode = null;

	
	/*public void ejbCreate() throws RemoteException, CreateException	{}
	public void ejbRemove(){}
	public void ejbActivate(){}
	public void ejbPassivate(){}*/
	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;
		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);
			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)
		{
			e.printStackTrace();
		}
		return retStr;
}//END OF PROCESS (1)
	
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		supplierList = null;
		
		supplierList = new ArrayList(); 
		messagePrStr = null;
		processErrString = null;
		
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null; 
		
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String childNodeName =  null;
		//filter field
		
		//brow field
		String empCode = null;
		String adCode =null;
		String refNo = null;
		String contCode = null;
		
		double balAmt =0;
		double claimAmt =0;
		double loanAdjAmt = 0;
	
		
		String balAmtStr = null;
		String claimAmtstr =null;
		String loanAdjAmtStr = null;
	
				
		Timestamp tranDate =null;
		Timestamp effDate =null;
		Timestamp endDate =null;
		
		String tranDateStr =null;
		String effDateStr =null;
		String endDateStr =null;
		
		try
		{
			if(conn==null)
			{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				DatabaseMetaData dbmd = conn.getMetaData();
				System.out.println("DriverName["+dbmd.getDriverName()+"]");
				System.out.println("DriverURI["+dbmd.getURL()+"]"  );
				System.out.println("DriverUSER["+dbmd.getUserName()+"]" );
				System.out.println("ApplDateFormat["+genericUtility.getApplDateFormat()+"]");
				System.out.println("DBDateFormat["+genericUtility.getDBDateFormat()+"]");
				connDriver = null;
			}
		
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");  
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			prdCode = genericUtility.getColumnValue("payroll_prd",headerDom);
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			System.out.println("parentNodeListLength:::::::::"+parentNodeListLength);
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength::: "+ childNodeListLength+"\n");
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					
					
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equalsIgnoreCase("emp_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							empCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equalsIgnoreCase("ad_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							adCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equalsIgnoreCase("ref_no"))
					{
						if(childNode.getFirstChild()!=null)
						{
							refNo = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equalsIgnoreCase("bal_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							balAmtStr = childNode.getFirstChild().getNodeValue();
							balAmt = Double.parseDouble(balAmtStr);
						}
					}
					if (childNodeName.equalsIgnoreCase("claim_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							claimAmtstr = childNode.getFirstChild().getNodeValue();
							claimAmt = Double.parseDouble(claimAmtstr);
						}
					}
					if (childNodeName.equalsIgnoreCase("tran_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranDateStr = childNode.getFirstChild().getNodeValue();
							tranDate= Timestamp.valueOf(getValidDateTimeString(tranDateStr.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())+" 00:00:00");
							   
						}
					}
					if (childNodeName.equalsIgnoreCase("eff_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							effDateStr = childNode.getFirstChild().getNodeValue();
							effDate= Timestamp.valueOf(getValidDateTimeString(effDateStr.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())+" 00:00:00");
							
						}
					}
					if (childNodeName.equalsIgnoreCase("end_date"))
					{ 
						if(childNode.getFirstChild()!=null)
						{
							endDateStr = childNode.getFirstChild().getNodeValue();
							endDate= Timestamp.valueOf(getValidDateTimeString(endDateStr.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())+" 00:00:00");
							
						}
					}
					if (childNodeName.equalsIgnoreCase("contcode"))
					{
						if(childNode.getFirstChild()!=null)
						{
							contCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equalsIgnoreCase("loan_adjamt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							loanAdjAmtStr = childNode.getFirstChild().getNodeValue();
							loanAdjAmt = Double.parseDouble(loanAdjAmtStr);
						}
					}
				}//inner loop
				//********************
				Customer customer= new Customer();
				customer.setEmpCode(empCode);
				customer.setAmount(claimAmt);
				System.out.println("Setting end Date:["+endDate+"]");
				customer.setEndDate(endDate);
				System.out.println("Setting Start Date:["+effDate+"]");
				customer.setStartDate(effDate);
				customer.setBalAmt(balAmt);
				customer.setAdCode(adCode);
				customer.setLoanAdjAmt(loanAdjAmt);
	
				int ele = getExistanceOfSupplierCode(supplierList, contCode);
				System.out.println("SuppCodeContract exist/not["+ele+","+contCode+"]");
				Suppliers supplier ;
				if (ele == -1)
				{
					supplier = new Suppliers();
					supplier.setSuppCode(contCode);
					supplier.setGenInfo(conn);
					supplier.setEffDate(effDateStr);
					supplier.setTranDate(tranDateStr);
					//supplier.setPrdCode(prdCode);
					supplierList.add(supplier);
					ele = supplierList.size() -1;
					System.out.println("The size of the element is "+ele);
				}
				else
				{
					supplier = (Suppliers)supplierList.get(ele);
				}
				supplier.setCustomerList(customer);
				supplierList.set(ele,supplier);	
			//**********************
			}// OUT FOR LOOP 
			makeTransaction(supplierList,conn);
		
			if(messagePrStr==null)
			{
				
				if(processErrString==null)
				{
					conn.commit();
					System.out.println("Transaction Commit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
					processErrString =" ";
					//errCode = "POSUCCESS"; 
					//errString =	itmDBAccessEJB.getErrorString("",errCode,"");
				}
				else
				{
					conn.rollback();
					System.out.println("Transaction RollBack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				}
				
			
			}
			else
			{
				
					String errString1 = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
					String begPart = errString1.substring(0,errString1.indexOf("<trace>")+7);
					String endPart = errString1.substring(errString1.indexOf("</trace>"));
					System.out.println("begPart:::"+begPart);
					System.out.println("endPart:::"+endPart);
					String mainStr = begPart+messagePrStr+endPart;
					errString1 = mainStr;
					System.out.println("errString1="+errString1);
					processErrString  = errString1;
					conn.rollback();
					System.out.println("Transaction RollBack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			}
		}//try end	
		catch(Exception e)
		{
			processErrString = "Exception";
			e.printStackTrace();
		}
		finally
		{
			System.out.println("Closing Connection....");
			try
			{ if(conn != null){conn.close();conn = null;}}
			catch(Exception e)
			{e.printStackTrace();}
		}
		return processErrString;
	}//END OF PROCESS(2)
	//TO FIND WHEATHER A CONTRACTOR CODE PRESENT IN LIST OR NOT
	private int getExistanceOfSupplierCode(ArrayList supplierList,String supplierCode)
	{
			int ctr = 0;
			int retVal = -1;
			Suppliers supplier;
			for (ctr = 0;ctr < supplierList.size();ctr++)
			{
				supplier = (Suppliers)supplierList.get(ctr);
				if (supplier.getSuppCode().trim().equalsIgnoreCase(supplierCode.trim()))
				{
					retVal = ctr;
					break;
				}
			}
			return retVal;
	}

//GENERATING TRAN ID 
private String generateTranId(String windowName,String tranDate,String siteCode,Connection conn)
{
	
		Statement stmt = null;
		ResultSet rs = null;
		String sql = null;
		String tranId = null;
		String xmlValues = null;
		 try
	     {
	    	sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE UPPER(TRAN_WINDOW)= '"+windowName+"'";
	    	System.out.println("Tran generator Sql"+sql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			System.out.println("keyString :"+rs.toString());
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);				
			}
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +	"<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues + "<tran_date>"+ tranDate + "</tran_date>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
		}
		catch (SQLException ex)
		{
			processErrString = "Exception";
			ex.printStackTrace();
		}
		catch (Exception e)
		{
			processErrString = "Exception";
			e.printStackTrace();
		}
		return tranId;
	}
//CONVERTING APPLICATION DATE TO DB DATE AND VICE VERSA
	public String getValidDateTimeString(String dateTimeStr, String sourceDateTimeFormat, String targetDateTimeFormat) throws ITMException
	{
		System.out.println("Getting the valid datetime string for dateTimeStr :"+dateTimeStr+": which is in format :"+sourceDateTimeFormat);
		Object date = null;
		String retDateStr = "";
		try
		{
			if (!(sourceDateTimeFormat.equalsIgnoreCase(targetDateTimeFormat)))
			{
				if (sourceDateTimeFormat.indexOf("/") != -1)
				{
					dateTimeStr.replace('/', '-');
				}
				else if (sourceDateTimeFormat.indexOf(".") != -1)
				{
					dateTimeStr.replace('.', '-');
				}
				date = new SimpleDateFormat(sourceDateTimeFormat).parse(dateTimeStr);
				SimpleDateFormat sdfOutput = new SimpleDateFormat(targetDateTimeFormat);
				retDateStr = sdfOutput.format(date);
			}
			else
			{
				retDateStr = dateTimeStr;
			}
		}
		catch (Exception e)
		{
			processErrString = "EXCEPTION";
			System.out.println("Exception :GenericUtility :getValidDateString :==>"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("retDateStr :"+retDateStr);
		return retDateStr;
	}
//GETTING CURRENT DATE IN APPLICATION DATE FORMAT
private String getCurrdateInAppFormat()
{
	String currAppdate =null;
	java.sql.Timestamp currDate = null;
	Object date = null;
	SimpleDateFormat DBDate=null;
	try
	{
			
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println(genericUtility.getDBDateFormat());
		 	DBDate= new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = DBDate.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(DBDate.format(date).toString() + " 00:00:00.0");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
	}
	catch(Exception e)
	{
		processErrString = "EXCEPTION";
		System.out.println("Exception in  getCurrdateInAppFormat:::"+e.getMessage());
	}
	return (currAppdate);
}

//******************************************************************************************************************
private void   makeTransaction(ArrayList supplierList,Connection conn)
{
	System.out.println("Transaction Making In Progress..................................");
	String  errorString = null;
	//String tranDate =getCurrdateInAppFormat(); 
	
	//Header
	
	String currCode=null;
	String siteCode=null;
	String bankCode=null;
	String finEntity=null;
	double exchRate=0;
	String suppCode=null;
	ArrayList customerList =null;
	String acctCodeAp=null;
	String cctrCodeAp=null;
	int line =0;
	String retVal = null;
	String prdCode=null;
	//String acctCode = null;
	//String cctrCode = null;

	//Detail
	String empCode = null;
	double amount=0;
	Customer customer;
	Suppliers supplier;
	double totAmountCustomer=0;
	String tranId=null;
	//String windowName ="W_PAYROLL_POST_ACC";
	String entryBatchNo = null;
	String effDate =null;
	String tranDate =null;
	String adCode =null;
	double amt=0;
	Timestamp startDate = null;
	Timestamp endDate =null;
	double 	loanAdjAmt = 0;
	double 	balAmt = 0;
	String acctPay = null;
	String cctrPay = null;
	
		
	try 
	{
		//Common xml String 
		
		
		
		for(int supp=0;supp<supplierList.size();supp++)
		{
			
			//Common Data
			masterXmlString = new StringBuffer();
			masterXmlString.append("<DocumentRoot>");
			masterXmlString.append("<description>").append("Datawindow Root").append("</description>");
			masterXmlString.append("<group0>");
			masterXmlString.append("<description>").append("Group0 description").append("</description>");
			masterXmlString.append("<Header0>");
			masterXmlString.append("<objName><![CDATA[").append("misc_voucher").append("]]></objName>");
			masterXmlString.append("<pageContext><![CDATA[").append("2").append("]]></pageContext>");
			masterXmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			masterXmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			masterXmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			masterXmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			masterXmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			masterXmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			masterXmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			masterXmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			masterXmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			masterXmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			masterXmlString.append("<description>").append("Header0 members").append("</description>");
			
		//	totAmtHdr =0;
			totAmountCustomer =0;
			supplier = (Suppliers)supplierList.get(supp);
			suppCode=supplier.getSuppCode();
			taxClass=supplier.getTaxClass();
			taxChap=supplier.getTaxChap();
			taxEnv=supplier.getTaxEnv();
			currCode=supplier.getCurrCode();
			siteCode=supplier.getSiteCode();
			bankCode=supplier.getBankCode();
			finEntity=supplier.getFinEntity();
			exchRate=supplier.getExchRate();
			acctCodeAp=supplier.getAcctCodeAp();
			cctrCodeAp=supplier.getCctrCodeAp();
			prdCode =  supplier.getPrdCode();
			effDate = supplier.getEffDate();
			tranDate = supplier.getTranDate();
			entryBatchNo = prdCode + supplier.getSiteCode();
			acctPay =supplier.getAcctCodeAp();
			cctrPay = supplier.getCctrCodeAp();
			System.out.println("Period Code@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@["+prdCode+"]");
			
//			Header xml String 
			masterXmlString.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"misc_voucher\" objContext=\"1\">");
			masterXmlString.append("<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\"/>");
			masterXmlString.append("<tran_id/>");
			masterXmlString.append("<vouch_type><![CDATA[").append("O").append("]]></vouch_type>");
			masterXmlString.append("<tran_date><![CDATA[").append(tranDate).append("]]></tran_date>");
			masterXmlString.append("<tran_type><![CDATA[").append("PRK").append("]]></tran_type>"); 
 			masterXmlString.append("<eff_date><![CDATA[").append(effDate).append("]]></eff_date>");	
			masterXmlString.append("<sundry_type><![CDATA[").append("S").append("]]></sundry_type>");
			masterXmlString.append("<sundry_code ><![CDATA[").append((suppCode==null?" ":suppCode.trim())).append("]]></sundry_code>");
			masterXmlString.append("<acct_code__ap><![CDATA[").append((acctCodeAp==null?"":acctCodeAp.trim())).append("]]></acct_code__ap>");
			masterXmlString.append("<cctr_code__ap><![CDATA[").append((cctrCodeAp==null?"":cctrCodeAp.trim())).append("]]></cctr_code__ap>");
			masterXmlString.append("<bill_no><![CDATA[").append("").append("]]></bill_no>");
			masterXmlString.append("<bill_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></bill_date>");
			masterXmlString.append("<order_ref><![CDATA[").append("").append("]]></order_ref>");
			masterXmlString.append("<site_code><![CDATA[").append((siteCode==null?" ":siteCode.trim())).append("]]></site_code>");
			masterXmlString.append("<fin_entity><![CDATA[").append((finEntity==null?"":finEntity.trim())).append("]]></fin_entity>");
			masterXmlString.append("<curr_code><![CDATA[").append((currCode==null?"":currCode.trim())).append("]]></curr_code>");
			masterXmlString.append("<proj_code><![CDATA[").append("").append("]]></proj_code>");
			masterXmlString.append("<cr_term><![CDATA[").append("").append("]]></cr_term>");
			masterXmlString.append("<due_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></due_date>");
			masterXmlString.append("<bill_amt><![CDATA[").append("0").append("]]></bill_amt>");
			masterXmlString.append("<tax_class><![CDATA[").append((taxClass==null?"":taxClass.trim())).append("]]></tax_class>");
			masterXmlString.append("<tax_chap><![CDATA[").append((taxChap==null?"":taxChap.trim())).append("]]></tax_chap>");
			masterXmlString.append("<tax_env><![CDATA[").append((taxEnv==null?"":taxEnv.trim())).append("]]></tax_env>");
			masterXmlString.append("<tax_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></tax_date>");
			masterXmlString.append("<tax_amt><![CDATA[").append("0").append("]]></tax_amt>");  //cross update
			masterXmlString.append("<tot_amt><![CDATA[").append("0").append("]]></tot_amt>");  //cross update
			masterXmlString.append("<adv_amt><![CDATA[").append("0").append("]]></adv_amt>");
			masterXmlString.append("<acct_code__adv><![CDATA[").append("").append("]]></acct_code__adv>");
			masterXmlString.append("<cctr_code__adv><![CDATA[").append("").append("]]></cctr_code__adv>");
			masterXmlString.append("<net_amt><![CDATA[").append("0").append("]]></net_amt>");  //cross update
			masterXmlString.append("<net_amt__bc><![CDATA[").append("0").append("]]></net_amt__bc>");  //cross update
			masterXmlString.append("<auto_pay><![CDATA[").append("Y").append("]]></auto_pay>");
			masterXmlString.append("<pay_mode><![CDATA[").append("").append("]]></pay_mode>");
			masterXmlString.append("<bank_code><![CDATA[").append((bankCode==null?"":bankCode.trim())).append("]]></bank_code>");
			masterXmlString.append("<entry_batch_no><![CDATA[").append((entryBatchNo==null?" ":entryBatchNo.trim())).append("]]></entry_batch_no>");
			masterXmlString.append("<anal_code><![CDATA[").append("").append("]]></anal_code>");
			masterXmlString.append("<emp_code><![CDATA[").append("").append("]]></emp_code>");
			masterXmlString.append("<diff_amt__exch><![CDATA[").append("").append("]]></diff_amt__exch>");
			masterXmlString.append("<acct_code__cf><![CDATA[").append("").append("]]></acct_code__cf>");
			masterXmlString.append("<cctr_code__cf><![CDATA[").append("").append("]]></cctr_code__cf>");
			masterXmlString.append("<confirmed><![CDATA[").append("N").append("]]></confirmed>");
			masterXmlString.append("<conf_date><![CDATA[").append("").append("]]></conf_date>");
			masterXmlString.append("<emp_code__aprv><![CDATA[").append("").append("]]></emp_code__aprv>");
			masterXmlString.append("<site_descr><![CDATA[").append("").append("]]></site_descr>");
			masterXmlString.append("<chg_date/>");
			masterXmlString.append("<chg_user/>");
			masterXmlString.append("<chg_term/>");
			masterXmlString.append("<remarks><![CDATA[").append("").append("]]></remarks>");
			masterXmlString.append("<supp_bill_amt><![CDATA[").append("00").append("]]></supp_bill_amt>");
			masterXmlString.append("<exch_rate ><![CDATA[").append("1").append("]]></exch_rate>");
			masterXmlString.append("<rnd_off><![CDATA[").append("R").append("]]></rnd_off>");
			masterXmlString.append("<rnd_to><![CDATA[").append("1").append("]]></rnd_to>");
			masterXmlString.append("<rnd_amt><![CDATA[").append("00").append("]]></rnd_amt>");
			masterXmlString.append("<sundry_type__pay><![CDATA[").append("S").append("]]></sundry_type__pay>");	
			masterXmlString.append("<sundry_code__pay><![CDATA[").append((suppCode==null?" ":suppCode.trim())).append("]]></sundry_code__pay>"); 
			masterXmlString.append("<acct_code__pay><![CDATA[").append((acctPay==null?"":acctPay.trim())).append("]]></acct_code__pay>");
			masterXmlString.append("<cctr_code__pay><![CDATA[").append((cctrPay==null?"":cctrPay.trim())).append("]]></cctr_code__pay>");
			masterXmlString.append("<chq_name><![CDATA[").append("").append("]]></chq_name>");
			masterXmlString.append("</Detail1>");
			customerList = (ArrayList)supplier.getCustomerList();
			System.out.println("Total No Of Customer Under Supplier:-["+suppCode+"]:-["+customerList.size()+"]");
			int lineNo =0;
			for(int cust=0;cust<customerList.size();cust++)
			{
				lineNo ++; 
				
				
				customer = (Customer)customerList.get(cust);
				startDate =customer.getStartDate();
				endDate = customer.getEndDate();
				empCode = customer.getEmpCode();
				adCode  = customer.getAdCode();
				amt = customer.getAmount();
				loanAdjAmt = customer.getLoanAdjAmt();
				balAmt = customer.getBalAmt();
				
			/* 	//write validation for claim amount and bal amount
					if lc_balamt < 0 then
			//Added by Nilesh to set the loan adjusted amount to 0 in case the balance is negative
			lc_loanadj  = 0			
			if lc_claimamt > 0 then
				errcode = 'VTCLAIMAM1'//'Claim Amount cannot be positive for negative balance'
				exit
			else
				if lc_claimamt < lc_balamt then
					errcode = 'VTCLAIMAM2'//'Claim Amount cannot be greater then Balance Amount'
					exit
				end if
			end if
		elseif lc_claimamt < 0 or lc_claimamt > lc_balamt then
			errcode = 'VTCLAIMAMT ~t' + 'For Employee ' + ls_emp 
			exit
		end if*/
				//	tranId = generateTranId("ECLAIM",getCurrdateInAppFormat(),loginSite,conn);
				tranId = generateTranId("T_EMP_ADCLAIM",getCurrdateInAppFormat(),loginSite,conn);
				addCctrAcctr(empCode,adCode);
				ClaimProc(empCode,adCode,amt,startDate,endDate,conn);
				insertAdClaimHdr(tranId,empCode,adCode,amt,balAmt,loanAdjAmt,startDate,prdCode,conn);
				insertAdClaim(tranId,empCode,adCode,amt,balAmt,startDate,conn);
				 
				
				masterXmlString.append("<Detail3 dbID=\"\" domID='"+lineNo+"'  objName=\"misc_voucher\"  objContext=\"3\">");
				masterXmlString.append("<attribute  pkNames=\"tran_id:line_no:\" status=\"N\" updateFlag=\"A\" selected=\"N\"/>");
				masterXmlString.append("<tran_id/>");
				masterXmlString.append("<line_no><![CDATA[").append(lineNo).append("]]></line_no>");
				masterXmlString.append("<tran_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></tran_date>");
				masterXmlString.append("<acct_code><![CDATA[").append((acctCodeG==null?" ":acctCodeG.trim())).append("]]></acct_code>");
				masterXmlString.append("<cctr_code><![CDATA[").append((cctrCodeG==null?" ":cctrCodeG.trim())).append("]]></cctr_code>");
				masterXmlString.append("<amount><![CDATA[").append(new Double(amt).toString()).append("]]></amount>");
				masterXmlString.append("<anal_code><![CDATA[").append("").append("]]></anal_code>");  //9/8/2006
				masterXmlString.append("<emp_code><![CDATA[").append(empCode).append("]]></emp_code>");
				masterXmlString.append("<apply_tax><![CDATA[").append("Y").append("]]></apply_tax>");
				masterXmlString.append("<tax_amt><![CDATA[").append("").append("]]></tax_amt>");
				masterXmlString.append("<remarks/>");
				masterXmlString.append("<sundry_type__for><![CDATA[").append("").append("]]></sundry_type__for>");
				masterXmlString.append("<sundry_code__for><![CDATA[").append("").append("]]></sundry_code__for>");
				masterXmlString.append("<acct_code__dr><![CDATA[").append("").append("]]></acct_code__dr>");
				masterXmlString.append("<cctr_code__dr><![CDATA[").append("").append("]]></cctr_code__dr>");
				masterXmlString.append("<acct_code__cr><![CDATA[").append("").append("]]></acct_code__cr>");
				masterXmlString.append("<cctr_code__cr><![CDATA[").append("").append("]]></cctr_code__cr>");
				masterXmlString.append("<prcp_id><![CDATA[").append("").append("]]></prcp_id>");
				masterXmlString.append("<line_no__rcp><![CDATA[").append("").append("]]></line_no__rcp>");
				masterXmlString.append("<item_code><![CDATA[").append("").append("]]></item_code>");
				masterXmlString.append("<quantity><![CDATA[").append("").append("]]></quantity>");
				masterXmlString.append("<rate><![CDATA[").append("").append("]]></rate>");
				masterXmlString.append("<rate__clg><![CDATA[").append("").append("]]></rate__clg>");
				masterXmlString.append("<bill_no><![CDATA[").append("").append("]]></bill_no>");
				masterXmlString.append("<bill_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></bill_date>");
				masterXmlString.append("<bill_amt><![CDATA[").append("").append("]]></bill_amt>");
				masterXmlString.append("<tax_class><![CDATA[").append((taxClass==null?" ":taxClass.trim())).append("]]></tax_class>");
				masterXmlString.append("<tax_chap><![CDATA[").append((taxChap==null?" ":taxChap.trim())).append("]]></tax_chap>");
				masterXmlString.append("<tax_env><![CDATA[").append((taxEnv==null?"":taxEnv.trim())).append("]]></tax_env>");
				masterXmlString.append("</Detail3>");	
			}
		}
		masterXmlString.append("</Header0>");
		masterXmlString.append("</group0>");
		masterXmlString.append("</DocumentRoot>");
		String retString = null;
		try 
		{
			if(!("EXCEPTION".equalsIgnoreCase(processErrString)))
			{
				PayRollVoucPrc payRollVoucPrcEJB = null;
				payRollVoucPrcEJB = new PayRollVoucPrc(); // added for ejb3
				String convertXmlString = masterXmlString.toString();
				payRollVoucPrcEJB.writeXmlInFile(convertXmlString,"PRK",suppCode);
				String returnArrFromSave [] = payRollVoucPrcEJB.saveXmlData(convertXmlString,userId,loginSite);	
				for (int a =0 ;a<returnArrFromSave.length; a++)
				{
					retString = retString +returnArrFromSave[a];
					retString = retString +"@";
				}
				System.out.println("retString:::::::::::::"+retString);
				String tranIdG = retString.substring(retString.indexOf("@")+1,retString.length()-1);
				System.out.println("Return Transaction Id:::::::["+tranIdG+"]");
				payRollVoucPrcEJB.updateMiscVoucherDet(tranIdG,conn);
				payRollVoucPrcEJB.updateMiscVoucher(tranIdG,conn);
			}
		}
		catch(Exception e)
		{
			
			processErrString = "EXCEPTION";
			e.printStackTrace();
			
		}
	}
	catch(Exception e)
	{
		processErrString = "EXCEPTION";
	}
}
//******************************************************************************************************************
private void  addCctrAcctr(String empCode,String adCode)
{
	
	acctCodeG = null;
	cctrCodeG = null;
	System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
	String acctCode1=null;
	String cctrCode=null; 
	
	PreparedStatement pstmt=null;
	ResultSet rs=null;   
	String sql =null;  
  ///Cheak wheather the account code and costcenter code present in employee master or not
	 sql = "select ACCT_CODE__SAL,CCTR_CODE__SAL from employee where emp_code='"+empCode+"'" ;
	System.out.println("empQuery="+sql);
	try
	{
		pstmt = conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		if(rs.next())
		{
			acctCode1 = rs.getString(1);
			cctrCode = rs.getString(2);
		}
		if(acctCode1==null)
		{
			System.out.println("Account Code not Found in Employee Master!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		}
		else
		{
			System.out.println("Account Code From employee:::["+acctCode1+"]");
		}
		if(cctrCode==null)
		{
			System.out.println("Cost Center  Code not Found in Employee Master!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		}
		else
		{
			System.out.println("Cost Center  Code From employee:::["+cctrCode+"]");
		}
		
		rs.close();
		pstmt.close();
	}
	catch(Exception e)
	{
		processErrString = "EXCEPTION";
		e.printStackTrace();
	}
//*************
	if(acctCode1==null)
	{
    
		sql = "SELECT ACCT_CODE__SAL,CCTR_CODE__SAL FROM ALLWDEDN WHERE AD_CODE='"+adCode+"' ";
		System.out.println("AdCode Query="+sql);
		try
		{  
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
			
				acctCodeG =rs.getString(1);
				cctrCodeG = rs.getString(2);
			}
		}
		catch(Exception e)
		{
			processErrString = "EXCEPTION";
			e.printStackTrace();
		}
	
	}
	else
	{
		acctCodeG = acctCode1;
		cctrCodeG = cctrCode;
	}
}
//********************************************
protected void ClaimProc(String empCode,String adCode,double claimAmt,Timestamp startDate,Timestamp endDate,Connection conn)
{
	 
	
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try
		{
			String sql = " UPDATE ALLOWDEDN_BAL 	SET 	AMT_BAL	= AMT_BAL - ?,AMT_ADJ  = AMT_ADJ + ? "
			+"	WHERE EMP_CODE = '"+empCode+"'	AND AD_CODE    = '"+adCode+"' 	AND START_DATE = ? 	AND END_DATE   = ?";
			System.out.println("ALLOWDEDN_BAL ::: "+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setDouble(1,claimAmt);
			pstmt.setDouble(2,claimAmt);
			System.out.println("StartDate:::["+startDate+"]");
			pstmt.setTimestamp(3,startDate);
			System.out.println("EndDate:::["+endDate+"]");
			pstmt.setTimestamp(4,endDate);
			System.out.println("NO Of Record update in the ALLOWDEDN_BAL is ["+pstmt.executeUpdate()+"]");
			pstmt.close();
			
		} 
		catch(Exception e)
		{
			processErrString = "EXCEPTION";
			e.printStackTrace();
		}
}

public void insertAdClaim(String tranId,String empCode,String adCode,double claimAmt,double balAmt,Timestamp startDate,Connection conn)
{
	
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String sql = null;
		try
		{
			sql = " INSERT INTO EMP_ADCLAIM (TRAN_ID, EMP_CODE, AD_CODE, EFF_DATE, BAL_AMT, CLAIM_AMT) "
			+"VALUES(?,?,?,?,?,?)";
			System.out.println("EMP_ADCLAIM ::: "+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			pstmt.setString(2,empCode);
			pstmt.setString(3,adCode);
			pstmt.setTimestamp(4,startDate);
			pstmt.setDouble(5,claimAmt);
			pstmt.setDouble(6,balAmt);
			
			System.out.println("NO Of Record Insert the EMP_ADCLAIM is ["+pstmt.executeUpdate()+"]");
			pstmt.close();
			
		} 
		catch(Exception e)
		{
			processErrString = "EXCEPTION";
			e.printStackTrace();
		}

}
public void insertAdClaimHdr(String tranId,String empCode,String adCode,double claimAmt,double balAmt,double loanAdjAmt,Timestamp startDate,String prdCode,Connection conn)
{
	
		PreparedStatement pstmt=null;
		String sql = null;
		try
		{
			sql = " INSERT INTO EMP_ADCLAIMHDR (TRAN_ID, TRAN_DATE, EMP_CODE, CLAIM_AMT, LOAN_ADJAMT, "
			+"PAYROLL_VOUCHER, PRD_CODE__PAYROLL, CHG_DATE, CHG_USER, CHG_TERM, AD_CODE ,CONFIRMED) "
			+"VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
			System.out.println("EMP_ADCLAIMHDR ::: "+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			pstmt.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis()));
			pstmt.setString(3,empCode);
			pstmt.setDouble(4,claimAmt);
			pstmt.setDouble(5,loanAdjAmt);
			pstmt.setString(6,"V");
			pstmt.setString(7,prdCode);
			pstmt.setTimestamp(8,new java.sql.Timestamp(System.currentTimeMillis()));
			pstmt.setString(9,chgUser);
			pstmt.setString(10,chgTerm);
			pstmt.setString(11,adCode);
			pstmt.setString(12,"Y");
		
			System.out.println("NO Of Record Insert the EMP_ADCLAIM is ["+pstmt.executeUpdate()+"]");
			pstmt.close();
			
		} 
		catch(Exception e)
		{
			processErrString = "EXCEPTION";
			e.printStackTrace();
		}

}

		

}//END OF EJB