/*
CHANGES:::
1-ON 16042007
1) If any reason voucher is not getting created it should give an error instead of showing process completed.
2) It is asking for the A/C codes for that AD Codes also for which posting is set to NO that ADCODES need not to be posted in misc voucher as posting is no  .
MSG NO = [PRCABORT] INSERT IN MESSAGES
3)loan calculation added
*/
package ibase.webitm.ejb.adm;
import java.rmi.RemoteException;
import javax.naming.InitialContext;
import java.text.SimpleDateFormat;
import ibase.utility.CommonConstants;
import java.util.ArrayList;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DatabaseMetaData;
import java.sql.Timestamp;
import java.sql.Statement;
import java.sql.SQLException;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.MasterStatefulEJB;
//import javax.ejb.SessionBean;
import javax.ejb.CreateException;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.ByteArrayInputStream;
import java.io.*;
import java.util.HashMap;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.ejb.*;
import ibase.system.config.*;

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

@Stateless // added for ejb3
public class PayRollVoucPrc extends ProcessEJB implements PayRollVoucPrcLocal,PayRollVoucPrcRemote // SessionBean
{
	//global used in detail also as well as header
	StringBuffer tranBuff = null;
	String type 	= null;
	String frEmp  	= null;
	String toEmp   	= null;
	String fromPrd 	= null;
	String toPrd  	= null;
	String frSite 	= null;
	String toSite 	= null;
	String frProc	= null;
	String toProc 	= null;
	String taxClass=null;
	String taxChap=null;
	String taxEnv=null;
	String userId = null;
	String loginSite=null;
	int lineNo =0;
	StringBuffer masterXmlString = null;//new StringBuffer();
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	//ConnDriver connDriver = new ConnDriver();
	CommonConstants commonConstants = new CommonConstants();
	ValidatorEJB validatorEJB = new ValidatorEJB();
	ArrayList 	supplierList = null;

	//ADDED BY MSALAM ON 05/09/07 for site_code + supplier wise map of employee list

	//end by msalam ON 05/09/07 for site_code + supplier wise map of employee list
	ArrayList empList = null;
	HashMap siteSupMap = null; //new HashMap();
	//ADDED BY MSALAM ON 13/08/07
	ArrayList cctrAcctrList = null;
	HashMap supplierMap = null; //new HashMap();
	String tfromEmp  	= null;
	String ttoEmp   	= null;

	HashMap acctCctrDetMap = null; //new  HashMap();
	HashMap supTranIdMap = null; //new  HashMap();

	String returnArrFromSave [];

	//END OF MSALAM ON 13/08/07

	String errString = null;
	String errString1 = null;
	Connection conn = null;
	String errCode="";
	String chgUser = null;
	String chgTerm = null;
	String acctCode =null;
	String cctrCode=null;
	String tranIdG = null;
	double totAmtHdr =0;
	/*
	public void ejbCreate() throws RemoteException, CreateException	{}
	public void ejbRemove(){}
	public void ejbActivate(){}
	public void ejbPassivate(){}
	*/
	public String process() throws RemoteException,ITMException
	{return "";}
	//PROCESSS
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
			ConnDriver connDriver = new ConnDriver();
			Document detailDom = null;
			Document headerDom = null;
			String retStr = "";
			if(conn==null)
			{
				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);
					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() );

				}
				catch (Exception e)
				{
					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);
				}
				connDriver = null;
		 	    retStr = process(headerDom, detailDom, windowName, xtraParams);
			}
			catch (Exception e)
			{

				System.out.println("Exception :PayRollVoucPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
				e.printStackTrace();
				retStr = e.getMessage();
			}
			return retStr;
	}//END OF PROCESS (1)
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		tranBuff = new StringBuffer ();
		tranBuff.append("Generate Voucher:::");
		boolean recordFound = false;
		type = null;
		errString = null;
		errString1 = null;
		supplierList = new ArrayList();

		//added by mslam on 05/09/07
		siteSupMap = new HashMap();
		String cctrSiteCode = null;

		//end by msalam on 05/09/07


		//By msalam on 13/08/07
		//cctrAcctrList = new ArrayList();
		supplierMap = new HashMap();

		acctCctrDetMap = new  HashMap();
		supTranIdMap = new  HashMap();

		//end by msalam on 13/08/07

		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		ResultSet rsProcess = null;
	//	PreparedStatement pstmtProcess = null;
		Statement stmtProcess = null;
		//***********Variable*************
		double stdExrt=0;
		Timestamp payrollDate = null;
		String empCode = null;
		String deptCode = null;
		String prdCode =null;
		String siteCodePay = null;
		String netAmtStr = null;
		String grade = null;
		String cadre=null;
		String payTable = null;
		String siteCodeWork =null;
		String designation =null;
		String procGroupFr =null;
		String procGroupTo=null;
		String siteCodeAcct=null;
		String finEntity=null;
		String acctCodeSal=null;
		String cctrCodeSal=null;
		String payMode=null;
		String bankCode=null;
		String siteCodeEmp=null;
		String withHeld=null;
		String currCode=null;
		String relieveDate=null;
		String SuppCodeContract =null;
		String paySite = null;
		String processSqlArr=null;
		String processSqlPay=null;
		//String acctCodeSal = null;
		//String cctrCodeSal = null;
		String errStringFlt=null;

		double netAmt=0;

		Timestamp frDate=null;
		Timestamp toDate =null;
		String column=null;
		String crade =null;
	//	**************************** comming from header
	/*	ArrayList fltList = null;
		fltList = new ArrayList();
		fltList.add("site_code__fr");
		fltList.add("site_code__to");
		fltList.add("prd_code__to");
		fltList.add("prd_code__from");
		fltList.add("emp_code__fr");
		fltList.add("emp_code__to");
		fltList.add("payroll_date");
		for(int i=0;i<fltList.size();i++)
		{
			column = (String)fltList.get(i);
			System.out.println("Validate Column :::["+column+"]");
			errStringFlt = ValidateFilterParam(headerDom,conn,column);
			if(errStringFlt!=null || (!errStringFlt.equals("")))break;

		}*/
		errStringFlt = ValidateFilterParam(headerDom,conn);
		type 	= null;
		frEmp  	= null;
		toEmp   	= null;
		fromPrd 	= null;
		toPrd  	= null;
		frSite 	= null;
		toSite 	= null;
		frProc	= null;
		toProc 	= null;

		if(errStringFlt == null || errStringFlt.equals(""))
		{
		try
		{
			type = 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");

			type = genericUtility.getColumnValue("type",headerDom);
			String frEmp   = genericUtility.getColumnValue("emp_code__fr",headerDom);
			String toEmp   = genericUtility.getColumnValue("emp_code__to",headerDom);
			String fromPrd = genericUtility.getColumnValue("prd_code__fr",headerDom);
			String toPrd   = genericUtility.getColumnValue("prd_code__to",headerDom);
			String frSite  = genericUtility.getColumnValue("site_code__fr",headerDom);
			String toSite  = genericUtility.getColumnValue("site_code__to",headerDom);
			String frProc = genericUtility.getColumnValue("proc_group__fr",headerDom);
			String toProc = genericUtility.getColumnValue("proc_group__to",headerDom);
			if(frEmp == null)frEmp="00";
			if(toEmp ==null)toEmp="ZZ";
			if(fromPrd == null)fromPrd="00";
			if(toPrd ==null)toPrd="ZZ";
			if(frSite == null)frSite="00";
			if(toSite == null)toSite="ZZ";
			if(frSite == null)frSite="00";
			if(toSite == null)toSite="ZZ";

			System.out.println("F I L T E R I N F O R M A T I O N ");
			System.out.println("From Employee::["+frEmp+"]");
			System.out.println("To Employee::["+toEmp+"]");
			System.out.println("From Period:::["+fromPrd+"]");
			System.out.println("To Period::["+toPrd+"]");
			System.out.println("From Site::["+frSite+"]");
			System.out.println("To Site::["+toSite+"]");
			System.out.println("From Proc Group::["+frProc+"]");
			System.out.println("To Proc Group::["+toProc+"]");

			String frEmp1 = ("          "+frEmp);
			frEmp1 = frEmp1.substring(frEmp1.length()-10);
			String toEmp1 = ("          "+toEmp);
			toEmp1 = toEmp1.substring(toEmp1.length()-10);
			
			//Validation for all the period codes to have stat_fin = 'Y' in period_stat table
			String prdStatFinValStr = null;
			
			if(type.equalsIgnoreCase("PP"))
			{
				prdStatFinValStr = " select nvl(ps.stat_ADM, 'N') statadm, P.prd_code, P.site_code__pay "
				 	+" from PAYROLL p left outer join period_stat ps on p.prd_code = ps.prd_code "
				 	+" and p.site_code__pay = ps.site_code "
					+" where p.VOUCHER_NO IS  NULL "
					+"		and p.PRD_CODE >= '" + fromPrd + "' AND p.PRD_CODE <= '" + toPrd +"' "
					+"		and p.SITE_CODE__PAY >= '" + frSite + "' AND p.SITE_CODE__PAY <= '" + toSite + "' "
					+"		AND p.EMP_CODE >= '" + frEmp + "' AND p.EMP_CODE <= '" + toEmp + "' ";

				System.out.println("PP prdStatFinValStr :: " + prdStatFinValStr);
			}
			else
			{
				prdStatFinValStr = " select nvl(ps.stat_ADM, 'N'), P.prd_code, P.site_code__pay "
				 	+" from ARREARS p left outer join period_stat ps on p.prd_code = ps.prd_code "
				 	+" and p.site_code__pay = ps.site_code "
					+" where p.VOUCHER_NO IS  NULL "
					+"		and p.PRD_CODE >= '" + fromPrd + "' AND p.PRD_CODE <= '" + toPrd +"' "
					+"		and p.SITE_CODE__PAY >= '" + frSite + "' AND p.SITE_CODE__PAY <= '" + toSite + "' "
					+"		AND p.EMP_CODE >= '" + frEmp + "' AND p.EMP_CODE <= '" + toEmp + "' ";

				System.out.println("Arr prdStatFinValStr :: " + prdStatFinValStr);
			}

			//
			int prdStatFinValCount = 0;			
			PreparedStatement prdStatFinValPStmt = null;
			ResultSet prdStatFinValRs = null;

			prdStatFinValPStmt = conn.prepareStatement(prdStatFinValStr);
			prdStatFinValRs = prdStatFinValPStmt.executeQuery();
			String statFin = null;
			String statAdm = null;
			String statPrdCode = null;
			String statSiteCode = null;
			while( prdStatFinValRs.next() )
			{
				statAdm = prdStatFinValRs.getString( 1 );
				statPrdCode = prdStatFinValRs.getString( 2 );
				statSiteCode = prdStatFinValRs.getString( 3 );
				
				if( "Y".equalsIgnoreCase( statAdm ) == false )
				{
					errString = "PRDADMUDF";
					errString =	itmDBAccessEJB.getErrorString("", errString, "");
					
					String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
					String endPart = errString.substring(errString.indexOf("</trace>"));
					//commented by msalam on 060907 as list of tranId not needed.
					//String mainStr = begPart+tranBuff.toString()+endPart;
					String mainStr = begPart + "Adm option not defined for Period " + statPrdCode + endPart;
					errString = mainStr;
					tranBuff.delete(0,tranBuff.length());
					tranBuff = null;
					begPart =null;
					endPart =null;
					mainStr =null;

					return errString;
				}
				/*
				else
				{
					
					int periodCode = Integer.parseInt( statPrdCode ); 
					int month = Integer.parseInt( statPrdCode.substring( 4, 6 ) );
					int year =  Integer.parseInt( statPrdCode.substring( 0, 4 ) );
					if( month == 1 )
					{
						year -= 1;
						month = 12;
					}
					else
					{
						month -= 1;
					}
					
					String statAdmPrd = null;
					
					statAdmPrd = Integer.toString( year * 100 + month );
					
					PreparedStatement prdStatAdmPStmt = null;
					ResultSet prdStatAdmRs = null;
					String prdStatAdmSql = null;
					prdStatAdmSql = " select count( * ) from period_stat where  stat_adm = 'Y' and prd_code = '" + statAdmPrd + "' and site_code = '" + statSiteCode + "'";
					prdStatAdmPStmt = conn.prepareStatement( prdStatAdmSql );
					prdStatAdmRs = prdStatAdmPStmt.executeQuery();
					
					int statAdmCnt = 0;
					if( prdStatAdmRs.next() )
					{
						statAdmCnt = prdStatAdmRs.getInt( 1 );
					}
					
					prdStatAdmPStmt.close();
					prdStatAdmPStmt = null;
					
					prdStatAdmRs.close();
					prdStatAdmRs = null;
					
					if( statAdmCnt == 0 )
					{
						errString = "PRDADMUDF";
						errString =	itmDBAccessEJB.getErrorString( "", errString, "" );
						String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
						String endPart = errString.substring(errString.indexOf("</trace>"));
						//commented by msalam on 060907 as list of tranId not needed.
						//String mainStr = begPart+tranBuff.toString()+endPart;
						String mainStr = begPart + "Adm option not defined for Period " + statAdmPrd + endPart;
						errString = mainStr;
						tranBuff.delete(0,tranBuff.length());
						tranBuff = null;
						begPart =null;
						endPart =null;
						mainStr =null;

						return errString;
					}
				}
				*/
			}// end of prdStatFinValRs.next()
				
			prdStatFinValPStmt.close();
			prdStatFinValPStmt = null;
			
			prdStatFinValRs.close();
			prdStatFinValRs = null;

			//End of Validation for all the period codes to have stat_fin = 'Y' in period_stat table
			
			//( PAYROLL.VOUCHER_NO IS NULL ) AND
			processSqlPay = " SELECT tP.EMP_CODE, tp.PRD_CODE, tp.SITE_CODE__PAY, "
							+"	tp.DEPT_CODE, tp.payroll_DATE, tp.NET_AMT, tp.GRADE, tp.PAY_TABLE, "
							+"	tp.SITE_CODE__EMP, tp.SITE_CODE__WORK, tp.DESIGNATION, E.SUPP_CODE__CON, tp.CADRE, s.site_code__acct, e.PAY_SITE "
							+"	FROM (select P.EMP_CODE, p.PRD_CODE, P.SITE_CODE__PAY, P.DEPT_CODE, P.Payroll_DATE, "
							+"					P.NET_AMT, P.GRADE, P.PAY_TABLE, P.SITE_CODE__EMP,	P.SITE_CODE__WORK, "
							+"					P.DESIGNATION, P.CADRE, p.VOUCHER_NO "
							+"				from PAYROLL p) tp, EMPLOYEE e, site s "
							+" WHERE ( tp.EMP_CODE = E.EMP_CODE ) AND "
							+"	 e.PAY_SITE = s.site_code(+) and "
							+"	 ( tp.VOUCHER_NO IS  NULL or length( trim( tp.VOUCHER_NO ) ) = 0 ) AND "
							+"	( ( tp.PRD_CODE >= '" + fromPrd.trim() + "' ) AND ( tp.PRD_CODE <= '" + toPrd.trim() + "' ) AND "
							+"	( tp.SITE_CODE__PAY >= '" + frSite.trim() + "') AND ( tp.SITE_CODE__PAY <= '" + toSite.trim() + "' ) AND "
							+"	( tp.EMP_CODE >= '" + frEmp.trim() + "' ) AND ( tp.EMP_CODE <= '" + toEmp.trim() + "' ) AND "
							+"	  (E.PROC_GROUP >= '" + frProc.trim() + "') AND ( E.PROC_GROUP <= '" + toProc.trim() + "') "
							+"		and E.SUPP_CODE__CON IS NOT NULL) "
							+" ORDER BY tp.PRD_CODE ASC, tp.EMP_CODE ASC ";


			processSqlArr = " SELECT tP.EMP_CODE, tp.PRD_CODE, tp.SITE_CODE__PAY, "
						+"	tp.DEPT_CODE, tp.payroll_DATE, tp.NET_AMT, tp.GRADE, tp.PAY_TABLE, "
						+"	tp.SITE_CODE__EMP, tp.SITE_CODE__WORK, tp.DESIGNATION, E.SUPP_CODE__CON, tp.CADRE, s.site_code__acct, e.PAY_SITE "
						+"	FROM (select P.EMP_CODE, p.PRD_CODE, P.SITE_CODE__PAY, P.DEPT_CODE, '' Payroll_DATE, "
						+"					P.NET_AMT, P.GRADE, P.PAY_TABLE, P.SITE_CODE__EMP,	P.SITE_CODE__WORK, "
						+"					P.DESIGNATION, P.CADRE, p.VOUCHER_NO "
						+"				from ARREARS p) tp, EMPLOYEE e, site s "
						+" WHERE ( tp.EMP_CODE = E.EMP_CODE ) AND "
						+"	 e.PAY_SITE = s.site_code(+) and "
						+"	 tp.VOUCHER_NO IS  NULL AND "
						+"	( ( tp.PRD_CODE >= '" + fromPrd.trim() + "' ) AND ( tp.PRD_CODE <= '" + toPrd.trim() + "' ) AND "
						+"	( tp.SITE_CODE__PAY >= '" + frSite.trim() + "') AND ( tp.SITE_CODE__PAY <= '" + toSite.trim() + "' ) AND "
						+"	( tp.EMP_CODE >= '" + frEmp.trim() + "' ) AND ( tp.EMP_CODE <= '" + toEmp.trim() + "' ) AND "
						+"	  (E.PROC_GROUP >= '" + frProc.trim() + "') AND ( E.PROC_GROUP <= '" + toProc.trim() + "') "
						+"		and E.SUPP_CODE__CON IS NOT NULL) "
						+" ORDER BY tp.PRD_CODE ASC, tp.EMP_CODE ASC ";


			    tfromEmp = frEmp;
				ttoEmp = toEmp;

     			stmtProcess = conn.createStatement();

     			System.out.println("Type::::::::::::::::::::::::::["+type+"]");
     			if(type.equalsIgnoreCase("PP"))
     			{
     				System.out.println("Pay Process Query :::-"+processSqlPay);
    				rsProcess=stmtProcess.executeQuery(processSqlPay);

    			}
    			else
    			{
    				System.out.println("Arr Process Query :::-"+processSqlArr);
    				rsProcess=stmtProcess.executeQuery(processSqlArr);

    			}
     			while(rsProcess.next())
     			{
     				System.out.println("Record Found.........................................");
     				recordFound  = true;
     				empCode = (rsProcess.getString(1)==null?" ":rsProcess.getString(1));
     				prdCode = (rsProcess.getString(2)==null?" ":rsProcess.getString(2));
     				siteCodePay = (rsProcess.getString(3)==null?" ":rsProcess.getString(3));
     				deptCode =  (rsProcess.getString(4)==null?" ":rsProcess.getString(4));
     				payrollDate = rsProcess.getTimestamp(5);
     				netAmt = rsProcess.getDouble(6);
     				grade =(rsProcess.getString(7)==null?" ":rsProcess.getString(7));
     				payTable = (rsProcess.getString(8)==null?" ":rsProcess.getString(8));
					siteCodeEmp =(rsProcess.getString(9)==null?" ":rsProcess.getString(9));
					siteCodeWork = (rsProcess.getString(10)==null?" ":rsProcess.getString(10));
					designation = (rsProcess.getString(11)==null?" ":rsProcess.getString(11));
					SuppCodeContract = (rsProcess.getString(12)==null?" ":rsProcess.getString(12));
					crade = (rsProcess.getString(13)==null?" ":rsProcess.getString(13));
					//next 2 lines uncommented by msalam on 050907
					cctrSiteCode = (rsProcess.getString(14)==null?" ":rsProcess.getString(14));
					//end of uncomment by msalam on 130807
					paySite = (rsProcess.getString(15)==null?" ":rsProcess.getString(15));

					//	cadre = (rsProcess.getString(8)==null?" ":rsProcess.getString(8));
					//	customer.setAcctCode(acctCodeSal);
					//	customer.setCctrCode(cctrCodeSal);
					Customer customer= new Customer();
					customer.setEmpCode(empCode);
					customer.setAmount(netAmt);
					//************************
					customer.setCrade(cadre);
					customer.setGrade(grade);
					customer.setDeptCode(deptCode);
					customer.setDesignation(designation);
					customer.setPayTable(payTable);
					customer.setSiteEmp(siteCodeEmp);
					customer.setSiteWork(siteCodeWork);
					customer.setSiteCodePay(siteCodePay);
					customer.setPayrollDate(payrollDate);

					//**********************************
					int ele = getExistanceOfSupplierCode(supplierList, SuppCodeContract.trim());
					System.out.println("SuppCodeContract exist/not[" + ele + "," + SuppCodeContract + "]");
					Suppliers supplier ;
					if (ele == -1)
					{
						supplier = new Suppliers();
						supplier.setSuppCode(SuppCodeContract.trim());
						supplier.setGenInfo(conn);
						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);

					//added by msalam on 05/09/07 for site+supplier map
					if( cctrSiteCode == null || cctrSiteCode.trim().length() == 0 
									|| paySite == null || paySite.trim().length() == 0 )
					{
						String payAccMsgStr = null;
						if( paySite == null || paySite.trim().length() == 0 )
						{
							errString = "VTSTUNDEF";
							payAccMsgStr = "Pay Site Not defined for employee " + empCode;
						}
						else
						{
							errString = "VTSTUNDEF";
							payAccMsgStr = "Site Code Account Not defined for site " + paySite;
						}
					
						errString =	itmDBAccessEJB.getErrorString("", errString, "");
						
						String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
						String endPart = errString.substring(errString.indexOf("</trace>"));
						String mainStr = begPart + payAccMsgStr + endPart;	
						errString = mainStr;
						tranBuff.delete(0,tranBuff.length());
						tranBuff = null;
						begPart =null;
						endPart =null;
						mainStr =null;

						return errString;
					}
					String siteSupKey = null;
					siteSupKey = cctrSiteCode.trim() + ":" + SuppCodeContract.trim();

					if(siteSupMap.containsKey(siteSupKey))
					{
						empList = (ArrayList)siteSupMap.get(siteSupKey);
					}
					else
					{
						empList = new ArrayList();
					}
					empList.add(customer);
					siteSupMap.put(siteSupKey, empList);
					//end by mslam on 05/09/07 for site+supplier map
			}// End of while

			//added by msalam on 05/09/07 fro getting cctr_code__sal + acct_code__sal for site+ supplier
			java.util.Iterator iteratorSup = null;
			java.util.Set setSup = null;
			java.util.Map.Entry meSup =null;
			setSup = siteSupMap.entrySet();
			iteratorSup = setSup.iterator();

			if(iteratorSup == null)
			{
				System.out.println("Null iterator......");
				return "NULLITR";
			}
			else{
				System.out.println("Not Null iterator......");
			}

			while(iteratorSup.hasNext())
			{
				meSup=(java.util.Map.Entry) iteratorSup.next();
				String tKey = null;
				String supplierCode = null;
				tKey = (String)meSup.getKey();

				empList = (ArrayList) meSup.getValue();

				supplierCode = tKey.substring(tKey.indexOf(":")+1);
				System.out.println("Supplier Code :: " + supplierCode);
				int supplierIndex = -1;
				Suppliers tSupplier = null;

				supplierIndex = getExistanceOfSupplierCode(supplierList, supplierCode);
				if(supplierIndex > -1)
					tSupplier = (Suppliers) supplierList.get(supplierIndex);
				else{
					System.out.println("Supplier not found");
					errString = "SUPNOTFND";
					//return "SUPNOTFND";
				}

				String empListStr = null;

				empListStr = makeListStr(empList);

				String prdCodeStr = null;
				prdCodeStr = tSupplier.getPrdCode();
				
				//Validation for all acct+cctr combination on 070907
				String acctCctrValSql = null;
				ArrayList acctCctrValList = null;
				acctCctrValList = new ArrayList();
				if(type.equalsIgnoreCase("PP"))
				{
					acctCctrValSql = " SELECT (case when (e.cctr_code__sal is null) or length(e.cctr_code__sal) = 0 "
							+"	then a. cctr_code__sal else e.cctr_code__sal end ) cctr_code, "
							+" a.acct_code__sal acct_code4 "
							+"	FROM Employee e, PAYROLLDET D, ALLWDEDN A "
							+" WHERE e.emp_code = d.emp_code "
							+"	 and d.ad_code = a.ad_code "
							+"	 and D.EMP_CODE IN ( " + empListStr + " ) "
							+"	 AND D.PRD_CODE = '" + prdCodeStr + "' "
							+"	 AND D.PAYABLE IN ('A' ,'D', 'P') "
							+"	 AND D.POST_YN ='Y' "
							+"	 and d.amount <> 0 ";
					System.out.println( "PP acctCctrValSql :: " + acctCctrValSql );
				}
				else
				{
					acctCctrValSql = " SELECT (case when (e.cctr_code__sal is null) or length(e.cctr_code__sal) = 0 "
							+"	then a. cctr_code__sal else e.cctr_code__sal end ) cctr_code, "
							+" a.acct_code__sal acct_code "
							+"	FROM Employee e, ARREARDET D, ALLWDEDN A "
							+" WHERE e.emp_code = d.emp_code "
							+"	 and d.ad_code = a.ad_code "
							+"	 and D.EMP_CODE IN ( " + empListStr + " ) "
							+"	 AND D.PRD_CODE = '" + prdCodeStr + "' "
							+"	 AND D.PAYABLE IN ('A' ,'D', 'P') "
							+"	 AND D.POST_YN ='Y' "
							+"	 and d.amount <> 0 ";
					System.out.println( "ARR acctCctrValSql :: " + acctCctrValSql );
				}

				PreparedStatement valPStmt = null;
				ResultSet valRs = null;
				String valAcctCode = null;
				String valCctrCode = null;
				
				try
				{
					valPStmt = conn.prepareStatement(acctCctrValSql);
					valRs = valPStmt.executeQuery();
					while(valRs.next()){
						valAcctCode = valRs.getString(1);
						valCctrCode = valRs.getString(2);
						
						acctCctrValList.add( valAcctCode.trim() + ":" + valCctrCode.trim() );
																	
					}
					
				}catch(Exception e){
					e.printStackTrace();
					errString = "EXCEPTION";
					return errString;	
				}finally{
					try{
						if( valRs != null )
						{
							valRs.close();
						}
						valRs = null;
						if( valPStmt != null )
						{
							valPStmt.close();
						}
						valPStmt = null;
					}catch(Exception ex){}
				}
				
				for(int acctCctrCount = 0; acctCctrCount < acctCctrValList.size(); acctCctrCount++)
				{
					int isAcctCctrExist = 1;
					try
					{
						String listItemStr = null;
						
						listItemStr = (String)acctCctrValList.get(acctCctrCount);
						valCctrCode = listItemStr.substring(0, listItemStr.indexOf(":"));
						valAcctCode= listItemStr.substring( listItemStr.indexOf(":") + 1);

						acctCctrValSql = " Select count(*) from Accounts_cctr where acct_code = '" + valAcctCode + "' and cctr_code = '" + valCctrCode + "'";
						
						System.out.println("acctCctrValSql :: " + acctCctrValSql);
						valPStmt = conn.prepareStatement(acctCctrValSql);
						valRs = valPStmt.executeQuery();
						if(valRs.next())
						{
							isAcctCctrExist = valRs.getInt(1);											
						}
						
						if( isAcctCctrExist == 0 )
						{
							errString = "ACCTUNDEF";
						}
						
					}catch(Exception e){
						e.printStackTrace();
						errString = "ACCTUNDEF";
						return errString;	
					}finally{
						try{
							if( valRs != null )
							{
								valRs.close();
							}
							valRs = null;
							if( valPStmt != null )
							{
								valPStmt.close();
							}
							valPStmt = null;
						}catch(Exception ex){}
					}
				}//end of for loop

				
				//end Validation for all acct+cctr combination 070907

				
				String acctCctrDetSql = null;
				if(type.equalsIgnoreCase("PP"))
				{
					acctCctrDetSql =" select t.cctr_code, t.acct_code, "
									+"	   (case when t.PAYABLE = 'A' or t.PAYABLE = 'P' then sum(t.AMT) else 0 End) credit, "
									+"	   (case when t.PAYABLE = 'D' then sum(t.AMT) else 0 End) debit "
									+" from (SELECT e.emp_code emp_code, (case when (e.cctr_code__sal is null) or length(e.cctr_code__sal) = 0 "
									+"					then a. cctr_code__sal else e.cctr_code__sal end ) cctr_code, "
									+"				 a.acct_code__sal acct_code, d.payable payable, d.amount amt "
									+"			FROM Employee e, PAYROLLDET D, ALLWDEDN A "
									+"		WHERE e.emp_code = d.emp_code "
									+"			 and d.ad_code = a.ad_code "
									+"			 and D.EMP_CODE IN ( " + empListStr + " ) "
									+"			 AND D.PRD_CODE = '" + prdCodeStr + "' "
									+"			 AND D.PAYABLE IN ('A' ,'D', 'P') "
									+"			 AND D.POST_YN ='Y' "
									+"			 and d.amount <> 0 "
									+"	) t "
									+"	group by t.cctr_code, t.acct_code, t.PAYABLE ";

					System.out.println("PP acctCctrDetSql :: " + acctCctrDetSql);
				}
				else
				{
					acctCctrDetSql =" select t.cctr_code, t.acct_code, "
									+"	   (case when t.PAYABLE = 'A' or t.PAYABLE = 'P' then sum(t.AMT) else 0 End) credit, "
									+"	   (case when t.PAYABLE = 'D' then sum(t.AMT) else 0 End) debit "
									+" from (SELECT e.emp_code emp_code, (case when (e.cctr_code__sal is null) or length(e.cctr_code__sal) = 0 "
									+"					then a. cctr_code__sal else e.cctr_code__sal end ) cctr_code, "
									+"				 a.acct_code__sal acct_code, d.payable payable, d.amount amt "
									+"			FROM Employee e, ARREARDET D, ALLWDEDN A "
									+"		WHERE e.emp_code = d.emp_code "
									+"			 and d.ad_code = a.ad_code "
									+"			 and D.EMP_CODE IN ( " + empListStr + " ) "
									+"			 AND D.PRD_CODE = '" + prdCodeStr + "' "
									+"			 AND D.PAYABLE IN ('A' ,'D', 'P') "
									+"			 AND D.POST_YN ='Y' "
									+"			 and d.amount <> 0 "
									+"	) t "
									+"	group by t.cctr_code, t.acct_code, t.PAYABLE ";

					System.out.println("Arr acctCctrDetSql :: " + acctCctrDetSql);
				}
				
				pstmt = conn.prepareStatement(acctCctrDetSql);
				rs = pstmt.executeQuery();

				cctrAcctrList = new ArrayList();
				while(rs.next())
				{
					AcctCctrDetail acctCctrDet = new AcctCctrDetail();
					acctCctrDet.acctCctrSal = rs.getString(1);
					acctCctrDet.acctCodeSal = rs.getString(2);

					double debit = 0.0;
					double credit = 0.0;

					credit = rs.getDouble(3);
					debit = rs.getDouble(4);
					acctCctrDet.amount = credit - debit;

					cctrAcctrList.add(acctCctrDet);
				}


				//key = tSupplier.getSuppCode().trim();

				System.out.println("Ket At 507 :: " + tKey + " List :: " + cctrAcctrList.toString());
				supplierMap.put(tKey, cctrAcctrList);
				System.out.println("Array List at 423 :: " + cctrAcctrList.toString());
				cctrAcctrList = null;
			}
			//End by msalam on 05/09/07 fro getting cctr_code__sal + acct_code__sal for site + supplier
			
			//Added by msalam on 301007 for validation on period_stat.stat_fin 
			//for current prdcode of current date
			
			String cctrSiteCodeFinVal = null;
			
			System.out.println("Supplier List :: " + supplierList.toString());
	
			java.util.Iterator iterator = null;
			java.util.Set set = null;
			java.util.Map.Entry me =null;
			set = supplierMap.entrySet();
			iterator = set.iterator();
	
			if(iterator == null){
				System.out.println("Null iterator......");
				errString = "NULLITR";
				return errString;
			}
			else{
				System.out.println("Not Null iterator......");
			}
			String currDate = null;
			currDate = getCurrdateInAppFormat();
			String currPrdCode = null;
			//get currdate in dd-MM-yyyy format
			//mpleDateFormat DBDate = null;
			String formatDateStr = null;
			try
			{
				//Date= new SimpleDateFormat("dd-mm-yyyy");
				formatDateStr = (java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( currDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) ).toString()).substring(0, 10);
				System.out.println("Valid :: " + formatDateStr );
			}
			catch(Exception e)
			{
				System.out.println("Exception in getCurrdateWoTimeInDBFormat :::"+e.getMessage());
			} 
			//currPrdCode = formatDateStr.substring( 0, 4) + formatDateStr.substring( 5, 7);
			currPrdCode = getPeriodCode( currDate,conn);
			
			System.out.println( "currPrdCode :: " + currPrdCode );
			//end get currdate in
	
			while(iterator.hasNext())
			{
				me=(java.util.Map.Entry) iterator.next();
				String tKey = null;
				String supplierCode = null;
				tKey = (String)me.getKey();
				//getting supplier and acctCctrList informatuion
				cctrAcctrList = (ArrayList) me.getValue();
				cctrSiteCodeFinVal = tKey.substring(0, tKey.indexOf(":"));
				supplierCode = tKey.substring(tKey.indexOf(":") + 1);
				//validation for stat_fin = 'Y' for the period of current date 
							 
				String prdFinValStr = null;
				prdFinValStr = " select count(*) "
				 	+" from  period_stat ps "
					+" where  ps.PRD_CODE = '" + currPrdCode + "'"
					+" AND nvl(ps.stat_fin, 'N') = 'Y' "
					+" AND ps.SITE_CODE = '" + cctrSiteCodeFinVal + "'";

				/*
				prdFinValStr = " select nvl(ps.stat_fin, 'N') statfin"
				 	+" from  period_stat ps "
					+" where  ps.PRD_CODE = '" + currPrdCode + "'"
					+"	AND ps.SITE_CODE = '" + cctrSiteCodeFinVal + "'";
				*/
				PreparedStatement prdFinValPStmt = null;
				ResultSet prdFinValRs = null;
				
				System.out.println( "prdFinValStr :: " + prdFinValStr );
				
				prdFinValPStmt = conn.prepareStatement(prdFinValStr);
				prdFinValRs = prdFinValPStmt.executeQuery();
				String statFinVal = null;
				String finSite = null;
				int prdFinCount = 0;
				if( prdFinValRs.next() )
				{
					prdFinCount = prdFinValRs.getInt( 1 );
				}
				if( prdFinCount == 0 )
				{
					errString = "PRDFINUDF";
					System.out.println("Fin option not defined for Period " + currPrdCode + " Site Code " + cctrSiteCodeFinVal) ;
					/*
					errString =	itmDBAccessEJB.getErrorString("", errString, "");
					
					String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
					String endPart = errString.substring(errString.indexOf("</trace>"));
					//commented by msalam on 060907 as list of tranId not needed.
					//String mainStr = begPart+tranBuff.toString()+endPart;
					String mainStr = begPart + "Fin option not defined for Period " + currPrdCode + " Site Code " + cctrSiteCodeFinVal ;
					System.out.println( "Error String :: " + mainStr );
					errString = mainStr;
					tranBuff.delete(0,tranBuff.length());
					tranBuff = null;
					begPart =null;
					endPart =null;
					mainStr =null;
					
					if( prdFinValRs != null )
					{
						prdFinValRs.close();
					}
					prdFinValRs = null;
					if( prdFinValPStmt != null )
					{				
						prdFinValPStmt.close();
					}
					prdFinValPStmt = null;
	
					return errString;
					*/
				}
				
				if( errString != null && errString.trim().length() > 0 )
				{
					break;
				}

			//end of validation
			}
			//end by msalam on 301007 for validation on period_stat.stat_fin 
			//for current prdcode of current date

			if(recordFound == false )
			{
				errString = "RECNOTF";//"No PayRoll/Arrears Found....";
			}
			else
			{
				if(errString == null || errString.trim().length() == 0)
				{
					errString1 = makeTransactionAcctCctrWise(supplierList, supplierMap, conn);
				}
			}

			if( errString == null || errString.trim().length() == 0 )
			{

				if(errString1 == null || errString1.trim().length() == 0 )
				{
					conn.commit();
					System.out.println("Transaction Commit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

				}
				else
				{
					//***ADDED ON 16042007
					errCode = errString1;
					//errString =	itmDBAccessEJB.getErrorString("","PRCABORT","");
					errString =	itmDBAccessEJB.getErrorString("", errCode, "");
					String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
					String endPart = errString.substring(errString.indexOf("</trace>"));
					System.out.println("begPart:::" + begPart);
					System.out.println("endPart:::" + endPart);
					String mainStr = begPart + " " + endPart;
					errString = mainStr;

					conn.rollback();
					System.out.println("Transaction RollBack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				}
				//errCode = "POSUCCESS";
				//errString =	itmDBAccessEJB.getErrorString("",errCode,"");
			}
			else
			{
				errCode = errString;
				errString =	itmDBAccessEJB.getErrorString("", errCode, "");
				String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
				String endPart = errString.substring(errString.indexOf("</trace>"));
				System.out.println("begPart:::" + begPart);
				System.out.println("endPart:::" + endPart);
				String mainStr = begPart + " " + endPart;
				errString = mainStr;
				conn.rollback();
				System.out.println("Transaction RollBack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
	
		}
		finally
		{
	
			try{
				if(conn != null){
					conn.close();
					conn = null;
				}
				if( rs != null)
				{
					rs.close();
					rs = null;
				}
				if( rsProcess != null)
				{
					rsProcess.close();
					rsProcess = null;
				}
				
				if( stmtProcess != null)
				{
					stmtProcess.close();
					stmtProcess = null;
				}
				
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}

				supplierList = null;
				cctrAcctrList = null;
				supplierMap = null;
				tfromEmp  	= null;
				ttoEmp   	= null;
			}
			catch(Exception e){e.printStackTrace();}
		}
	}//end of validation
	else
	{
		errString = errStringFlt;
	}
	System.out.println("Rettuning String errString::::::::::::"+errString);
	if(errString == null || errString.trim().length() == 0 )
	{
		errString =	itmDBAccessEJB.getErrorString("","SUCC","");
		String begPart = errString.substring(0,errString.indexOf("<trace>")+7);
		String endPart = errString.substring(errString.indexOf("</trace>"));
		//commented by msalam on 060907 as list of tranId not needed.
		//String mainStr = begPart+tranBuff.toString()+endPart;
		String mainStr = begPart+"Success" + endPart;
		errString = mainStr;
		tranBuff.delete(0,tranBuff.length());
		tranBuff = null;
		begPart =null;
		endPart =null;
		mainStr =null;
	}
	supplierList = null;
	cctrAcctrList = null;
	supplierMap = null;
	tfromEmp  	= null;
	ttoEmp   	= null;
	
	return errString;
}//END OF PROCESS(2)

//added by msalam on 160807
private String makeTransactionAcctCctrWise(ArrayList supplierList, HashMap suplierMap, 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 crTerm = null;
	String acctPay = null;
	String cctrPay = null;
	String remarks = null;

	String detAcctCodeAp = null;
	String detCctrCodeAp = null;
	
	//added by msalam on 060907
	String cctrSiteCode = null;
	//end by msalam on 060907


	try
	{
		//Common xml String
		System.out.println("Supplier List :: " + supplierList.toString());

		java.util.Iterator iterator = null;
		java.util.Set set = null;
		java.util.Map.Entry me =null;
		set = supplierMap.entrySet();
		iterator = set.iterator();

		if(iterator == null){
			System.out.println("Null iterator......");
			errorString = "NULLITR";
			return errorString;
		}
		else{
			System.out.println("Not Null iterator......");
		}

		while(iterator.hasNext())
		{
			me=(java.util.Map.Entry) iterator.next();
			String tKey = null;
			String supplierCode = null;
			tKey = (String)me.getKey();
			//getting supplier and acctCctrList informatuion
			cctrAcctrList = (ArrayList) me.getValue();
			cctrSiteCode = tKey.substring(0, tKey.indexOf(":"));
			supplierCode = tKey.substring(tKey.indexOf(":") + 1);

			int supplierIndex = -1;
			supplierIndex = getExistanceOfSupplierCode(supplierList, supplierCode);
			supplier = (Suppliers) supplierList.get(supplierIndex);
			//
			
			lineNo = 0;
			//Common Data
			remarks = null;
			masterXmlString = null;
			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;

			suppCode=supplier.getSuppCode();
			System.out.println("Sup Code at 680 :: " + suppCode);
			taxClass=supplier.getTaxClass();
			taxChap=supplier.getTaxChap();
			taxEnv=supplier.getTaxEnv();
			currCode=supplier.getCurrCode();
			siteCode=supplier.getSiteCode();
			bankCode=supplier.getBankCode();
			finEntity=supplier.getFinEntity();
			exchRate=supplier.getExchRate();
			//start of msalam on 070807
			//next 2 lines commented by msalam on 070807 and it is taken form supplier table
			//for the requirment in mail
			//acctCodeAp=supplier.getAcctCodeAp();
			//cctrCodeAp=supplier.getCctrCodeAp();
			String acctCodeSql = null;
			acctCodeSql = " SELECT ACCT_CODE__AP, CCTR_CODE__AP FROM SUPPLIER WHERE SUPP_CODE = '" + suppCode + "' ";
			PreparedStatement acctPStmt = null;
			ResultSet acctRs = null;

			try
			{
	
				acctPStmt = conn.prepareStatement(acctCodeSql);
				acctRs = acctPStmt.executeQuery();
				if(acctRs.next()){
					acctCodeAp = acctRs.getString(1);
					cctrCodeAp = acctRs.getString(2);
	
					System.out.println("Supplier acctCodeAp :: " + acctCodeAp);
					System.out.println("Supplier cctrCodeAp :: " + cctrCodeAp);
				}
			}catch(Exception e){
				e.printStackTrace();
				errorString = "ACCTEXC";
				return errorString;	
			}finally{
				try{
					if( acctRs != null )
						acctRs.close();
					acctRs = null;
					if( acctPStmt != null )
						acctPStmt.close();
					acctPStmt = null;
				}catch(Exception ex){}
			}

			if( acctCodeAp == null )
			{
				errorString = "ACCTNFND";
			}
			if( cctrCodeAp == null )
			{
				errorString = "CCTNFND";
			}
			if( errorString != null )
			{
				return errorString;
			}
			//end by msalam on 070807
			
			//getting bank code from site master for accounting site
			
			String siteBankCode = " ";
			
			String bankCodeSql = null;
			bankCodeSql = " SELECT BANK_CODE FROM SITE WHERE SITE_CODE = '" + cctrSiteCode.trim() + "' ";
			System.out.println("Site sql :: " + bankCodeSql);
			PreparedStatement bankPStmt = null;
			ResultSet bankRs = null;

			try{	
				bankPStmt = conn.prepareStatement(bankCodeSql);
				bankRs = bankPStmt.executeQuery();
				if(bankRs != null)
				{
					if(bankRs.next()){
						siteBankCode = (bankRs.getString(1)).trim();
						System.out.println("Site Bank :: " + siteBankCode);
					}
				}
				
			}catch(Exception e){
				e.printStackTrace();
				//errorString = "EXCEPTION";
			}finally{
				try{
					if(bankRs != null)
					{
						bankRs.close();
					}
					bankRs= null;
					if(bankPStmt != null)
					{
						bankPStmt.close();
					}
					bankPStmt = null;
				}catch(Exception ex){}
			}	
			//end of getting bankcode
			
			//If bank code is not blank then it should exist in bank master
			String bankSiteCode = null;			
			String bankSiteSql = null;
			
			if( siteBankCode == null || siteBankCode.trim().length() == 0 )
				siteBankCode = "";
			
			bankSiteSql = " SELECT site_code FROM Bank WHERE bank_CODE = '" + siteBankCode.trim() + "' ";
			System.out.println("Bank sql :: " + bankSiteSql);
			PreparedStatement bankSitePStmt = null;
			ResultSet bankSiteRs = null;

			try{	
				bankSitePStmt = conn.prepareStatement(bankSiteSql);
				bankSiteRs = bankSitePStmt.executeQuery();
				if(bankSiteRs != null)
				{
					if(bankSiteRs.next()){
						bankSiteCode = bankSiteRs.getString(1);
						System.out.println("Bank SiteCode :: " + bankSiteCode);
					}
				}
				
			}catch(Exception e){
				e.printStackTrace();
				//errorString = "EXCEPTION";
			}finally{
				try{
					if(bankSiteRs != null)
					{
						bankSiteRs.close();
					}
					bankSiteRs= null;
					if(bankSitePStmt != null)
					{
						bankSitePStmt.close();
					}
					bankSitePStmt = null;
				}catch(Exception ex){}
			}
			
			if(bankSiteCode != null && bankSiteCode.trim().length() > 0)
			{
				if(	!(bankSiteCode.trim().equalsIgnoreCase(cctrSiteCode.trim())) )
				{
					errorString = "BNKCDERR";
					return errorString;	
				}
			}
			//end of If bank code is not blank then it should exist in bank master
			
						
			prdCode =  supplier.getPrdCode();
			crTerm  = supplier.getCrTerm();
			
			System.out.println("Cr Term :: " + crTerm);
			
			//If crTerm is blank then prompt error. 070907
			if(crTerm == null || crTerm.trim().length() == 0)
			{
				System.out.println("Cr Term Blank");
				errorString = "CRTRMBLK";
				return errorString;
			}
				
			//End If crTerm is blank then prompt error. 070907
			

			//start of msalam on 070807
			//next 2 lines commented by msalam on 070807 and it is taken form supplier table
			//for the requirment in mail
			//acctPay =supplier.getAcctCodeAp();
			//cctrPay = supplier.getCctrCodeAp();
			if( acctCodeAp != null)
				acctPay = acctCodeAp.trim();
			if( cctrCodeAp != null)
				cctrPay = cctrCodeAp.trim();
			//end by msalam on 070807

			System.out.println("Period Code@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@["+prdCode+"]");
			String tranTy = null;
			//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("E").append("]]></vouch_type>");
			masterXmlString.append("<tran_date><![CDATA[").append(getCurrdateInAppFormat()).append("]]></tran_date>");
			if(type.equalsIgnoreCase("PP"))
         	{
        		masterXmlString.append("<tran_type><![CDATA[").append("PAY").append("]]></tran_type>");
        		tranTy = "PAY";
				//line commented by ms alam on 070807 as per mail from Mr. Subu Chandra
				//and modified line added
        		//remarks = "PayRoll For Period "+prdCode+"]";
				remarks = "Contract Charges for the period-" + prdCode ;
        	}
        	else
        	{
        		masterXmlString.append("<tran_type><![CDATA[").append("ARR").append("]]></tran_type>");
        		tranTy = "ARR";
        		remarks = "Arrears Process For Period-" + prdCode;
        	}

			masterXmlString.append("<eff_date><![CDATA[").append(getCurrdateInAppFormat()).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>");
			//commented by msalam on 060907 and modified line added
			//masterXmlString.append("<site_code><![CDATA[").append((siteCode==null?" ":siteCode.trim())).append("]]></site_code>");
			masterXmlString.append("<site_code><![CDATA[").append((cctrSiteCode==null?" ":cctrSiteCode.trim())).append("]]></site_code>");
			//end of comment/modified my mslam on 06/09/07
			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((crTerm==null?"":crTerm.trim())).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>");
			//commented by msalam on 060907 and modified line added
			//masterXmlString.append("<bank_code><![CDATA[").append((bankCode==null?"":bankCode.trim())).append("]]></bank_code>");
			masterXmlString.append("<bank_code><![CDATA[").append((siteBankCode==null?"":siteBankCode.trim())).append("]]></bank_code>");
			//end commented by msalam on 060907 and modified line added
			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(remarks).append("]]></remarks>");
			//line added by msalam on 070807 for requirment in mail
			masterXmlString.append("<tran_mode><![CDATA[").append("A").append("]]></tran_mode>");
			//end by msalam on 070807
			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>");

			String adCode = null;
			double amt = 0.0;

			for(int acctCctrCnt=0; acctCctrCnt < cctrAcctrList.size(); acctCctrCnt++)
			{
				AcctCctrDetail accCcDet = null;
				accCcDet = (AcctCctrDetail) cctrAcctrList.get(acctCctrCnt);

				amt = accCcDet.amount;
				adCode = accCcDet.adCode;

				detAcctCodeAp = accCcDet.acctCodeSal;
				detCctrCodeAp = accCcDet.acctCctrSal;

				lineNo++;
				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((detAcctCodeAp==null?" ":detAcctCodeAp.trim())).append("]]></acct_code>");
				masterXmlString.append("<cctr_code><![CDATA[").append((detCctrCodeAp==null?" ":detCctrCodeAp.trim())).append("]]></cctr_code>");
				//line added by msalam on 130807
				masterXmlString.append("<tran_mode><![CDATA[").append("A").append("]]></tran_mode>");
				//end by msalam on 130807
				//next line commented and modified line added by msalam on 070807 for requirment in mail
				masterXmlString.append("<amount><![CDATA[").append(new Double(amt).toString()).append("]]></amount>");
				//modified line commented as told by subu kumar
				//masterXmlString.append("<amount><![CDATA[").append(new Double(-amt).toString()).append("]]></amount>");
				//end by msalam on 070807
				masterXmlString.append("<anal_code><![CDATA[").append("").append("]]></anal_code>");  //9/8/2006
				masterXmlString.append("<emp_code><![CDATA[").append("").append("]]></emp_code>");
				masterXmlString.append("<apply_tax><![CDATA[").append("Y").append("]]></apply_tax>");
				masterXmlString.append("<tax_amt><![CDATA[").append("").append("]]></tax_amt>");
				//changed by msalam on 210907 and modified line added
				//Remarks set blank as per mail from subu sir on 21/09/07
				//masterXmlString.append("<remarks><![CDATA[").append("Voucher For Period-"+prdCode+", AC/CC-" + detAcctCodeAp.trim() + "/" + detCctrCodeAp.trim()).append("]]></remarks>"); //& Ad Code [" ]
				masterXmlString.append("<remarks><![CDATA[").append( "" ).append("]]></remarks>"); //& Ad Code [" ]
				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("").append("]]></tax_class>");
				masterXmlString.append("<tax_chap><![CDATA[").append("").append("]]></tax_chap>");
				masterXmlString.append("<tax_env><![CDATA[").append("").append("]]></tax_env>");
				masterXmlString.append("</Detail3>");
			}
			//end by msalam on 130807

			masterXmlString.append("</Header0>");
			masterXmlString.append("</group0>");
			masterXmlString.append("</DocumentRoot>");
			String convertXmlString = masterXmlString.toString();

			System.out.println("MasterXml String :: " + convertXmlString);
			System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
			//System.out.println(masterXmlString);
			writeXmlInFile(convertXmlString,tranTy,suppCode);
			System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
			String returnArrFromSave [] = saveXmlData(convertXmlString,userId,loginSite);
			String retString = null;
			for (int a =0 ;a<returnArrFromSave.length; a++)
			{
				retString = retString +returnArrFromSave[a];
				retString = retString +"@";
			}
			System.out.println("retString:::::::::::::"+retString);
			this.tranIdG = retString.substring(retString.indexOf("@")+1,retString.length()-1);
			supTranIdMap.put(supplierCode, this.tranIdG);
			System.out.println("Return Transaction Id:::::::["+this.tranIdG+"]");
		}//end of supplier Iterator while loop

		for(int supp=0;supp<supplierList.size();supp++)
		{
			Suppliers tSupplier = null;
			tSupplier = (Suppliers)supplierList.get(supp);
		 	customerList = (ArrayList)tSupplier.getCustomerList();
		 	String tSuppCode = null;
		 	tSuppCode = (String)tSupplier.getSuppCode();
			System.out.println("Total No Of Customer Under Supplier:-["+suppCode+"]:-["+customerList.size()+"]");
			line =0;
			lineNo = 0;
			for(int cust=0;cust<customerList.size();cust++)
			{
				customer = (Customer)customerList.get(cust);
				empCode = customer.getEmpCode();

				retVal = custLoanCalculation(empCode,prdCode,customer);
				System.out.println("ErrCode :["+retVal+"]");

				 if((retVal != null) && (retVal.indexOf("Exception")==-1))
				 {
				 	errString = "No acctCode For Adcode["+retVal+"][Cust="+empCode+"]";
				 	break;

				 }
				 else
				 {
				 	if((retVal!=null) && (retVal.indexOf("Exception"))!=-1)
				 	{
				 		errString = retVal;
				 		//errString = "xxx";
				 		break;
				 	}

					customer = (Customer)customerList.get(cust);

					String tTranId = null;
					String tEmpCode = null;
					String tPrdCode = null;
					tPrdCode = tSupplier.getPrdCode();
					tEmpCode = customer.getEmpCode();
					tTranId = (String)supTranIdMap.get(tSuppCode);
					updatePayRoll(tEmpCode, tPrdCode, tTranId);
					
					if(tranBuff.indexOf(tTranId) == -1)
						tranBuff.append("[" + tTranId + "]");
				 }
			}

		}
	}//End Of Try
	catch(Exception e)
	{
		errString1 = "PRCEXC";
		if( errorString == null || errorString.trim().length() == 0)
			errorString = errString1;
		e.printStackTrace();
	}

	return errorString;	
}
//End of msalam on 160807

private void updatePayRoll(String empCode,String prdCode,String tranId)
{
		System.out.println("type:::["+type+"]");
		PreparedStatement pstmt=null;
		String sql =null;
		try
		{
			if(type.equalsIgnoreCase("PP"))
			{
		 		sql = " UPDATE PAYROLL SET VOUCHER_NO = ? , VOUCHER_DATE  = ?,CONFIRMED       ='Y' WHERE PRD_CODE = '"+prdCode+"' AND EMP_CODE='"+empCode+"'";
		 	}
		 	else
		 	{
		 		sql = " UPDATE ARREARS SET VOUCHER_NO = ? , VOUCHER_DATE  = ? ,CONFIRMED       ='Y' WHERE PRD_CODE = '"+prdCode+"' AND EMP_CODE='"+empCode+"'";

		 	}
		 	System.out.println("PayRoll Sql :::"+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			System.out.println("Setting TranId = ["+tranId+"]");
			pstmt.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis()));
			System.out.println("Update Record in payroll ["+pstmt.executeUpdate()+"]");
			pstmt.close();

		}
		catch(Exception e)
		{
			errString1 = "EXCEPTION";
			e.printStackTrace();
		}
}
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;
}

//added by msalam on 140807
private int getAcctCctrExistInList(ArrayList tacctCctrList, String acctCctr){
	for(int counter = 0; counter < tacctCctrList.size(); counter++)
		if(((String)tacctCctrList.get(counter)).equals(acctCctr))
			return counter;

	return -1;
}
//end by msalam on 140807
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)
	{
		System.out.println("Exception in  getCurrdateInAppFormat:::"+e.getMessage());
	}
	return (currAppdate);
}
private Timestamp getCurrdateWoTimeInDBFormat()
{
	java.sql.Timestamp currDate = null;
	Object date = null;
	SimpleDateFormat DBDate=null;
	try
	{
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			DBDate= new SimpleDateFormat("yyyy-mm-dd");
			date = DBDate.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(DBDate.format(date).toString() + " 00:00:00.0");
			System.out.println(currDate);
	}
	catch(Exception e)
	{
		System.out.println("Exception in getCurrdateWoTimeInDBFormat :::"+e.getMessage());
	}
	return (currDate);
}
protected void  updateMiscVoucherDet(String tranIdG,Connection conn)
{
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try
		{
			String sql = "  UPDATE MISC_VOUCHDET SET BILL_AMT=TAX_AMT+AMOUNT WHERE TRAN_ID ='"+tranIdG+"'";
			System.out.println("Update Misc_Voucher::["+sql+"]");
			pstmt = conn.prepareStatement(sql);
			System.out.println("Setting tranIdG["+tranIdG+"]");
		//	pstmt.setString(1,tranIdG);
			pstmt.executeUpdate();
			pstmt.close();
		}
		catch(Exception e)
		{
			errString1 = "EXCEPTION";
			e.printStackTrace();
		}
}

protected void updateMiscVoucher(String tranIdG,Connection conn)
{


		PreparedStatement pstmt=null;
		ResultSet rs=null;
		double taxAmt=0;
		double amount=0;
		try
		{
			String sql = " SELECT SUM(TAX_AMT),SUM(AMOUNT) FROM MISC_VOUCHDET WHERE TRAN_ID ='"+tranIdG+"'";
			System.out.println("MISC_VOUCHDET SQL STATEMENT "+sql);
			pstmt = conn.prepareStatement(sql);
			//pstmt.setString(1,tranIdG);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				taxAmt = rs.getDouble(1);
				amount = rs.getDouble(2);
				System.out.println("Tax Amount:::::::::["+taxAmt+"]");
				System.out.println("Amount:::::::::["+amount+"]");

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

			 sql = " UPDATE MISC_VOUCHER SET TOT_AMT = "+amount+" , tax_amt ="+taxAmt+" WHERE TRAN_ID = '"+tranIdG+"'";
			System.out.println("Update Query misc_voucher:["+sql+"]");
			pstmt = conn.prepareStatement(sql);
			System.out.println("Setting TotAmount["+totAmtHdr+"]");
			System.out.println("Setting tranIdG["+tranIdG+"]");
			//pstmt.setString(1,tranIdG);
			pstmt.executeUpdate();
			pstmt.close();

		}
		catch(Exception e)
		{
			errString1 = "EXCEPTION";
			e.printStackTrace();
		}
}
//applying dom method
public String [] saveXmlData(String xmlString, String userId, String siteCode)throws ITMException
{
	//writeXmlInFile();
	InitialContext ctx = null;
	String retString = null;
	String password = userId ;
	String retArr []=  new String[2];
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	try
	{
		AppConnectParm appConnect = new AppConnectParm();
		ctx = new InitialContext(appConnect.getProperty());
		MasterStatefulLocal masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStateful/local");
		//MasterStateful masterStateful = masterStatefulHome.create();
		retString = masterStateful.processRequest(new String[]{userId,password}, siteCode, true, xmlString);
		System.out.println("Return String in  Miscvoucher 1" + retString+"****");

		 retArr =  parse(retString);
		System.out.println("RetString is after parsing " + retString);
		if(retArr[0].equals("Success"))
		{
			retArr[0] = "CONFIRMED";
			System.out.println("Return String after asigned" + retString);
		}
		else
		{
			System.out.println("Error in voucher generatino...");
		}
	}
	catch(ITMException itme)
	{
		System.out.println("ITMException :saveXmlData :==>");
		throw itme;
	}
	catch(Exception e)
	{
		System.out.println("Exception :saveXmlData :==>");
		throw new ITMException(e);
	}
		System.out.println("Return String in  Miscvoucher 2" );
		return retArr;
}
private static Document createDom(String retString)
{
	Document dom = null;
	try
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		ByteArrayInputStream baos = new ByteArrayInputStream(retString.getBytes());
		dom = db.parse(baos);
	}
	catch(Exception e)
	{
		System.out.println("Exception occures in xmlDocument :"+e);
	}
	return dom;
}
public String [] parse(String retString)
{
	System.out.println("retString 1255461!" + retString);
	int childNodeListLen = 0;
	Document dom = null;
	String tranId ="";
	String retArr[]= new String[2];
	try
	{
		dom = createDom(retString);
		Node childNode = null, parentNode = null, parentNode1=null;
		NodeList childNodeList = null, parentNodeList = null, parentNodeList1=null;
		int ParentLen=0,ChildLen = 0;
		String Value = "";
		String childNodeName = "";
		parentNodeList = dom.getElementsByTagName("Detail");
		// Code for taking Misc Voucher Tran Id
		parentNodeList1 = dom.getElementsByTagName("TranID");
		parentNode1 = parentNodeList1.item(0);
		tranId = parentNode1.getFirstChild().getNodeValue();
		System.out.println("child node  tranId  tag is "+tranId);
		/////////////// 6/15/2006
		ParentLen = parentNodeList.getLength();
		System.out.println(ParentLen);
		for(int j = 0; j < ParentLen; j++)
		{
			parentNode = parentNodeList.item(j);
			retString = parentNode.getFirstChild().getNodeValue();
			System.out.println("child node is  detail tag is "+"  and retString  "+retString);
		}
		retArr[0] =retString;
		retArr[1] = tranId;
		System.out.println("child node is retArr [0]  detail tag is "+retArr [0]);
		System.out.println("child node is  retArr [1] detail tag is  "+retArr [1]);
	}
	catch(Exception e)
	{
		System.out.println("Exception occures in xmlDocument :"+e);
	}
		return retArr;
}
protected static void writeXmlInFile(String xmlString,String tranType,String suppCode)
{
	File mkd  = null;
	int i=0;
	String LogPath = "C:\\pb10\\log\\VOUCHER-LOG";
	FileOutputStream fos = null;
	try
	{
		mkd = new File(LogPath);
		System.out.println("Log Path:::"+LogPath);
		if(!mkd.exists())
		{
			mkd.mkdirs();
			System.out.println("Directory Built................ "+mkd);
		}
		else
		{
			String str[] = mkd.list();
			for( i=0;i<str.length;i++)
			{

				System.out.println("Deleting File:::["+LogPath+"\\"+str[i]+"]");
				mkd = new File(LogPath+"\\"+str[i]);
				mkd.delete();
				mkd = null;
			}


		}

		fos =new FileOutputStream(LogPath+File.separator+suppCode+"-"+tranType+".xml");
		byte convertStringToByte1[] = xmlString.getBytes();
		fos.write(convertStringToByte1);
		LogPath =null;

	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	finally
	{
		try
		{
			fos.close();
			mkd = null;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}


	}
}

//Validation Of The Filter Parameter
private String ValidateFilterParam(Document dom,Connection conn)
{
		String errString = "";
		String errCode = "";
		String childNodeName = "";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int cnt,ctr,currentFormNo=0;
		int childNodeListLength;
		String sql = null;

		String siteCodeTo = null;
		String siteCodeFrom= null;
		String prdCodeTo= null;
		String prdCodeFrom= null;
		String payRollDate= null;
		String empTo = null;
		String 	empFrom = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;

		try
		{
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{

						cnt = 0;
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if (childNodeName.trim().equalsIgnoreCase("prd_code__to") )
						{
							prdCodeTo = validatorEJB.getColumnValue("prd_code__to",dom);
							sql = "SELECT COUNT(*)  FROM PERIOD WHERE CODE ='"+prdCodeTo+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMPRD1";
									errString = itmDBAccessEJB.getErrorString("prd_code__to",errCode,userId);
									break;
								}
							}
						}

						else if(childNodeName.trim().equalsIgnoreCase("prd_code__fr"))
						{
							prdCodeFrom = validatorEJB.getColumnValue("prd_code__fr",dom);
							sql = "SELECT COUNT(*)  FROM PERIOD WHERE CODE ='"+prdCodeFrom+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMPRD1";
									errString = itmDBAccessEJB.getErrorString("prd_code__fr",errCode,userId);
									break;
								}
							}

						}
						else if(childNodeName.trim().equalsIgnoreCase("emp_code__fr") )
						{
							empFrom = validatorEJB.getColumnValue("emp_code__fr",dom);
							sql = "SELECT COUNT(*)  FROM EMPLOYEE WHERE EMP_CODE ='"+empFrom+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMEMP1";
									errString = itmDBAccessEJB.getErrorString("prd_code__fr",errCode,userId);
									break;
								}
							}

						}
						else if(childNodeName.trim().equalsIgnoreCase("emp_code__to") )
						{
							empTo = validatorEJB.getColumnValue("emp_code__to",dom);
							sql = "SELECT COUNT(*)  FROM EMPLOYEE WHERE EMP_CODE ='"+empFrom+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMEMP1";
									errString = itmDBAccessEJB.getErrorString("prd_code__fr",errCode,userId);
									break;
								}
							}

						}
					/*	else if(childNodeName.trim().equalsIgnoreCase("site_code__to"))
						{
							siteCodeTo = validatorEJB.getColumnValue("site_code__to",dom);
							sql = "SELECT COUNT(*)  FROM SITE WHERE SITE_CODE ='"+siteCodeTo+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMSITE1";
									errString = itmDBAccessEJB.getErrorString("site_code__to",errCode,userId);
									break;
								}
							}

						}*/
					/*	else if(childNodeName.trim().equalsIgnoreCase("site_code__fr"))
						{
							siteCodeFrom = validatorEJB.getColumnValue("site_code__fr",dom);
							sql = "SELECT COUNT(*)  FROM SITE WHERE SITE_CODE ='"+siteCodeFrom+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							System.out.println("sql :"+sql);
							if (rs.next())
							{
								cnt = rs.getInt(1);
								if (cnt == 0)
								{
									errCode = "VMSITE1";
									errString = itmDBAccessEJB.getErrorString("site_code__from",errCode,userId);
									break;
								}
							}

						}*/
						else if(childNodeName.trim().equalsIgnoreCase("payroll_date"))
						{
							java.sql.Timestamp frDate = null;
							java.sql.Timestamp toDate = null;
							java.sql.Timestamp dateFrDom =null;
							String dateFrDomStr = null;

							payRollDate =null;
							String prdCode = null;
							payRollDate = validatorEJB.getColumnValue("payroll_date",dom);
							prdCode =validatorEJB.getColumnValue("prd_code__to",dom);
							sql = "	SELECT FR_DATE, TO_DATE FROM PERIOD WHERE CODE = '"+prdCode+"'";
							System.out.println("Sql::::::::::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								frDate = rs.getTimestamp(1);
								toDate = rs.getTimestamp(2);
								System.out.println("From Date::::::::::["+frDate+"]");
								System.out.println("To Date::::::::::["+toDate+"]");
							}
							dateFrDomStr = genericUtility.getValidDateString(payRollDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
							dateFrDom = java.sql.Timestamp.valueOf(dateFrDomStr + " 00:00:00");
							System.out.println("Date From Header::::::::::["+dateFrDom+"]");
							if (!(dateFrDom.compareTo(frDate)>=0 && dateFrDom.compareTo(toDate)<=0))
							{
								errCode = "VTPAYDATE";
								errString = itmDBAccessEJB.getErrorString("payroll_date",errCode,userId);
								break;
							}
						}
					}
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		System.out.println("ErrString ::"+errString);
		return errString;
}//End Of Validation
//**********************************

	//by msalam on 130807 overloading the function
	private String  addCctrAcctr(String acctCodeSal, String cctrCodeSal, String prdCode)
	{

		HashMap parameterMap = new  HashMap();

		String acctCodeEmpMst=null;
		String cctrCodeEmpMst=null;
		String retValue=null;
		String acctCode=null;
		String cctrCode=null;
		String sql =null;
		String sql1 =null;
		java.util.HashMap acctCctrMap = new java.util.HashMap();
		double amt=0;
		double totamt =0;

		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String paybles = null;
		String post = null;
		String errFromLc =null;
		String	refType ;
		String	refNo ;
		String type1 =null;
		String postYn = null;
		String rndOff = null;
		double rndTo = 0;

		String adCode=null;
		try
		{
				acctCode = acctCodeSal;
				cctrCode = cctrCodeSal;
				if(type.equalsIgnoreCase("PP"))
				{
					//added by msalam on 140807
					sql1 = "SELECT PAYROLLDET.AMOUNT ,PAYROLLDET.PAYABLE ,PAYROLLDET.POST_YN,ALLWDEDN.AD_CODE ,PAYROLLDET.REF_TYPE  ,PAYROLLDET.REF_NO ,PAYROLLDET.TYPE ,"
					 		+" PAYROLLDET.RND_OFF ,PAYROLLDET.RND_TO "
					 		+" FROM PAYROLLDET,ALLWDEDN, EMPLOYEE "
					 		+" WHERE ALLWDEDN.AD_CODE=PAYROLLDET.AD_CODE "
					 		+" AND PAYROLLDET.EMP_CODE = EMPLOYEE.EMP_CODE "
					 		+" AND EMPLOYEE.EMP_CODE >= '"+tfromEmp.trim()+"' AND EMPLOYEE.EMP_CODE <= '"+ttoEmp.trim()+"' "
							+" AND EMPLOYEE.ACCT_CODE__SAL='" + acctCodeSal + "'"
							+" AND EMPLOYEE.CCTR_CODE__SAL = '" + cctrCodeSal + "'"
							+" AND PRD_CODE='"+prdCode+"'  " ;
					//end by msalam on 140807
				}
				System.out.println("type :["+type+"]");
				System.out.println("sql1 :"+sql1);
				pstmt = conn.prepareStatement(sql1);
				rs = pstmt.executeQuery();
				amt = 0;
				paybles = null;
				while(rs.next())
				{
					double amt1 = rs.getDouble(1);
					paybles = rs.getString(2);
					post = rs.getString(3);
					adCode = rs.getString(4);
					refType = rs.getString(5);
					refNo = rs.getString(6);
					type1 = rs.getString(7);
					rndOff = rs.getString(8);
					rndTo = rs.getDouble(9);


					//LoanCalculation loanCalculation= new LoanCalculation();
					//errFromLc = loanCalculation.gbfPayRollPost(parameterMap,conn,mtype);
					//System.out.println("errFromLc::["+errFromLc+"]");
					//loanCalculation =null;
					//if (errFromLc != null)
					//{
					//	retValue = errFromLc;
					//	break;
					//}
					//errFromLc = null;

					if("Y".equalsIgnoreCase(post))
					{
						if(("A".equalsIgnoreCase(paybles)) || ("P".equalsIgnoreCase(paybles)))
						{
								amt = amt + amt1 ;
						}
						if("D".equalsIgnoreCase(paybles))
						{
								amt = amt - amt1;
						}
					}

				}
				lineNo++;
				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((acctCode==null?" ":acctCode.trim())).append("]]></acct_code>");
				masterXmlString.append("<cctr_code><![CDATA[").append((cctrCode==null?" ":cctrCode.trim())).append("]]></cctr_code>");
				//line added by msalam on 130807
				masterXmlString.append("<tran_mode><![CDATA[").append("A").append("]]></tran_mode>");
				//end by msalam on 130807
				//next line commented and modified line added by msalam on 070807 for requirment in mail
				masterXmlString.append("<amount><![CDATA[").append(new Double(amt).toString()).append("]]></amount>");
				//modified line commented as told by subu kumar
				//masterXmlString.append("<amount><![CDATA[").append(new Double(-amt).toString()).append("]]></amount>");
				//end by msalam on 070807
				masterXmlString.append("<anal_code><![CDATA[").append("").append("]]></anal_code>");  //9/8/2006
				masterXmlString.append("<emp_code><![CDATA[").append("").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><![CDATA[").append("Voucher For Period["+prdCode+"] for AC ["+ acctCode +"] for CC ["+ cctrCode +"]").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("").append("]]></tax_class>");
				masterXmlString.append("<tax_chap><![CDATA[").append("").append("]]></tax_chap>");
				masterXmlString.append("<tax_env><![CDATA[").append("").append("]]></tax_env>");
				masterXmlString.append("</Detail3>");
				rs.close();
				pstmt.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		acctCctrMap = null;
		parameterMap.clear();
		System.out.println("Retunning Error String From addCctrAcctr()"+retValue);
		return retValue;
	}

	//end by msalam overloading

	//added by msalam on 140807
	private class AcctCctrDetail{

		public double amount = 0.0;
		public String paybles = null;
		public String post = null;
		public String adCode = null;
		public String errFromLc =null;
		public String refType ;
		public String refNo ;
		public String type =null;
		public String postYn = null;
		public String rndOff = null;
		public double rndTo = 0;
		public String acctCodeSal = null;
		public String acctCctrSal = null;

	}
	//end by msalam on 140807

	//added by msalam on 160807
	private String  custLoanCalculation(String empCode,String prdCode,Customer customer)
	{

		HashMap parameterMap = new  HashMap();

		String acctCodeEmpMst=null;
		String cctrCodeEmpMst=null;
		String retValue=null;
		String acctCode=null;
		String cctrCode=null;
		String sql =null;
		String sql1 =null;
		java.util.HashMap acctCctrMap = new java.util.HashMap();
		double amt=0;
		double totamt =0;

		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String paybles = null;
		String post = null;
		String errFromLc =null;
		String	refType ;
		String	refNo ;
		String type1 =null;
		String postYn = null;
		String rndOff = null;
		double rndTo = 0;
		
		//ADDED BY MSALAM ON 03/10/07
		double baseAmt = 0.0;
		double slabAmt = 0.0;
		double resultAmt = 0.0;
		String seqNo = null;
		double calcAmt = 0.0;
		//END ADDED BY MSALAM ON 03/10/07
		//addvariable to parameter
		//******************************
		System.out.println( "In Cust Loan Calculation!!!!!!!!!!!!!!!" );
		//parameterMap.put("post_yn",customer.getPostYN());
		parameterMap.put( "post_yn", "Y" );
		parameterMap.put( "emp_code",empCode );
		parameterMap.put( "prd_code",prdCode );
	//	parameterMap.put("type",type);
		String mtype = this.type;
		parameterMap.put("site_code",customer.getSiteCodePay());
		parameterMap.put("dept_code",customer.getDeptCode());
		parameterMap.put("grade",customer.getCrade());
		parameterMap.put("cadre",customer.getGrade());
		parameterMap.put("design",customer.getDesignation());
		parameterMap.put("pay_table",customer.getPayTable());
		parameterMap.put("site_emp",customer.getSiteEmp());
		parameterMap.put("site_work",customer.getSiteWork());
		parameterMap.put("prd_comp",prdCode);
		parameterMap.put("proc_group_fr",frProc);
		parameterMap.put("proc_group_to",toProc);
		parameterMap.put("user_id",userId);
		parameterMap.put("chg_term",chgTerm);

	//	***********************************
	//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())
			{
				acctCodeEmpMst = rs.getString(1);
				cctrCodeEmpMst = rs.getString(2);
			}
			if(acctCodeEmpMst==null){System.out.println("Account Code not Found in Employee Master!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");}
			else{System.out.println("Account Code From employee:::["+acctCodeEmpMst+"]");}
			if(cctrCodeEmpMst==null)
				{System.out.println("Cost Center  Code not Found in Employee Master!!!!!!!!!!!!!!!!!!!!!!!!!!!");}
			else{System.out.println("Cost Center  Code From employee:::["+cctrCodeEmpMst+"]");}
			rs.close();
			pstmt.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	    if(type.equalsIgnoreCase("PP"))
	    {
	    	mtype = "PP";
			 sql = "SELECT PAYROLLDET.AMOUNT ,PAYROLLDET.PAYABLE ,PAYROLLDET.POST_YN,ALLWDEDN.AD_CODE ,PAYROLLDET.REF_TYPE  ,PAYROLLDET.REF_NO ,PAYROLLDET.TYPE ,"
					+" PAYROLLDET.RND_OFF ,PAYROLLDET. RND_TO, base_amt, slab_amt, result_amt, PAYROLLDET.seq_no, PAYROLLDET.CALC_AMT FROM PAYROLLDET,ALLWDEDN WHERE ALLWDEDN.AD_CODE=PAYROLLDET.AD_CODE"
					+" AND EMP_CODE='" + empCode + "' AND PRD_CODE='" + prdCode + "'" ;
		}
		else
		{
			mtype = "ARR";
			 sql = " SELECT ARREARDET.DIFF_AMT ,ARREARDET.PAYABLE ,ARREARDET.POST_YN ,ALLWDEDN.AD_CODE ,ARREARDET.REF_TYPE  ,ARREARDET.REF_NO,ARREARDET.type , "
					+ " ARREARDET.RND_OFF ,ARREARDET.RND_TO, ARREARDET.base_amt, ARREARDET.slab_amt, ARREARDET.result_amt, ARREARDET.seq_no, ARREARDET.CALC_AMT "
					+ " FROM ARREARDET,ALLWDEDN WHERE ALLWDEDN.AD_CODE=ARREARDET.AD_CODE "
				 	+ " AND EMP_CODE='" + empCode + "' AND PRD_CODE='" + prdCode + "'" ;

		}
		System.out.println("AdCode Query="+sql);
		String adCode=null;
		try
		{
			if((acctCodeEmpMst != null) && (cctrCodeEmpMst!=null) )
			{

				acctCode = acctCodeEmpMst;
				cctrCode = cctrCodeEmpMst;
				if(type.equalsIgnoreCase("PP"))
				{
					mtype = this.type;
				 	sql1 = "SELECT PAYROLLDET.AMOUNT ,PAYROLLDET.PAYABLE ,PAYROLLDET.POST_YN,ALLWDEDN.AD_CODE ,PAYROLLDET.REF_TYPE  ,PAYROLLDET.REF_NO ,PAYROLLDET.TYPE ,"
							+" PAYROLLDET.RND_OFF ,PAYROLLDET. RND_TO, base_amt, slab_amt, result_amt, PAYROLLDET.seq_no, PAYROLLDET.CALC_AMT FROM PAYROLLDET,ALLWDEDN WHERE ALLWDEDN.AD_CODE=PAYROLLDET.AD_CODE"
							+" AND EMP_CODE='" + empCode + "' AND PRD_CODE='" + prdCode + "'" ;
				}
				else
				{
					mtype = this.type;
					 sql1 = " SELECT ARREARDET.DIFF_AMT ,ARREARDET.PAYABLE ,ARREARDET.POST_YN ,ALLWDEDN.AD_CODE ,ARREARDET.REF_TYPE  ,ARREARDET.REF_NO,ARREARDET.type , "
							+ " ARREARDET.RND_OFF ,ARREARDET.RND_TO, ARREARDET.base_amt, ARREARDET.slab_amt, ARREARDET.result_amt, ARREARDET.seq_no, ARREARDET.CALC_AMT "
							+ " FROM ARREARDET,ALLWDEDN WHERE ALLWDEDN.AD_CODE=ARREARDET.AD_CODE "
						 	+ " AND EMP_CODE='" + empCode + "' AND PRD_CODE='" + prdCode + "'" ;
				}
				System.out.println("type :[" + type + "]");
				System.out.println("One Record Qry :" + sql1);
				pstmt = conn.prepareStatement( sql1 );
				rs = pstmt.executeQuery();
				amt = 0;
				paybles = null;
				while(rs.next())
				{
					double amt1 = rs.getDouble( "AMOUNT" );
					paybles = rs.getString( "PAYABLE" );
					post = rs.getString( "POST_YN" );
					adCode = rs.getString( "AD_CODE" );
					refType = rs.getString( "REF_TYPE" );
					refNo = rs.getString( "REF_NO" );
					type1 = rs.getString( "TYPE" );
					rndOff = rs.getString( "RND_OFF" );
					rndTo = rs.getDouble( "RND_TO" );
					//next 5 lines added by msalam on 03/10/07
					baseAmt = rs.getDouble( "BASE_AMT" );
					slabAmt = rs.getDouble( "SLAB_AMT" );
					resultAmt = rs.getDouble( "result_amt" );
					seqNo = rs.getString( "SEQ_NO" );
					calcAmt = rs.getDouble( "CALC_AMT" );

					parameterMap.put("type",type1);
					parameterMap.put( "post_yn", "Y" );
					parameterMap.put( "ad_code", adCode );
					parameterMap.put( "amount", Double.toString(amt1) );
					parameterMap.put( "ref_type", refType );
					parameterMap.put( "ref_No", refNo );
					parameterMap.put( "rnd_off", "R" );
					parameterMap.put( "rnd_to", Double.toString(rndTo) );
					//next 5 lines added by msalam on 03/10/07
					parameterMap.put( "base_amt", Double.toString(baseAmt) );
					parameterMap.put( "slab_amt", Double.toString(slabAmt) );
					parameterMap.put( "result_amt", Double.toString(resultAmt) );
					parameterMap.put( "seq_no", seqNo );
					parameterMap.put( "calc_amt", Double.toString(resultAmt) );
					
					LoanCalculation loanCalculation= new LoanCalculation();
					System.out.println( "Out going Input Map::[" + parameterMap.toString() + "]" );
					errFromLc = loanCalculation.gbfPayRollPost( parameterMap, conn, mtype, mtype );
					System.out.println( "errFromLc::[" + errFromLc + "]" );
					loanCalculation = null;
					if (errFromLc != null)
					{
						retValue = errFromLc;
						break;

					}
					errFromLc = null;

					if("Y".equalsIgnoreCase(post))
					{
						if(("A".equalsIgnoreCase(paybles)) || ("P".equalsIgnoreCase(paybles)))
						{
								amt = amt + amt1 ;
						}
						if("D".equalsIgnoreCase(paybles))
						{
								amt = amt - amt1;
						}
					}

				}
				rs.close();
				pstmt.close();
			}
			else
			{
					System.out.println("Query to be fired(Else) ::::["+sql+"]");
			 		paybles = null;
					amt =0;
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						acctCode = null;
						amt = 0;
						cctrCode = null;

						amt = rs.getDouble( "AMOUNT" );
						adCode = rs.getString( "AD_CODE" );
						paybles = rs.getString( "PAYABLE" );
						post =  rs.getString( "POST_YN" );
						refType = rs.getString( "REF_TYPE" );
						refNo =  rs.getString( "REF_NO" );
						type1 =  rs.getString( "TYPE" );
						rndOff = rs.getString( "RND_OFF" );
						rndTo = rs.getDouble( "RND_TO" );
						//next 5 lines added by msalam on 03/10/07
						baseAmt = rs.getDouble( "BASE_AMT" );
						slabAmt = rs.getDouble( "SLAB_AMT" );
						resultAmt = rs.getDouble( "result_amt" );
						seqNo = rs.getString( "SEQ_NO" );
						calcAmt = rs.getDouble( "CALC_AMT" );

						parameterMap.put( "post_yn", "Y" );
						parameterMap.put( "rnd_off", rndOff );
						parameterMap.put( "rnd_to", Double.toString( rndTo ) );

						parameterMap.put( "ad_code", adCode );
						parameterMap.put("type",type1);
						
						parameterMap.put( "amount", Double.toString( amt ) );
						parameterMap.put( "ref_type", refType );
						parameterMap.put( "ref_no", refNo );
						//next 5 lines added by msalam on 03/10/07
						parameterMap.put( "base_amt", Double.toString(baseAmt) );
						parameterMap.put( "slab_amt", Double.toString(slabAmt) );
						parameterMap.put( "result_amt", Double.toString(resultAmt) );
						parameterMap.put( "seq_no", seqNo );
						parameterMap.put( "calc_amt", Double.toString(resultAmt) );

						LoanCalculation loanCalculation= new LoanCalculation();
						errFromLc = loanCalculation.gbfPayRollPost( parameterMap, conn, mtype, mtype );
						System.out.println("errFromLc::["+errFromLc+"]");
						loanCalculation =null;
						if (errFromLc != null)
						{
							retValue = errFromLc;
							break;

						}

						if(acctCodeEmpMst != null)
						{
							acctCode =acctCodeEmpMst;
						}
						else
						{
							acctCode  = rs.getString(2);
						}
						//***ADDED ON 16042007
						if(acctCode == null && ("Y".equalsIgnoreCase(post)))
						{
							retValue = adCode;
							break;
						}
						cctrCode= rs.getString(3);

						if(cctrCode == null)
						{
							cctrCode = "X";
						}
						String key = acctCode+"-"+cctrCode;
						if(acctCctrMap.containsKey(key))
						{
							totamt = 0;
							totamt = Double.parseDouble(acctCctrMap.get(key).toString());
							if("Y".equalsIgnoreCase(post))
							{
								if("A".equalsIgnoreCase(paybles)|| ("P".equalsIgnoreCase(paybles)))
								{
									totamt = totamt + amt ;
								}
								if("D".equalsIgnoreCase(paybles))
								{
									totamt = totamt - amt ;
								}
								acctCctrMap.put(key,new Double(totamt));
							}


						}
						else
						{
							if("Y".equalsIgnoreCase(post))
							{
								if("D".equalsIgnoreCase(paybles))
								{
									amt = -amt;
								}
								acctCctrMap.put(key,new Double(amt));
							}

						}
					}
				}//end if
			}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		acctCctrMap = null;
		parameterMap.clear();
		System.out.println("Retunning Error String From addCctrAcctr()"+retValue);
		return retValue;
	}

	//end by msalam on 160807

	private String makeListStr(ArrayList empList)
	{
		String listStr = "";
		Customer cust = null;

		for(int i=0; i < empList.size(); i++)
		{
			cust = (Customer) empList.get(i);
			listStr += "'" + cust.getEmpCode() + "'" + (i == empList.size() - 1 ? "" : ", ");
		}
		return (listStr);
	}
	private String getPeriodCode(String date, Connection conn) throws Exception
	{
		String prdCode = null;
		String sql = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Timestamp dateTS = null;
		try
		{
			dateTS = Timestamp.valueOf(genericUtility.getValidDateString(date, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
			sql = "SELECT CODE FROM PERIOD WHERE FR_DATE <= ? AND TO_DATE >= ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, dateTS);
			pstmt.setTimestamp(2, dateTS);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				prdCode = rs.getString(1);
			}
			rs.close(); rs = null;
			pstmt.close(); pstmt = null;
		}
		catch(Exception e)
		{
			System.out.println("Exception in [JobOrderEJB] [getPeriodCode]==>" + e.getMessage());
			throw e;
		}
		return prdCode;
	}


}//END OF EJB