/*
	Modification:-
	1-20062007 
	______________________
	1. it reads the punchstr,lunchhours from attendance_day, and  deduction from attd_dedn, 
	using this data it calculate actualworktime. 
	2. it calculate paidhour using leave,weakelyoff,holiday,tour.
	3. it calculate othour on daily basis using paidhour & shifthour and make entry in empotime_det on daily basis.
	4. shifthour is fetched from workshft for dayno & epmloyee shift .( shift is fetch from work_shift)
	5. it calculate ot  for ot timespan make its entry in empotime on monthly basis.
	6. it make entry of work_hour,paid_hour,othour in attd_reg on daily basis .
	7. it make entry of work_hour,paid_hour in  attendatce_mon for total attendance processing span.
	8. if status is 'A' it makes entry in attendance_absent.
	9. processing time span is fetched from period table .
	10. ot timespan is fetched from work_balance.
	11. for calculating ottimespan it first find workcode from employee table and using it it find out 
	ottimespan for from work_balance.
	12.before processing it check entry in attd_reg,empotime_det,attendance_absent for processing span 
	   if entry found  it delete those entrys.
*/
package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.util.*;
import java.sql.*;
import java.util.Calendar;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import org.w3c.dom.*;
import java.text.NumberFormat;
import java.io.*;

//import javax.ejb.SessionBean;
import javax.ejb.CreateException;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import ibase.system.config.*;
import javax.ejb.Stateless; // added for ejb3
@Stateless
public class AttdProcess extends ProcessEJB implements  AttdProcessLocal ,AttdProcessRemote	//SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	CommonConstants commonConstants = new CommonConstants();
	String chgUser = null;
	String chgTerm = null;
	String userId= "";
	String termId= "";
	Timestamp today = new java.sql.Timestamp(System.currentTimeMillis());
	ResultSet rsn1=null,rsn2=null,rsn3=null,rsn4=null,rsn5=null,
			rsn6=null,rsn7=null,rsn8=null,rsn9=null,rsn10=null,
		rsn11=null,rsn12=null,rsn13=null,rsn14=null,rsn15=null,
		rsn16=null,rsn17=null,rsn18=null,rsn19=null,rsn20=null,
		rsn21=null;
	PreparedStatement stmt14=null;

	//Added by Nisar on 21/02/07
	/*File filePtr = new File("C:\\pb10\\log\\pbnitrace.log");

	static
	{
			File mkd = new File("C:\\pb10\\log");
			if(!mkd.exists())
			{
				mkd.mkdirs(); 
				System.out.println("Directory Built................ "+mkd);
			}			
	}
	//ended by nisar on 21/02/07*/

	

  /*public void ejbCreate() throws RemoteException, CreateException
	{
		try
		{
			System.out.println("AttdProcessEJB ejbCreate called.........");
		}
		catch (Exception e)
		{
			System.out.println("Exception :AttdProcessEJB :ejbCreate :==>"+e);
			e.printStackTrace();
			throw new CreateException();
		}
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("process(xmlString,xmlString2,windowName,xtraParams CALLED..."+ xmlString);
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String2 :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			errString = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :AttdProcessEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			//throw new ITMException(e);
		}
		return errString; 
	}

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		ConnDriver connDriver = new ConnDriver();
		System.out.println("Process function called from process().........");
		String errString = "";
		StringBuffer retTabSepStrBuff = new StringBuffer();
		String payrollDate = "";
		String siteCodeFrom = "";
		String siteCodeTo = "";
		String empCodeFrom = "";
		String empCodeTo = "";
		String procGroupFrom = "";
		String procGroupTo = "";
		String status = "";
		String cutOffDateString = "";
		String prdCode = "";
		String curEmp = "";
		String sql = "";
		String grade = "";
		String withHeld = "";
		String paySite = "";
		String designation = "";
		String payrollDateString = "";
		String empFName = "";
		String empLName = "";
		String deptCode ="";
		String errCode = "";
		Connection conn = null;
		int noDays = 0;
		//ResultSet rsSelEmp = null;
		//ResultSet rs = null;
		PreparedStatement pstmtSelEmp = null;
		Statement stmtn1 = null;
		Timestamp dateJoin = null;
		Timestamp relieiveDate = null;
		Timestamp fromDate = null;
		Timestamp toDate = null;
		Timestamp cutOffDate = null;
		try
		{
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			conn = connDriver.getConnectDB("DriverITM");
			
			conn.setAutoCommit(false);
			System.out.println("xtraParams : "+xtraParams);
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			termId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			System.out.println("userId: " +userId+ " TermId: " +termId);

			prdCode = genericUtility.getColumnValue("prd_code__fr",headerDom);
			empCodeFrom = genericUtility.getColumnValue("emp_code__fr",headerDom);

			if ( empCodeFrom == null || empCodeFrom.trim().length() == 0 )
			{	
				empCodeFrom = "0";
			} 
			empCodeTo = genericUtility.getColumnValue("emp_code__to",headerDom);
			if ( empCodeTo == null || empCodeTo.trim().length() == 0 )
			{	
				empCodeTo = "ZZZZZZZZZZ";
			}
			siteCodeFrom = genericUtility.getColumnValue("site_code__fr",headerDom);
			if ( siteCodeFrom == null || siteCodeFrom.trim().length() == 0 )
			{
				siteCodeFrom = "0";
			} 
			siteCodeTo = genericUtility.getColumnValue("site_code__to",headerDom);
			if ( siteCodeTo == null || siteCodeTo.trim().length() == 0 )
			{
				siteCodeTo = "ZZZZZ";
			} 
			procGroupFrom = genericUtility.getColumnValue("proc_group__from",headerDom);
			if ( procGroupFrom == null || procGroupFrom.trim().length() == 0 )
			{
				procGroupFrom = "0";
			} 
			procGroupTo = genericUtility.getColumnValue("proc_group__to",headerDom);
			if ( procGroupTo == null || procGroupTo.trim().length() == 0 )
			{
				procGroupTo = "ZZZZZ";
			} 
			payrollDateString = genericUtility.getColumnValue("payroll_date",headerDom);
			String noDaysStr = genericUtility.getColumnValue("no_days",headerDom);
			if( noDaysStr == null)
				noDays = 0;
			else
				noDays = Integer.parseInt(noDaysStr);

			cutOffDateString = genericUtility.getColumnValue("cutoff_date",headerDom);  // add from vanita
			if ( cutOffDateString != null)
			{
				System.out.println(">>>>>>>>>>  cutOffDateString  before  "+cutOffDateString);
				if(cutOffDateString.indexOf(' ')!= -1)
				{
					cutOffDateString=cutOffDateString.substring(0,cutOffDateString.indexOf(' '));
				}
				if (cutOffDateString.indexOf("-") != -1)
				{
					cutOffDateString=cutOffDateString.replace('-','/');
				}

				System.out.println(">>>>>>>>>>  cutOffDateString  after  " + cutOffDateString);
				cutOffDateString = genericUtility.getValidDateString(cutOffDateString, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
				cutOffDate = java.sql.Timestamp.valueOf(cutOffDateString + " 00:00:00");
			} 
			System.out.println("prdCode : " + prdCode + "  empCodeFr :" + empCodeFrom + " empCodeTo :"+empCodeTo+"  siteCodeFr :"+siteCodeFrom+ "  procGroupFrom : " +procGroupFrom+ "  procGroupTo : " + procGroupTo);
			if (siteCodeFrom != null )
			{
				// get the to and from dates from period table
				sql = " SELECT FR_DATE, TO_DATE  "         
					+ " FROM 	PERIOD "  
					+ " WHERE CODE = '" + prdCode + "'";  
					System.out.println("sql:::"+sql); 

				stmtn1 = conn.createStatement();
				rsn1 = stmtn1.executeQuery(sql);
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n1 Opened",true);
				if(rsn1.next())
				{
					fromDate = rsn1.getTimestamp(1);
					toDate = rsn1.getTimestamp(2);
				}
				else  
				{
					System.out.println("No Records found in PERIOD for Prd Code : " + prdCode);
					errString = itmDBAccessEJB.getErrorString("","VMPRDCDX","","",conn);					
					return errString;			
				}  
				System.out.println("From Date : " + fromDate + "   To Date : " + toDate);
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n1 Closed",true);
				rsn1.close();
				rsn1=null;
				stmtn1.close();
				stmtn1=null;
				sql = "SELECT EMP_CODE, EMP_FNAME, EMP_LNAME, DATE_JOIN, DESIGNATION, DEPT_CODE, PAY_SITE, WITH_HELD, GRADE, RELIEVE_DATE, STATUS  "
					+ "FROM EMPLOYEE  "
					+ "WHERE ( EMP_CODE BETWEEN '" + empCodeFrom + "' AND '" + empCodeTo + "' ) AND  "
					+ "( WORK_SITE BETWEEN '" + siteCodeFrom + "' AND '" + siteCodeTo + "' ) AND  "
					+ "NOT(NVL(STATUS,' ') = 'S' AND  "
					+ "RELIEVE_DATE <= ? ) AND  " 
					+ "DATE_JOIN <= ? AND  "
					+ "PROC_GROUP BETWEEN '" + procGroupFrom + "' AND '" + procGroupTo + "'";
				System.out.println("SQL : " + sql);
				pstmtSelEmp = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
				pstmtSelEmp.setTimestamp(1,fromDate);
				pstmtSelEmp.setTimestamp(2,toDate);
				rsn2 = pstmtSelEmp.executeQuery();
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n2 Opened",true);
				if(!rsn2.next())
				{
					errCode = "VTNOROWS";
					errString = itmDBAccessEJB.getErrorString("","VTNOROWS",userId);
				}
				else
					rsn2.beforeFirst();
				while(rsn2.next())
				{
					curEmp = rsn2.getString(1);
					empFName = rsn2.getString(2);
					empLName = rsn2.getString(3);
					dateJoin = rsn2.getTimestamp(4);
					designation = rsn2.getString(5);
					deptCode = rsn2.getString(6);
					paySite = rsn2.getString(7);
					withHeld = rsn2.getString(8);
					grade = rsn2.getString(9);
					relieiveDate = rsn2.getTimestamp(10);
					status = rsn2.getString(11);
					System.out.println("relieve Date :: " + relieiveDate);
					System.out.println("Processing for prdCode : " + prdCode + " curEmp : " + curEmp);
					if (relieiveDate != null)
					{
						System.out.println(relieiveDate.toString() + " :: " + fromDate.toString()  + " : " + relieiveDate.after(fromDate));
						//if (relieiveDate.after(fromDate)) // To be clarified - Jiten
						//modified by ms alam on 26/06/07 as it was bug to consider fromDate
						if (relieiveDate.after(toDate)) 
						{
							continue;
						}
					}
					System.out.println("Befor Call to attdProcess ......");
					errString = attdProcess(fromDate,toDate,curEmp,prdCode,conn);
					System.out.println("After Call to attdProcess ......");
					if(errString.indexOf("VTPROSUC") == -1){
						break;
					}
				}//end of if for sitecodefrom
				if(errString.indexOf("VTPROSUC") >= 0){
					//System.out.println("Success************** ");
					//errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);

					System.out.println("Commit transaction**********");
					if(conn!=null)
						conn.commit();
					// Modified by Piyush on 19/03/2015 [To show message in RCP].Start
					// errString = "";
					if( xtraParams.indexOf("user_lang=") == -1)						
					{
						errString = "";
					}
					// Modified by Piyush on 19/03/2015 [To show message in RCP].Start
				}
				else{
					//System.out.println("Not Successful************** ");
					//errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);

					if(conn!=null)
						conn.rollback();
				}
				rsn2.close();
				rsn2=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n2 Closed",true);
				pstmtSelEmp.close();
				pstmtSelEmp=null;
			}
		}
		catch(SQLException se)
		{
			System.out.println("SQLException :AttdProcessEJB : ==>\n" + se);
			se.printStackTrace();
			errCode = "VTPROUNSUC";
			errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
			//throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception :AttdProcessEJB :==>\n"+e.getMessage());
			e.printStackTrace();
			errCode = "VTPROUNSUC";
			errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
			try
			{
				if(conn!=null)
				conn.rollback();
			}
			catch(Exception e1)
			{
				e =e1;
			}
			throw new ITMException(e);
		}
		finally
		{
			try
			{		
				if(conn != null)
				{	
					conn.close();
				}
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
		}
		
		return errString ;
	}

	public String attdProcess(Timestamp fromDate, Timestamp toDate,String empCode,String prdCode,Connection conn ) throws RemoteException,ITMException
	{
		PreparedStatement stmt = null,stmtn11=null,stmtn12=null,stmtn13=null,stmtn14=null,stmtn16=null;
		PreparedStatement stmt1 = null,stmt15=null,stmtn5=null,stmtn6=null,stmtn4=null;
		PreparedStatement updstmt = null;
		Statement crstmt = null,crstmtn4=null;
		Statement stmt11 = null,stmt10=null,stmt9=null;
		String errString = "";
		double workHour = 0;
		long worTimeInMin =0;
		long stTimeImMilsec=0;
		long edTimeImMilsec=0;
		long noOfDays=0;
		long dayTminMilsec=0;
		long totactWorkTimeMin =0;
		long totPaidLeaveInMin =0;
		double totPaidLeaveInDay =0;
		double workToDoPerDay =0;
		long dednTimeInMin =0;
		long totDednTimeInMin =0;
		long paidTimeInMin =0;
		long totPaidTimeInMin =0;
		long totWoffinMin =0;
		long totWoffinDay =0;
		long actWorkTime =0;
		long paidLeave =0;
		long otTimeMin =0;
		String othour ="0";
		double totOtHours =0;
		String actWorkTimeInHr ="0";
		double totWorkTimeForOt =0;
		int count =0;
		int count1 =0;
		String status = "A";
		String punchStr = null;
		String sqlTimeIn = "";
		String wShftsql = "";
		String sqlDednIn = "";
		String sqlDelReg = "";
		String sqlDelempotime_det = "";
		String sqlDelAttd_Abs = "";
		String sqlDelempotime = "";
		String sqlWorkBal = "";
		String sqlLeave = "";
		String insertRegSql = "";
		String insertEmpotimeSql = "";
		String updateEmpotimeSql = "";
		String insertEmpotime_detSql = "";
		String insertAttd_AbsSql = "";
		String work_Shiftsql = "";
		String selectFrmMon = "";
		String updateMon = "";
		String insertMon = "";
		String iTime = "";
		String oTime = "";
		String shift = "";
		long lunchTimeInMin = 0;
		String eligibleOt ="";
		String emp_EligibleOt ="";
		Timestamp chgDate = null;
		Timestamp otStDate = null;
		ArrayList otStartDateArr = new ArrayList();
		ArrayList otEndDateArr = new ArrayList();
		ArrayList paidPrdCodeArr = new ArrayList();
		Timestamp otFrom = null;
		Timestamp otTo = null;
		Timestamp otEdDate = null;
		Timestamp lveDateFrom=null;
		Timestamp otTimeFr=null;
		Timestamp otTimeTo=null;
		Timestamp lveDateTo=null;
		String chgUsr = "";
		String paidPrCodeStr = "0";
		int paidPrCode = 0;
		String paidTimeInHr = "";
		String actWorkTimeHr = "";
		String totPaidTimeInHr = "";
		String totactWorkTimeHr = "";
		String totWoffinHr = "";
		String paidLeaveHr = "";
		String workSite = "";
		String holTblNo = "";
		String cadre = "";
		String grade = "";
		String workCode = "";
		String single = "";
		String sql = "";
		String tourStarts = "";
		String tourEnds = "";
		String holNonPayable = "";
		String woffPayable = "";
		String holPayDouble = "";
		String woffPayDouble = "";
		String procDateStr=null;
		String holTblNoFr=null;
		String holType=null;
		String keyStringQuery = null;
		String tranId = null;
		boolean  isExist=false; 
		boolean  isOtEdDateInSpan=false; 
		boolean  isOtStDateInSpan=false; 
		boolean  isOtSpanExist=false; 
		boolean isHolidayPaid=false;//Added by Nisar 08/02/07
		String errCode ="";
		
		//ResultSet rs = null;
		//ResultSet rs1 = null,rs2 = null,rs14=null;
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues=null;
		int fullDayHr=0;
		int noDay=0;
		int halfDayHr=0;
		int dayOfWeek=0;
		int paidHoliDay=0;
		int woff=0;
		int paidWoff=0;
		int tourDay=0;
		int tourTimeInMin=0;
		int chkMonth=-1;
		int noOfOtDays=0;
	//	int tranId=1;
		int empotimeUpdate=0;
		double workDay=0;
		double paidDay=0;
		int holWoffDay=0;
		double leaveDay=0;
		double TotWorkDay=0;
		double TotPaidDay=0;
		String formatOtTimeInHrs = ""; //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
		Timestamp procDate=fromDate;

		java.util.Date tourStartDate = null;//Added by jaimin on 13/06/2008 (AD89SUN013)
		java.util.Date tourEndDate = null;//Added by jaimin on 13/06/2008 (AD89SUN013)

		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		System.out.println(">>>>>>>>>  procDate :"+procDate+"  empCode : "+empCode);
		
		//previous code
		sqlDelReg = "DELETE FROM ATTD_REG WHERE EMP_CODE = ?"+ "AND ATTD_DATE BETWEEN ? AND ? ";
		
		//20062007

		//modified and added By msalam on 25/06/07 as dont delete those records which are approved in empotime_det
		
		//sqlDelReg = "DELETE FROM ATTD_REG WHERE EMP_CODE = ?"+ " AND ATTD_DATE = ? ";
		//End by ms alam

		sqlDelempotime_det = "DELETE FROM EMPOTIME_DET WHERE  OT_DATE  BETWEEN ? AND ? AND EMP_CODE='"+empCode+"' AND NVL(APPROVED_FLAG, 'N') = 'N'";
		sqlDelAttd_Abs = "DELETE FROM ATTENDANCE_ABSENT WHERE  EMP_CODE= ? AND ATTD_DATE  BETWEEN ? AND ?";
		sqlDelempotime = "DELETE FROM EMPOTIME WHERE TRAN_ID = ? AND EMP_CODE='"+empCode+"'";

		System.out.println("sqlDelempotime_det:::"+sqlDelempotime_det ); 
		System.out.println("sqlDelAttd_Abs:::"+sqlDelAttd_Abs); 
		System.out.println("sqlDelempotime:::"+sqlDelempotime); 

		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); //Added by jaimin on 13/06/2008 (AD89SUN013)
			tranId = getExistTranId(empCode,procDate,conn); // gets Tran_id from empotime - Jiten
			if(tranId == null)
			 // Modified by Piyush on 19/03/2015 [To pass required parameters to generate tran id as per transetup. Issues resolved during RCP migration]
			 // tranId = getTranId(conn); 
			 tranId = getTranId(empCode,procDate,conn);
			else
				isExist=true;
		
			otTimeFr=fromDate; 
			
			AdmCommon admCommon = new AdmCommon();
			
			int delAttdReg = -1;
			//1. Deleting Attd_reg
			//msalam
			
			System.out.println("Del attd Reg :: " + sqlDelReg);
			
			System.out.println("From Date = " + fromDate + ",  toDate = " + toDate);
			stmt = conn.prepareStatement(sqlDelReg);
			
			//previous code
			stmt.setString(1, empCode);
			stmt.setTimestamp(2, fromDate);
			stmt.setTimestamp(3, toDate);

			delAttdReg = stmt.executeUpdate();
			System.out.println("delAttdReg :: " + delAttdReg);
			
			//modified by msalam on 25/06/07 to filter approved records in empotime_det
			/*
			Timestamp tFromDate = fromDate;
			int delAttdReg = -1;

			while(tFromDate.before(toDate)){
				stmt.setString(1, empCode);
				stmt.setTimestamp(2,tFromDate);

				//int delAttdReg = stmt.executeUpdate(sqlDelReg);
				if(!isApprevedExistFor(empCode, tFromDate, conn)){
					delAttdReg = stmt.executeUpdate();
					System.out.println("Deleted From Attd_reg EmpCode = " + empCode + " :: Date = " + tFromDate);
					System.out.println("delAttdReg :: " + delAttdReg);
				}
				tFromDate = getAddDateInTimestamp(tFromDate, 1);
			}
			*/
			stmt.close();
			stmt=null;
			
//			System.out.println("attd del :: " + sqlDelReg);
			System.out.println("attd del :: " + sqlDelAttd_Abs);
			
			//2. Deleting Attendance_absent
			
			stmt = conn.prepareStatement(sqlDelAttd_Abs);
			stmt.setString(1,empCode);
			stmt.setTimestamp(2,fromDate);
			stmt.setTimestamp(3,toDate);
			int delAttd_Abs = stmt.executeUpdate();
			stmt.close(); 
			stmt=null;

			System.out.println("No of records deleated from  attendance_absent "+delAttd_Abs); 

			sql = "SELECT WORK_SITE, HOL_TBLNO, CADRE ,ELIGIBLE_OT,GRADE,WORK_TBLNO "   
				+ "FROM  EMPLOYEE "
				+ "WHERE EMP_CODE = '" + empCode + "'";
			
			System.out.println("sql:::"+sql); 
			crstmt = conn.createStatement();
			rsn3 = crstmt.executeQuery(sql);	
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n3 Opened",true);
			if (rsn3.next())
			{
				workSite = rsn3.getString(1);
				holTblNo = rsn3.getString(2);
				cadre = rsn3.getString(3);
				emp_EligibleOt = rsn3.getString(4);
				grade = rsn3.getString(5);
				workCode = rsn3.getString(6);
			}
			crstmt.close();
			crstmt=null;
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n3 Closed",true);
			rsn3.close();
			rsn3=null;
			//sqlWorkBal = "SELECT WORK_HOUR,START_DATE,END_DATE,PAID_PRDCODE FROM WORK_BALANCE WHERE PERIOD_CODE ='"+workCode+"'";
//			sqlWorkBal = "SELECT START_DATE,END_DATE,PRD_CODE__PAY FROM WORK_TABLE WHERE WORK_TBLNO ='"+workCode+"' ";//AND PRD_CODE__PAY = '"+prdCode+"'";  
//			sqlWorkBal = "SELECT START_DATE,END_DATE,PRD_CODE__PAY FROM WORK_TABLE WHERE WORK_TBLNO ='"+workCode+"' AND PRD_CODE__PAY = '"+prdCode+"'"; //COMMENT REMOVED BY ALKA 02/08/07
/*			System.out.println("sqlWorkBal:::"+sql); 
			crstmtn4 = conn.createStatement();
			rsn4 = crstmtn4.executeQuery(sqlWorkBal);
			System.out.println("SQL :: "+sqlWorkBal); */
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n4 Opened",true);
	 		
			//3. Delete from EmpOtime_det table for the given empCode having given work Order.
			//msalam
/*			while (rsn4.next())
			{
				//workHour = Double.parseDouble(rsn4.getString(1));
				otStDate = rsn4.getTimestamp(1);
				otEdDate = rsn4.getTimestamp(2);
				paidPrCodeStr = rsn4.getString(3);
				otStartDateArr.add(otStDate);
				otEndDateArr.add(otEdDate);
				paidPrdCodeArr.add(paidPrCodeStr);
*/				
				
				stmtn4 = conn.prepareStatement(sqlDelempotime_det);
/*				stmtn4.setTimestamp(1,otStDate);
				stmtn4.setTimestamp(2,otEdDate);ALKA*/
				stmtn4.setTimestamp(1,fromDate);
				stmtn4.setTimestamp(2,toDate);

				int  empotime_det = stmtn4.executeUpdate();
				System.out.println("No of records deleated from  empotime_det "+empotime_det); 
				stmtn4.close();  
				stmtn4=null;
//			}
/*			rsn4.close();
			rsn4=null;
			crstmtn4.close();
			crstmtn4=null;*/
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n4 Closed",true);

			//paidPrCode=Integer.parseInt(paidPrCodeStr.trim());

			/*if(prdCode.trim().equalsIgnoreCase(paidPrCodeStr.trim())){
				stmt = conn.prepareStatement(sqlDelempotime_det);
				stmt.setTimestamp(1,otStDate);
				stmt.setTimestamp(2,otEdDate);
				int  empotime_det = stmt.executeUpdate();
				System.out.println("No of records deleated from  empotime_det "+empotime_det); 
				stmt.close();  
			}*/

			/*stTimeImMilsec=fromDate.getTime();
			edTimeImMilsec=toDate.getTime();
			dayTminMilsec=24*60*60*1000;
			noOfDays =(edTimeImMilsec - stTimeImMilsec)/dayTminMilsec;*/

			System.out.println("toDate :"+toDate+": otEdDate :"+otEdDate);
			System.out.println("fromDate :"+fromDate+": otStDate :"+otStDate);

			System.out.println(">>>>>>>>>.  workSite : "+workSite);
			System.out.println(">>>>>>>>>.  cadre : "+cadre);
			System.out.println(">>>>>>>>>.  grade : "+grade);
			
			single = admCommon.getAdmEnv(workSite, cadre, grade, "SINGLE_PUNCH", fromDate, conn);
			woffPayable	= admCommon.getAdmEnv(workSite, cadre, grade, "WOFFPAYABLE", fromDate, conn);
			System.out.println(">>>>>>>>>.  woffPayable : "+woffPayable);
			if(woffPayable.equalsIgnoreCase("NULLFOUND") || !woffPayable.equalsIgnoreCase("N")) 
			{
				woffPayable = "Y";
			}
			else
			{
				holNonPayable = holNonPayable + "$W$";  
			}
			holPayDouble = admCommon.getAdmEnv(workSite, cadre, grade, "HOLIDAYPAYDOUBLE", fromDate, conn);
			if(holPayDouble.equalsIgnoreCase("NULLFOUND") || !holPayDouble.equalsIgnoreCase("Y"))
			{
				holPayDouble = "N";
			}
			woffPayDouble = admCommon.getAdmEnv(workSite, cadre, grade, "WOFFPAYDOUBLE", fromDate, conn);                                   
			if(woffPayDouble.equalsIgnoreCase("NULLFOUND") || !woffPayDouble.equalsIgnoreCase("Y"))
			{
				woffPayDouble = "N";
			}


			System.out.println("No of Records Deleted in ATTD_REG : " + delAttdReg);
			sqlTimeIn="SELECT PUNCH_STR,CHG_DATE,CHG_USER,IN_TIME,OUT_TIME,SHIFT,LUNCH_TIME FROM ATTENDANCE_DAY WHERE EMP_CODE = ?  AND ATTD_DATE = ?";
			System.out.println("sqlTimeIn:::"+sqlTimeIn); 
			while (procDate.before(getAddDateInTimestamp(toDate, 1)))
			{
				isHolidayPaid=false;
				if (otFrom==null)
				{
					otFrom=procDate;
				}
				if(otFrom !=null)
				isOtSpanExist=true;
				otTo=procDate;
				Calendar  cal = Calendar.getInstance();
				cal.setTime(procDate);
				int month=cal.get(Calendar.MONTH );
				System.out.println("@@@@@@@@@@@@@@@@22   month "+month);
				if(chkMonth == -1)
				chkMonth=month;
				totDednTimeInMin=0;
				worTimeInMin=0;
				fullDayHr=0;
				halfDayHr=0;
				dayOfWeek=0;
				paidHoliDay=0;
				paidWoff=0;
				paidWoff=0;
				noDay=0;
				tourDay=0;
				iTime="0";
				oTime="0";
				workDay=0;
				paidDay=0;
				holWoffDay=0;
				leaveDay=0;
				formatOtTimeInHrs = ""; //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY 
				lveDateTo=null;
				lveDateFrom=null;
				holTblNoFr= holTblNo;
				eligibleOt=emp_EligibleOt;
				tourStarts=null;
				tourEnds=null;
				punchStr=null;
				holType=null;
			//	totDednTimeInMin=0;
				status = "A";
				stmtn5 = conn.prepareStatement(sqlTimeIn);
				stmtn5.setString(1,empCode);
				stmtn5.setTimestamp(2,procDate);

				rsn5 = stmtn5.executeQuery();	
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n5 Opened",true);
				if (rsn5.next())
				{
					punchStr=rsn5.getString("punch_str");
					chgDate=rsn5.getTimestamp("CHG_DATE");
					chgUsr=rsn5.getString("CHG_USER");
					iTime=rsn5.getString("IN_TIME");
					oTime=rsn5.getString("OUT_TIME");
					shift=rsn5.getString("SHIFT");
					lunchTimeInMin=rsn5.getLong("LUNCH_TIME");
					System.out.println(" punchStr  : "+punchStr+"  shift :"+shift+" lunchTimeInMin :"+lunchTimeInMin );
					if(punchStr != null)
					{
						status = "P";
						workDay=1;
						worTimeInMin=getWorkTime(punchStr);     // return time spend by employee in company ( depend on punch string)
						System.out.println(" procDate  : "+procDate+"  worTimeInMin :"+worTimeInMin);
						if(worTimeInMin == 0)//Added at Sun 09/02/07
						{
							status = "A";
							workDay=0;
						}
					}
				}
				stmtn5.close();
				stmtn5=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n5 Closed",true);
				rsn5.close();
				rsn5=null;
				sqlDednIn="SELECT DEDN_TIME FROM ATTD_DEDN  WHERE EMP_CODE = ?  AND DEDN_DATE = ?";
					System.out.println("sqlDednIn:::"+sqlDednIn); 
				if(worTimeInMin!=0)
				{									// this block find out the time to deduct from time spend by employee in company
					stmtn6 = conn.prepareStatement(sqlDednIn);
					stmtn6.setString(1,empCode);
					stmtn6.setTimestamp(2,procDate);
					rsn6 = stmtn6.executeQuery();
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n6 Opened",true);
					while(rsn6.next())
					{
						dednTimeInMin =rsn6.getInt("dedn_time");
						totDednTimeInMin=totDednTimeInMin+dednTimeInMin;
						System.out.println(" procDate  : "+procDate+"  dednTimeInMin : "+dednTimeInMin);  
					}
					stmtn6.close();
					stmtn6=null;
					rsn6.close();
					rsn6=null;
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n6 Closed",true);
				}
				System.out.println(">>>>>.  lunchTimeInMin "+lunchTimeInMin);
				String availLaunchTime = "";
				availLaunchTime = admCommon.getAdmEnv(workSite,cadre,grade,"AVAIL_LUNCH_TIME",procDate,conn);

				if(availLaunchTime.equalsIgnoreCase("N") && punchStr != null)////if lunch time is not applicable then deduct lunch time	
					actWorkTime=worTimeInMin-totDednTimeInMin - lunchTimeInMin;//Long.parseLong(lunchTimeInMin); 
				else
					actWorkTime=worTimeInMin-totDednTimeInMin;

				System.out.println(">>>>>.  actWorkTime "+actWorkTime);

				totactWorkTimeMin=totactWorkTimeMin + actWorkTime;  // totactWorkTimeMin  is used to make  entry in attendance_mon

				procDateStr=procDate.toString();
				dayOfWeek=getDayOfWeek(procDateStr);
				String shft="";
				work_Shiftsql="SELECT SHIFT FROM WORK_SHIFT WHERE EMP_CODE = ? and ? BETWEEN FROM_DT AND TO_DT";
				System.out.println("work_Shiftsql:::"+work_Shiftsql); 

				stmt1 = conn.prepareStatement(work_Shiftsql);
				stmt1.setString(1,empCode);
				stmt1.setTimestamp(2,procDate);
				rsn7 = stmt1.executeQuery();
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n7 Opened",true);
				if(rsn7.next())
				{
					 shft = rsn7.getString(1);  // shft specifies employee belong to which shift
				}
				stmt1.close();
				stmt1=null;
				rsn7.close();
				rsn7=null;

				//writeLog(filePtr,"[AddProcessEJB]ResultSet n7 Closed",true);

				if(shft == null || "".equalsIgnoreCase(shft))
				{
					work_Shiftsql="SELECT WORK_SHIFT FROM EMPLOYEE WHERE EMP_CODE = ?";
						System.out.println("work_Shiftsql:::"+work_Shiftsql); 
					stmt1 = conn.prepareStatement(work_Shiftsql);
					stmt1.setString(1,empCode);
					rsn8 = stmt1.executeQuery();
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n8 Opened",true);
					if(rsn8.next())
					{
						 shft = rsn8.getString(1);
					}
					stmt1.close();
					stmt1=null;
					rsn8.close();
					rsn8=null;
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n8 Closed",true);
		
					if(shft == null){
						errString = itmDBAccessEJB.getErrorString("","VTSHFTNUL",userId);
						return errString;
					}
//					COMMENTED BY ALKA ON 07/09/07 AS ATTENDENCE PROCESS TO BE DONE EVEN IF THE SHIFT IS FIXED
					/*String shiftType = "";
					sql = "SELECT WORK_TYPE FROM WORKSHFT WHERE SHIFT = '"+shft+"'";
					System.out.println("sql:::"+sql); 
					stmt9 = conn.createStatement();
					rsn9 = stmt9.executeQuery(sql);
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n9 Opened",true);
					if(rsn9.next()){
						shiftType = rsn9.getString("WORK_TYPE");
						if(shiftType != null && shiftType.trim().equalsIgnoreCase("X")){  
							errString = itmDBAccessEJB.getErrorString("","VTSHFTFX",userId);
							return errString;
						}
					}
					rsn9.close();
					rsn9=null;
					stmt9.close();
					stmt9=null;*/
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n9 Closed",true);
				}
				
				System.out.println(" dayOfWeek : :"+dayOfWeek); 
				System.out.println("shft : :"+shft); 
				//wShftsql="select fd_hrs,hd_hrs from workshft where day_no= ? and shift=?";
				wShftsql="SELECT FD_HRS,HD_HRS FROM WORKSHFT WHERE DAY_NO = "+dayOfWeek+" AND SHIFT = '"+shft+"'";
				
				System.out.println("wShftsql : :"+wShftsql); 
				stmt10 = conn.createStatement();
				rsn10 = stmt10.executeQuery(wShftsql);

				//writeLog(filePtr,"[AddProcessEJB]ResultSet n10 Opened",true);
				while(rsn10.next())
				{
					 fullDayHr = rsn10.getInt("fd_hrs");      // fullDayHr is time, the employee has to work  if he work full day 
					 halfDayHr = rsn10.getInt("hd_hrs");      // halfDayHr is time, the employee has to work  if he work half day 
					 System.out.println("fullDayHr : :"+fullDayHr);
					 System.out.println(" halfDayHr : :"+halfDayHr);

				}
				if("W".equalsIgnoreCase(shft.trim())){
					status = "W";
				}//end of while
				stmt10.close();
				stmt10=null;
				rsn10.close();
				rsn10=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n10 Closed",true);

				paidLeave=0;
				sqlLeave = "SELECT CASE WHEN A.NO_DAYS IS NULL THEN 0 ELSE A.NO_DAYS END ,"
					+ "CASE WHEN B.PAYABLE IS NULL THEN 'N' ELSE B.PAYABLE END , "
					+ "A.LVE_DATE_FR , A.LVE_DATE_TO , "
					+ "CASE WHEN A.LEAVE_STARTS IS NULL THEN 'B' ELSE A.LEAVE_STARTS END,"
					+ "CASE WHEN A.LEAVE_ENDS IS NULL THEN 'E' ELSE A.LEAVE_ENDS END "
					+ "FROM  EMPLEAVE A , LEAVES B "
					+ "WHERE A.EMP_CODE = '" + empCode + "' "
					+ "AND 	A.LVE_CODE = B.LVE_CODE "
					+ "AND 	? BETWEEN A.LVE_DATE_FR AND A.LVE_DATE_TO "
					+ "AND 	A.USE_FLAG = 'C' "  
					+ "AND	A.STATUS = 'A' ";    
					System.out.println("sqlLeave:::"+sqlLeave); 
				stmtn11 = conn.prepareStatement(sqlLeave);
				stmtn11.setTimestamp(1,procDate);
				rsn11 = stmtn11.executeQuery();
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n11 Opened",true);
				while(rsn11.next())      // this block find out leave
				{
					int noDays = rsn11.getInt(1);
					String payable = rsn11.getString(2);
					lveDateFrom = rsn11.getTimestamp(3);
					lveDateTo = rsn11.getTimestamp(4);
					String startStatus = rsn11.getString(5);
					String endStatus = rsn11.getString(6);
					System.out.println("noDays :"+noDays+" payable :"+payable+"	lveDateFrom :"+lveDateFrom+"  lveDateTo : "+lveDateTo+" startStatus  :"+startStatus+"  endStatus : "+endStatus);
					if(payable == null || !payable.trim().equalsIgnoreCase("Y"))
					{
						payable = "N";
					}
					if(noDays < 0)
					{
						noDays = 0;
					}
					if(noDays > 0)
					{
						System.out.println("Payable : " + payable);
						switch(payable.charAt(0))
						{
							case 'Y' :
								if(status == "A")
									{
										status = "L";
										if((startStatus.trim().equalsIgnoreCase("M") && lveDateFrom.equals(procDate)) || (endStatus.trim().equalsIgnoreCase("M") && lveDateTo.equals(procDate)))  
										{
											leaveDay=0.5;
											paidLeave = halfDayHr*60;  
											totPaidLeaveInDay=totPaidLeaveInDay+0.5;
										}
										else
										{
											leaveDay=1;
											paidLeave =fullDayHr*60;   
											totPaidLeaveInDay=totPaidLeaveInDay+1;
										}	
										break;
									}
						}
					}
					noDays = 0;    
				} // while(rsLeave.next())
				stmtn11.close();
				stmtn11=null;
				rsn11.close();
				rsn11=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n11 Closed",true);
				 
				sql = "SELECT HOL_TBLNO__FR "
				    + "FROM EMP_EMPLOY_EVENTS "
				    + "WHERE EMP_CODE= '" + empCode + "' "
				    + "AND EFF_DATE > ? "
				    + "AND 	EFF_DATE  = (SELECT MIN(EFF_DATE) FROM  EMP_EMPLOY_EVENTS  "
				    + "WHERE EMP_CODE = '" + empCode + "'  AND TRANS_TYPE = 'H' "
				    + "AND 	CONFIRMED = 'Y' "
				    + "AND	EFF_DATE > ?) "
				    + "AND	CONFIRMED = 'Y' ";

				sql=sql+" AND 	TRANS_TYPE = 'H' ";
				System.out.println("sql:::"+sql); 
				stmtn12 = conn.prepareStatement(sql);
				stmtn12.setTimestamp(1,procDate);
				stmtn12.setTimestamp(2,procDate);
				rsn12 = stmtn12.executeQuery();
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n12 Opened",true);
				if(rsn12.next())
				{
					holTblNoFr = rsn12.getString(1);   
				}
				stmtn12.close();
				stmtn12=null;
				rsn12.close();
				rsn12=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n12 Closed",true);
				System.out.println("  holTblNoFr : : "+holTblNoFr);
				System.out.println("procDate  : :"+procDate);
				sql = "SELECT CASE WHEN HOL_TYPE IS NULL THEN 'H' ELSE HOL_TYPE END "
					+ "FROM  HOLIDAY "
					+ "WHERE HOL_TBLNO = '" + holTblNoFr + "' "
					+ "AND 	HOL_DATE  = ? ";
					System.out.println("sql:::"+sql); 
				stmtn13 = conn.prepareStatement(sql);
				stmtn13.setTimestamp(1,procDate);
				rsn13=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n13 Opened & Before rsn13="+rsn13,true);
				rsn13 = stmtn13.executeQuery();
				boolean isFound=false;
				if(rsn13.next())
				{
					isFound=true;
					holType = rsn13.getString(1);
				}
				stmtn13.close();
				stmtn13=null;
				rsn13.close();
				rsn13=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n13 Opened & isFound=>"+isFound+" & rsn13="+rsn13,true);
				if(isFound)
				{
					System.out.println("<<<<<<<<<<status : : "+status);
					//	holType = rsn13.getString(1);
			
					if(holType.equalsIgnoreCase("H") && status=="P")//Added by Nisar 08/02/07
					{
						paidHoliDay = fullDayHr*60; 					
						status = "H";
						isHolidayPaid=true;//Check for holiday paid
					}//end by Nisar 08/02/07
					System.out.println("holType : : "+holType);
					System.out.println("<<<<<<<<<status : : "+status);
					System.out.println("<<<<<<<<<paidHoliDay : : "+paidHoliDay);
					/*if(holType.equalsIgnoreCase("W"))//Commented for week off type as it is to be taken from work_shift
					{
						status = "W";											
					}*/
					//commented by tarani on 21062007 as holy day goes to the attd month in weakly off day
					if(holType.equalsIgnoreCase("W")  && "Y".equalsIgnoreCase(woffPayable))
					{
						paidWoff = fullDayHr*60;
						holWoffDay=1;
						totWoffinDay= totWoffinDay+1;  
						status = "W";
					}
					/*else*/
					System.out.println("holType::["+holType+"]");
					System.out.println("status::["+status+"]");
					
					if(holType.equalsIgnoreCase("H") && status.equalsIgnoreCase("A" ))
					{
						paidHoliDay = fullDayHr*60;  
						status = "H";
						holWoffDay=1;
						totWoffinDay= totWoffinDay+1;
					}
				}
				else
				{
					sql = "SELECT HOL_TYPE "
						+ "FROM 	CHANGE_HOLIDAY "
						+ "WHERE EMP_CODE =  '" + holTblNoFr + "' "
						+ "AND 	HOL_DATE_FOR = ? " 
						+ "AND 	CONFIRMED = 'Y' ";  
						System.out.println("sql:::"+sql); 
					stmtn14=null;
					rsn14=null;
					stmtn14 = conn.prepareStatement(sql);
					stmtn14.setTimestamp(1,procDate);
					rsn14 = stmtn14.executeQuery();
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n14 Opened",true);
					if(rsn14.next())
					{
						holType = rsn14.getString(1);
						/*if(holType.equalsIgnoreCase("W"))//Commented by Jiten as week off is to be checked from work_shift
						{
							status = "W";											
						}*/
						//uncomment by tarani
						if(holType.equalsIgnoreCase("W")  && "Y".equalsIgnoreCase(woffPayable) )
						{
							paidWoff = fullDayHr*60;   
							holWoffDay=1;
							totWoffinDay= totWoffinDay+1;
							status = "W";
						}
						/*else*/
						System.out.println("holType::["+holType+"]");
						System.out.println("status::["+status+"]");
						if(holType.equalsIgnoreCase("H") && status.equalsIgnoreCase("A") )
						{
							paidHoliDay = fullDayHr*60; 
							holWoffDay=1;
						    status = "H";
							totWoffinDay= totWoffinDay+1;
						}
					}
					rsn14.close();
					rsn14=null;
					stmtn14.close();
					stmtn14=null;
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n14 Closed",true);
					
				}
				System.out.println("woffPayable::["+woffPayable+"]");
				System.out.println("status::["+status+"]");
				//commented by tarani because it added weakly off 2 time in if and hear
			/*	if(status.equalsIgnoreCase("W") && woffPayable.equalsIgnoreCase("Y")){//Jiten as week off is to be taken from shift 
					paidWoff = fullDayHr*60;   
					holWoffDay=1;
					totWoffinDay= totWoffinDay+1;
				}*/			
				if(rsn13!=null)
				{
					rsn13.close();
					rsn13=null;
				}
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n13 Closed &rsn13="+rsn13,true);

				sql = " SELECT CASE WHEN NO_DAYS IS NULL THEN 0 ELSE NO_DAYS END , "
					+ "CASE WHEN TOUR_STARTS IS NULL THEN 'S' ELSE TOUR_STARTS END , "
					+ "CASE WHEN TOUR_ENDS IS NULL THEN 'E' ELSE TOUR_ENDS END "
					+" , START_TIME, END_TIME, CASE WHEN DATE_FROM = DATE_TO THEN 'Y' ELSE 'N' END AS ISTOUR_FOR_SAMEDAY " //start_time and end_time added by jaimin on 13/06/2008 (AD89SUN013)
					+ "FROM  TOUR "
				  	+ "WHERE EMP_CODE = '" + empCode + "' "
				    + "AND 	? BETWEEN DATE_FROM AND DATE_TO "     
					+ "AND	STATUS = 'A' ";
					System.out.println("sql:::"+sql); 
				stmt15 = conn.prepareStatement(sql);
				stmt15.setTimestamp(1,procDate);
				rsn15 = stmt15.executeQuery();
				String isTourForSameDay = "N";
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n15 Opened",true);
				if(rsn15.next())
				{
					noDay = rsn15.getInt(1);
					tourStarts = rsn15.getString(2);
					tourEnds = rsn15.getString(3);
					tourStartDate = rsn15.getDate(4);//Added by jaimin on 13/06/2008 (AD89SUN013)
					tourEndDate = rsn15.getDate(5);//Added by jaimin on 13/06/2008 (AD89SUN013)
					isTourForSameDay = rsn15.getString(6);//Added by jaimin on 13/06/2008 (AD89SUN013)
				}
				stmt15.close();
				stmt15=null;
				rsn15.close();
				rsn15=null;
				//writeLog(filePtr,"[AddProcessEJB]ResultSet n15 Closed",true);
			
				if(noDay > 0  && status == "A" )   
				{
					//Start - added by jaimin on 13/06/2008 (AD89SUN013) - To ignore tour if tour is for 1 or less then 1 day and tour start time and end time is between attendance in time & out time
					String tourStTime = "00:00";
					String tourEndTime = "99:99";
					if (tourStartDate != null && tourEndDate != null)
					{
						tourStTime = sdf.format(tourStartDate);
						tourEndTime = sdf.format(tourEndDate);
					}
					if (isTourForSameDay.equals("Y") && compareTime(iTime,tourStTime) <= 0 && compareTime(tourEndTime,oTime) <= 0)
					{
						System.out.println("intime/outtime of tour b/w intime/outtime of attendance ");
						tourDay = 0;
					}
					//End - added by jaimin on 13/06/2008 (AD89SUN013)
					else
					{
						tourDay =fullDayHr*60;
						status = "T";
					}
				}

				//Commented by Jiten 25/09/06 		
				//paidTimeInMin=actWorkTime+paidLeave+paidHoliDay+tourDay+paidWoff;  // for adjusting paid leaves
				System.out.println("[AttdProcess]nnnnnnnnn=>"+paidLeave+"@"+paidHoliDay+"@"+tourDay+"@"+paidWoff);
				if(actWorkTime > 0)//Added by Jiten 25/09/06
				{
					paidTimeInMin=fullDayHr*60+paidLeave+paidHoliDay+tourDay+paidWoff;
					if(status=="W")
					{
						paidTimeInMin=paidWoff;
					}
					if(status=="H")
					{
						paidTimeInMin=paidHoliDay;
					}
					if(status=="T")
					{
						paidTimeInMin=tourDay;
					}
					if(status=="A")
					{
						paidTimeInMin=paidLeave;
					}
					System.out.println("paidTimeInMin :: "+paidTimeInMin);
				}
				else if(actWorkTime == 0)
				{
					paidTimeInMin=paidLeave+paidHoliDay+tourDay+paidWoff;
					System.out.println("paidTimeInMin :::"+paidTimeInMin);
				}
				System.out.println("paidTimeInMin :"+paidTimeInMin);
				if(status == "T")
					actWorkTime=tourDay;
				if(actWorkTime > 0)//Added by jiten 25/09/06
				{
					otTimeMin = actWorkTime - paidTimeInMin;
				}
				if(status=="W" || status=="H")//Added by Nisar 07/02/07
				{
					workDay=0;
				}//end of block Nisar 07/02/07
				System.out.println("[AttdProcessEJB]workDay=>"+workDay);
				
				System.out.println("paidTimeInMin :"+paidTimeInMin+"fullDayHr :"+fullDayHr+"otTimeMin :"+otTimeMin);//Jiten
				if(status == "P" &&  "Y".equalsIgnoreCase(eligibleOt))
				{
					othour=getTimeinHr(otTimeMin);
					formatOtTimeInHrs = getTimeInHrsFormat(otTimeMin);
				}
				else
				{
					othour="0";
					formatOtTimeInHrs = "0";
				}
				System.out.println(">>>>>>>>>  eligibleOt  "+eligibleOt);
				System.out.println(">>>>>>>>>  othour  "+othour);
				totOtHours=totOtHours+Double.parseDouble(othour);//Added by jiten 27/09/06
				System.out.println(">>>>>>>>>  eligibleOt  "+eligibleOt);
				System.out.println(">>>>>>>>>  othour  "+othour);
				System.out.println(">>>>>>>>>  totOtHours  "+totOtHours);
				actWorkTimeInHr=getTimeinHr(actWorkTime);
				System.out.println("actWorkTimeInHr : "+actWorkTimeInHr+" actWorkTime "+actWorkTime);	
				totWorkTimeForOt=totWorkTimeForOt+Double.parseDouble(actWorkTimeInHr);   // this variable is used to insert record in empotime
				noOfOtDays++;
 			   	System.out.println("totWorkTimeForOt : "+totWorkTimeForOt);
				paidDay=workDay + leaveDay + holWoffDay;
				
//				ADDED BY ALKA 11/08/07 FOR WEELY OFF - PAIDDAY & HOL-WOFFDAY TO BE UPDATED TO 1 IF 
//				1. HE COMES TO WORK I.E. OVERTIME
//				2. WOFFPAYABLE VARIABLE IN SITE_ENV IS 'Y'
				if ((status=="W" && Double.parseDouble(actWorkTimeInHr) > 0 ) || (status=="W"  &&  woffPayable.equalsIgnoreCase("Y")))
				{
					isHolidayPaid = true;
				}
//				ADDITION ENDED BY ALKA 11/08/07
				if(isHolidayPaid)//Added by Nisar 08/02/07
				{
					paidTimeInMin = fullDayHr*60;
					paidDay=1;
					holWoffDay=1;
				}//ended by Nisar 08/02/07
				System.out.println(">>>>isHolidayPaid>>>"+isHolidayPaid+"&=>"+paidDay);


				TotWorkDay=TotWorkDay+workDay;
				TotPaidDay=TotPaidDay+paidDay;

				chkMonth=month;
				actWorkTimeHr=getTimeinHr(actWorkTime);
				paidTimeInHr=getTimeinHr(paidTimeInMin);

				System.out.println(">>>>>>>>> fullDayHr "+fullDayHr); 
				System.out.println(">>>>>>>>> paidTimeInMin "+paidTimeInMin); 
				System.out.println(">>>>>>>>> actWorkTime "+actWorkTime); 
				System.out.println(">>>>>>>>> otTimeMin "+otTimeMin); 
				System.out.println(">>>>>>>>> actWorkTimeHr "+actWorkTimeHr); 
				System.out.println(">>>>>>>>> paidTimeInHr "+paidTimeInHr); 
				System.out.println(">>>>>>>>> othour "+othour); 
				System.out.println(">>>>>>>>> holWoffDay "+holWoffDay); 
				System.out.println(">>>>>>>>> leaveDay "+leaveDay); 
				System.out.println(">>>>>>>>> status "+status);
				totPaidTimeInMin=totPaidTimeInMin+paidTimeInMin;
				//Added by msalam on 25/06/07 as no need to insert those record which all ready exist
				
				//private boolean isArrdRegExistFor(String empCode, Timestamp attdDate, Connection conn)
				if(!isAttdRegExistFor(empCode, procDate, conn))
				{
//					insertRegSql = "INSERT INTO ATTD_REG (EMP_CODE, ATTD_DATE, STATUS,CHG_DATE,CHG_USER,CHG_TERM,WORK_HOUR,PAID_HOUR,IN_TIME,OUT_TIME,SHIFT,OT_HOUR,PUNCH_STR,WORK_DAYS,LEAVE_DAYS,HOL_WOFF_DAYS,PAID_DAYS,LOP_DAYS,LOP_HRS,EXTRA_DAYS,EXTRA_HRS) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ? ,? , ? ,? ,? ,? ,? , ? ,? , ? ,?, ?, ?, ?) ";
					insertRegSql = "INSERT INTO ATTD_REG (EMP_CODE, ATTD_DATE, STATUS,CHG_DATE,CHG_USER,CHG_TERM,WORK_HOUR,PAID_HOUR,IN_TIME,OUT_TIME,SHIFT,OT_HOUR,PUNCH_STR,WORK_DAYS,LEAVE_DAYS,HOL_WOFF_DAYS,PAID_DAYS,LOP_DAYS,LOP_HRS,EXTRA_DAYS,EXTRA_HRS,OT_HOUR_TIME) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ? ,? , ? ,? ,? ,? ,? , ? ,? , ? ,?, ?, ?, ?, ?) ";
					System.out.println("insertRegSql:::"+insertRegSql); 
					System.out.println(">>>>>>>>  procDate : "+procDate+"  paidTimeInMin : "+paidTimeInMin+" worTimeInMin : "+worTimeInMin);
					stmt = conn.prepareStatement(insertRegSql);
					stmt.setString(1,empCode);
					stmt.setTimestamp(2,procDate);
					stmt.setString(3,status);
					stmt.setTimestamp(4,today);
					stmt.setString(5,userId);
					stmt.setString(6,termId);
					if((status=="W" || status=="H")&& "Y".equalsIgnoreCase(eligibleOt)) //added by Nisar 07/02/07 & Jiten 09/02/07
					//Updated by nisar @ sun on 24/02/07
					{
						othour=actWorkTimeHr;
						formatOtTimeInHrs = getTimeInHrsFormat(actWorkTime);
						totactWorkTimeMin = totactWorkTimeMin - actWorkTime;
						actWorkTimeHr = "0";
					}//end of block added by nisar 07/02/07
					stmt.setString(7,actWorkTimeHr);
					stmt.setString(8,paidTimeInHr);
					stmt.setString(9,iTime);
					stmt.setString(10,oTime);
					stmt.setString(11,shft);				
					stmt.setString(12,othour);
					stmt.setString(13,punchStr);
					stmt.setDouble(14,workDay);
					stmt.setDouble(15,leaveDay);
					stmt.setInt(16,holWoffDay); 
					System.out.println("holWoffDay["+holWoffDay+"]");
					stmt.setDouble(17,paidDay);
					stmt.setInt(18,(status.equals("A")) ? 1:0);
					stmt.setInt(19,(status.equals("A")) ? fullDayHr:0);
					stmt.setInt(20,0);
					stmt.setInt(21,0);
					stmt.setString(22,formatOtTimeInHrs);
					int tmp = stmt.executeUpdate();
					if(tmp > 0)
					{
						errCode = "VTPROSUC";
					}
					stmt.close();
					stmt=null;
					System.out.println("Record Inserted in ATTD_REG");
					//End by ms alam on 25/06/07
				}//End of if(!isAttdRegExistFor)
				/////////Second Part of OT//////////////
				if(status == "A")
				{
					insertAttd_AbsSql="INSERT INTO ATTENDANCE_ABSENT (ATTD_DATE,EMP_CODE,SHIFT,CHG_DATE,CHG_USER,CHG_TERM)  VALUES (? ,? , ?, ?, ?, ? )"; 
					System.out.println("insertAttd_AbsSql:::"+insertAttd_AbsSql); 
					stmt = conn.prepareStatement(insertAttd_AbsSql);
					stmt.setTimestamp(1,procDate);
					stmt.setString(2,empCode);
					stmt.setString(3,shft);
					stmt.setTimestamp(4,today);
					stmt.setString(5,userId);
					stmt.setString(6,termId);
					empotimeUpdate=stmt.executeUpdate();
					if(empotimeUpdate > 0)
					{
						errCode = "VTPROSUC";
					}
					stmt.close();
					stmt=null;
				
				}
				procDate = getAddDateInTimestamp(procDate, 1);
				
			}   // ene while

			System.out.println(">>>>>>  tranId "+tranId);
			System.out.println(">>>>>>  empCode "+empCode);
			System.out.println(">>>>>>  prdCode "+prdCode);
			System.out.println(">>>>>>  procDate "+procDate);
			System.out.println(">>>>>>  otTimeFr "+otTimeFr);
			System.out.println(">>>>>>  totOtHours "+totOtHours);
			System.out.println(">>>>>>  today "+today);
			System.out.println(">>>>>>  userId "+userId);
			System.out.println(">>>>>>  termId "+termId);


			otTimeTo=getAddDateInTimestamp(procDate,-1);
			//////////Third part of OT//////////////////
			selectFrmMon="SELECT COUNT(1) from ATTENDANCE_MON WHERE EMP_CODE =? AND PRD_CODE =?";
			System.out.println("selectFrmMon:::"+selectFrmMon); 
			stmtn16 = conn.prepareStatement(selectFrmMon);
			stmtn16.setString(1,empCode);
			stmtn16.setString(2,prdCode);
			rsn16 = stmtn16.executeQuery();
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n16 Opened",true);
			if (rsn16.next())
			{
				count = rsn16.getInt(1);
			}
			stmtn16.close();
			stmtn16=null;
			rsn16.close();
			rsn16=null;
			//writeLog(filePtr,"[AddProcessEJB]ResultSet n16 Closed",true);
			if(count >0)
			{
				totPaidTimeInHr=getTimeinHr(totPaidTimeInMin);
				totactWorkTimeHr=getTimeinHr(totactWorkTimeMin);
				totWoffinHr=getTimeinHr(totWoffinMin);
				System.out.println(">>>>>>>>  totWoffinHr "+totWoffinHr);
				updateMon="UPDATE ATTENDANCE_MON SET LVES_TAKEN = ? ,WOFF_DAYS = ? ,PAID_HOUR = ? , WORK_HOUR = ? ,WORK_DAYS = ? ,PAID_DAYS = ?, ADDON_DAYS = ? ,PROC_WINDOW = ?,CHG_TERM = ?,CHG_USER = ?,CHG_DATE = ? WHERE EMP_CODE = ? AND PRD_CODE = ?";
				System.out.println("updateMon:::"+updateMon); 
				stmt = conn.prepareStatement(updateMon);
				stmt.setDouble(1,totPaidLeaveInDay);
				stmt.setLong(2,totWoffinDay);
				stmt.setString(3,totPaidTimeInHr);
				stmt.setString(4,totactWorkTimeHr);
				stmt.setDouble(5,TotWorkDay);  
			 	stmt.setDouble(6,TotPaidDay);
				stmt.setInt(7,0);
				stmt.setString(8,"H");
				stmt.setString(9, termId);
				stmt.setString(10, userId);
				stmt.setTimestamp(11, today);
				stmt.setString(12,empCode);
				stmt.setString(13,prdCode);
				int updatedAttdMon = stmt.executeUpdate();
				if(updatedAttdMon > 0)
				{
					errCode = "VTPROSUC";
				}
				stmt.close();
				stmt=null;
				System.out.println("Updated ATTENDANCE_MON : " + updatedAttdMon);
			}
			else
			{
				totPaidTimeInHr=getTimeinHr(totPaidTimeInMin);
				totactWorkTimeHr=getTimeinHr(totactWorkTimeMin);
				totWoffinHr=getTimeinHr(totWoffinMin);
				paidLeaveHr=getTimeinHr(totPaidLeaveInMin);
				insertMon = "INSERT INTO ATTENDANCE_MON (EMP_CODE,PRD_CODE, WORK_DAYS,WOFF_DAYS,LVES_TAKEN,PAID_DAYS,CHG_TERM,CHG_USER,CHG_DATE ,WORK_HOUR,PAID_HOUR,ADDON_DAYS,PROC_WINDOW)VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,?)";
				System.out.println("insertMon:::"+insertMon); 
				stmt = conn.prepareStatement(insertMon);

				stmt.setString(1, empCode);
				stmt.setString(2, prdCode);
				stmt.setDouble(3, TotWorkDay);  
				stmt.setLong(4, totWoffinDay);
				stmt.setDouble(5, totPaidLeaveInDay);
				stmt.setDouble(6, TotPaidDay);  
				stmt.setString(7, termId);
				stmt.setString(8, userId);
				stmt.setTimestamp(9, today);
				stmt.setString(10, totactWorkTimeHr);
				stmt.setString(11, totPaidTimeInHr);
				stmt.setInt(12, 0);//Added by Jiten - 25/09/06
				stmt.setString(13, "H");//Added by Jiten - 25/09/06
				int insertAttdAttdMon = stmt.executeUpdate();
				if(insertAttdAttdMon > 0)
				{
					errCode = "VTPROSUC";
				}
				stmt.close();
				stmt=null;
				System.out.println("Inseted ATTENDANCE_MON : " + insertAttdAttdMon);

			}
			System.out.println("paidPrCodeStr : "+paidPrCodeStr+" prdCode :"+prdCode+"eligibleOt : "+eligibleOt);
			System.out.println("otStartDateArr : "+otStartDateArr);
			System.out.println("otEndDateArr : "+otEndDateArr);
			System.out.println("paidPrdCodeArr : "+paidPrdCodeArr);
//			for(int i = 0;i < paidPrdCodeArr.size();i++){
//				errCode = generateOT(Timestamp.valueOf(otStartDateArr.get(i).toString()),Timestamp.valueOf(otEndDateArr.get(i).toString()),workCode,empCode, fromDate, toDate,conn);
				errCode = generateOT(fromDate,toDate,workCode,empCode,conn);
				if(errCode.equalsIgnoreCase("VTPROUNSUC")){
					errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
//					break;
				}				
//			}
			if(errCode.equalsIgnoreCase("VTPROSUC"))
				{
				errCode = "VTPROSUC";

				errString = itmDBAccessEJB.getErrorString("","VTPROSUC",userId);
			}
			if(otStartDateArr.size() > 0 ){
				otStartDateArr.clear();
				otStartDateArr = null;
			}
			if(otEndDateArr.size() > 0 ){
				otEndDateArr.clear();
				otEndDateArr = null;
			}
			if(paidPrdCodeArr.size() > 0 ){
				paidPrdCodeArr.clear();
				paidPrdCodeArr = null;
			}		
			sql="UPDATE  attendance_day SET status='U' where emp_code=? and attd_date between ? and ?";//To be moved to the if condn for successfuel - jiten // Added by Kamal
			System.out.println("sql:::"+sql); 
			updstmt=conn.prepareStatement(sql);
			updstmt.setString(1,empCode);
			updstmt.setTimestamp(2,fromDate);
			updstmt.setTimestamp(3,toDate);
			updstmt.executeUpdate();
			updstmt.clearParameters();
			updstmt.close();
			updstmt=null;								
		}
		catch (SQLException se)
		{
			System.out.println("SQLException :AttdProcessEJB :attdProcess()" + se);
			se.printStackTrace();
			errCode = "VTPROUNSUC";
			errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
			System.out.println("ErrString :"+errString);			
		}
		catch(Exception e)
		{
			System.out.println("Exception : "+e);
			e.printStackTrace();
			errCode = "VTPROUNSUC";
			errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
			System.out.println("ErrString :"+errString);			
		}
		finally
		{
			try
			{
				if(updstmt != null) updstmt.close();
				if(stmt != null) stmt.close();
				if(rsn21 != null) rsn21.close();	
				//writeLog(filePtr,"[AddProcessEJB]ResultSet rs closed",true);
			}
			catch (Exception e)
			{
				System.out.println("SQLException :AttdProcessEJB :attdProcess()" + e);
				e.printStackTrace();
				errCode = "VTPROUNSUC";
				errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC",userId);
				System.out.println("ErrString :"+errString);				
			}
		}
		System.out.println("ErrString :"+errString);

		return errString;
	}

	private String generateOT(Timestamp stDate,Timestamp edDate,String workCode,String empCode, Connection conn)
	{
		Statement stmt = null;
		PreparedStatement pstmt = null,pstmtUpdate = null,pstmtInsert = null;
		//ResultSet rs = null;
		String tranId = "",shift = "",stDateStr ="",wShftsql ="",prdCode ="",errCode ="VTPROSUC";
		//added by msalam on 27/06/07
		String tempTranId = "", tempEmpCode = "";
/*		Timestamp tFromDate = null;
		Timestamp tToDate = null;*/ //COMMENTED BY ALKA 17/08/07
		//added by msalam on 27/06/07
		int lineNo=1,dayOfWeek = 0;
		boolean isExist= false;
/***	double totOThr = 0,otHr = 0.0; Discarded by Jiten @ sun***/
		double totOThr = 0,otHr = 0, formatOtTimeInHrs = 0, totFormatOtTimeInHrs = 0;  //VARIABLE ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
		long fullDayHr = 0;
	/*** double totOThr1=0;//Added by Nisar on 10/02/07
		long hrInMin=0;//Added by Nisar on 10/02/07
		String hrToStr="";//Added by Nisar on 10/02/07  Commented by Jiten @ sun***/
		String hrToStr=""; //Added by Nisar on 26/02/07
		Timestamp otStDate = null;
		Timestamp fromDt = null, toDate = null;

		String sql = "",insertEmpotimeSql ="",updateEmpotimeSql= "",insertEmpotime_detSql = "";
		try{
			insertEmpotimeSql="INSERT INTO EMPOTIME (TRAN_ID,EMP_CODE,PRD_CODE,OT_DATE,OT_TIME_FR,OT_TIME_TO,OT_HOURS,CHG_DATE,CHG_USER,CHG_TERM,STATUS,STATUS_DATE,FLAG,CAL_OT_HOURS)  Values (? ,? , ?, ?, ?, ? , ?, ?, ?, ?, ?, ?, ?,?)";
			updateEmpotimeSql="UPDATE  EMPOTIME SET OT_DATE = ? ,OT_TIME_FR = ? ,OT_TIME_TO = ? ,OT_HOURS = ? ,CHG_DATE = ? ,CHG_USER = ? ,CHG_TERM = ? ,STATUS = ? ,STATUS_DATE = ? ,CAL_OT_HOURS = ? WHERE TRAN_ID = ? ";
			insertEmpotime_detSql="INSERT INTO EMPOTIME_DET (TRAN_ID,LINE_NO,EMP_CODE,OT_DATE,SHIFT,SHIFT_TIME,OT_TIME,DAY_NO,CAL_OT_TIME, APPROVED_FLAG)  VALUES (? ,? , ?, ?, ?, ? , ? ,?,?,'N')";
			
			insertEmpotimeSql="INSERT INTO EMPOTIME (TRAN_ID,EMP_CODE,PRD_CODE,OT_DATE,OT_TIME_FR,OT_TIME_TO,OT_HOURS,CHG_DATE,CHG_USER,CHG_TERM,STATUS,STATUS_DATE,FLAG,CAL_OT_HOURS, OT_HOURS_TIME, CAL_OT_HRS_TIME)  Values (? ,? , ?, ?, ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
			updateEmpotimeSql="UPDATE  EMPOTIME SET OT_DATE = ? ,OT_TIME_FR = ? ,OT_TIME_TO = ? ,OT_HOURS = ? ,CHG_DATE = ? ,CHG_USER = ? ,CHG_TERM = ? ,STATUS = ? ,STATUS_DATE = ? ,CAL_OT_HOURS = ?, OT_HOURS_TIME = ?, CAL_OT_HRS_TIME = ? WHERE TRAN_ID = ? ";
			insertEmpotime_detSql="INSERT INTO EMPOTIME_DET (TRAN_ID,LINE_NO,EMP_CODE,OT_DATE,SHIFT,SHIFT_TIME,OT_TIME,DAY_NO,CAL_OT_TIME, APPROVED_FLAG, OT_HOURS_TIME, CAL_OT_HRS_TIME)  VALUES (? ,? , ?, ?, ?, ? , ? ,?,?,'N', ?, ?)";
			fromDt = stDate;
			toDate = edDate;
			System.out.println("stDate : "+stDate);
			System.out.println("edDate : "+edDate);
						
			while(stDate.before(getAddDateInTimestamp(edDate,1)))
			{
				System.out.println("stDate  ["+stDate+"]");
				Timestamp endDate = stDate;
				Calendar cal1 =Calendar.getInstance();
				Calendar cal2 =Calendar.getInstance();
				cal1.setTime(stDate);
				cal2.setTime(endDate);
				
				cal2.set(Calendar.DATE,cal1.getActualMaximum(Calendar.DAY_OF_MONTH));
				java.util.Date d = cal2.getTime();
				endDate = new java.sql.Timestamp(d.getTime());
				if(endDate.after(edDate)){
					endDate = edDate;
				}
				///
				totOThr = 0;
				totFormatOtTimeInHrs = 0;
			/***totOThr1=0;  Commented by Jiten @ sun ***/
				lineNo = 1;
				System.out.println("OT Generation From Work Balance Period :: From Date :"+stDate+": End Date :"+endDate);
				otStDate = stDate;
				while(stDate.before(getAddDateInTimestamp(endDate,1)))
				{
					tranId = getExistTranId(empCode,stDate,conn); // gets Tran_id from empotime - Jiten
					System.out.println("tranId from getExistTranId :::: " + tranId);  //SOP BY ALKA 01/08/07
					if(tranId == null)
						// Modified by Piyush on 19/03/2015 [To pass required parameters to generate tran id as per transetup. Issues resolved during RCP migration]
						// tranId = getTranId(conn);
						tranId = getTranId(empCode,stDate,conn);
					else
						isExist = true;
					System.out.println("stDate : "+stDate);
					System.out.println("tranId : "+tranId);
					
					
//					sql = "SELECT OT_HOUR,SHIFT FROM ATTD_REG WHERE EMP_CODE = ? AND ATTD_DATE = ?";
					sql = "SELECT OT_HOUR,SHIFT,OT_HOUR_TIME FROM ATTD_REG WHERE EMP_CODE = ? AND ATTD_DATE = ?";
					System.out.println("SQL : "+sql);
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,empCode);
					pstmt.setTimestamp(2,stDate);
					rsn17 = pstmt.executeQuery();
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n17 Opened",true);
					if(rsn17.next()){
						otHr = rsn17.getDouble(1);
						shift = rsn17.getString(2);
						formatOtTimeInHrs = rsn17.getDouble(3);
						if(shift == null){
							shift = "";
						}							
					}
					pstmt.clearParameters();
					pstmt.close();
					pstmt=null;
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n17 Closed",true);
					rsn17.close();
					rsn17=null;
					
					stDateStr=stDate.toString();
					dayOfWeek=getDayOfWeek(stDateStr);
					
					wShftsql="SELECT FD_HRS,HD_HRS FROM WORKSHFT WHERE DAY_NO = "+dayOfWeek+" AND SHIFT = '"+shift+"'";
					System.out.println("wShftsql : :"+wShftsql); 
					stmt = conn.createStatement();
					rsn18 = stmt.executeQuery(wShftsql);
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n18 Opened",true);
					if(rsn18.next()){
						fullDayHr = rsn18.getLong(1); 
					}
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n18 Closed",true);
					if(rsn18 != null){
						rsn18.close();
						rsn18 = null;
						stmt.close();
						stmt = null;						
					}					
					
					sql = "SELECT CODE FROM PERIOD WHERE ? BETWEEN FR_DATE AND TO_DATE";
					pstmt = conn.prepareStatement(sql);
					pstmt.setTimestamp(1,stDate);
					rsn19 = pstmt.executeQuery();
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n19 Opened",true);
					if(rsn19.next()){
						prdCode = rsn19.getString(1);
					}
					//writeLog(filePtr,"[AddProcessEJB]ResultSet n19 Closed",true);
					rsn19.close();
					rsn19=null;
					pstmt.close();
					pstmt=null;
					//added by tarani on 130307
					
				//	System should not generate record for ot where cal_ot_time is 0
			
					if(otHr != 0)
					{ 
						totOThr = totOThr+otHr;
						totFormatOtTimeInHrs = totFormatOtTimeInHrs + formatOtTimeInHrs;
						totFormatOtTimeInHrs = Double.parseDouble(getTimeinHrsUpdated(totFormatOtTimeInHrs));
						hrToStr=getTimeinHrsUpdated(totOThr);
						totOThr=Double.parseDouble(hrToStr);
						System.out.println("isExist  ["+isExist+"]");
						

						if(isExist){
							//Added by msalam on 270607
							tempTranId = tranId;
							tempEmpCode = empCode;
							
/*							tFromDate = otStDate;
							tToDate = endDate; COMMENTED BY ALKA 17/08/07*/
							//end ny msalam on 270607
							System.out.println("updateEmpotimeSql : "+updateEmpotimeSql);
							pstmtUpdate = conn.prepareStatement(updateEmpotimeSql);
							//pstmtUpdate.setTimestamp(1,today);
							pstmtUpdate.setTimestamp(1,endDate);
							pstmtUpdate.setTimestamp(2,otStDate);
							pstmtUpdate.setTimestamp(3,endDate);
							pstmtUpdate.setDouble(4,totOThr);
							pstmtUpdate.setTimestamp(5,today);
							pstmtUpdate.setString(6,userId);
							pstmtUpdate.setString(7,termId);
							pstmtUpdate.setString(8," ");
							pstmtUpdate.setTimestamp(9,today);
							pstmtUpdate.setDouble(10,totOThr);//added by kamal
							pstmtUpdate.setDouble(11,totFormatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtUpdate.setDouble(12,totFormatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtUpdate.setString(13,tranId); //CHANGED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtUpdate.executeUpdate();
							pstmtUpdate.clearParameters();
							pstmtUpdate.close();
							pstmtUpdate = null;
						}
						else{
							System.out.println("insertEmpotimeSql : "+insertEmpotimeSql);
							pstmtInsert = conn.prepareStatement(insertEmpotimeSql);
							pstmtInsert.setString(1,tranId);
							pstmtInsert.setString(2,empCode);
							pstmtInsert.setString(3,prdCode);
							//pstmtInsert.setTimestamp(4,today);
							pstmtInsert.setTimestamp(4,endDate);
							pstmtInsert.setTimestamp(5,otStDate);
							pstmtInsert.setTimestamp(6,endDate);
							pstmtInsert.setDouble(7,totOThr);
							pstmtInsert.setTimestamp(8,today);
							pstmtInsert.setString(9,userId);
							pstmtInsert.setString(10,termId);
							pstmtInsert.setString(11," ");
							pstmtInsert.setTimestamp(12,today); 
							pstmtInsert.setString(13,"D"); 
							pstmtInsert.setDouble(14,totOThr); //added by kamal
							pstmtInsert.setDouble(15,totFormatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtInsert.setDouble(16,totFormatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtInsert.executeUpdate();
							pstmtInsert.clearParameters();
							pstmtInsert.close();
							pstmtInsert = null;
//							isExist = true;  //COMMENTED BY ALKA  16/08/07
						}					
	
						System.out.println("insertEmpotime_detSql : "+insertEmpotime_detSql);
						/*
						//previous code
							pstmtInsert = conn.prepareStatement(insertEmpotime_detSql);
							pstmtInsert.setString(1,tranId);
							pstmtInsert.setInt(2,lineNo);
							pstmtInsert.setString(3,empCode.trim());
							pstmtInsert.setTimestamp(4,stDate);
							pstmtInsert.setString(5,shift);
							pstmtInsert.setLong(6,fullDayHr);
							pstmtInsert.setDouble(7,otHr);
							pstmtInsert.setInt(8,dayOfWeek);
							pstmtInsert.setDouble(9,otHr);// new added by kamal
							pstmtInsert.executeUpdate();
						
						*/
						
						//if by ms alam on 25/06/07
						
//						ADDED BY ALKA 16/08/07
						if (isExist && lineNo == 1)
						{
							// Remarked and changed bellow by by Piyush to get proper line no - 11/12/2008 
							//sql = "SELECT COUNT(*) FROM EMPOTIME_DET WHERE Emp_Code = '" + empCode + "' AND OT_DATE >= ? AND OT_DATE <=?";
							sql = "SELECT MAX(LINE_NO) FROM EMPOTIME_DET WHERE Emp_Code = '" + empCode + "' AND OT_DATE >= ? AND OT_DATE <=?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setTimestamp(1, fromDt);
							pstmt.setTimestamp(2, toDate);
							rsn19 = pstmt.executeQuery();
							if (rsn19.next())
							{
								lineNo = rsn19.getInt(1) + 1;
							}
							rsn19.close(); rsn19 = null;
							pstmt.close(); pstmt = null;
						}
//						ADDITION ENDED BY ALKA 16/08/07
						
						//if empotime_det entry exist for the given tran_id, line no)
					    //boolean isEmpOTimeExistFor(String empCode, Timestamp otDate, Connection conn)
//						if(!isEmpOTimeExistFor(empCode.trim(), stDate, conn))
						if(!isEmpOTimeExistFor(empCode, stDate, conn))
						{ 
							pstmtInsert = conn.prepareStatement(insertEmpotime_detSql);
							pstmtInsert.setString(1,tranId);
							pstmtInsert.setInt(2,lineNo);
							pstmtInsert.setString(3,empCode.trim());
							pstmtInsert.setTimestamp(4,stDate);
							pstmtInsert.setString(5,shift);
							pstmtInsert.setLong(6,fullDayHr);
							pstmtInsert.setDouble(7,otHr);
							pstmtInsert.setInt(8,dayOfWeek);
							pstmtInsert.setDouble(9,otHr);// new added by kamal
							pstmtInsert.setDouble(10,formatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							pstmtInsert.setDouble(11,formatOtTimeInHrs); //ADDED BY ALKA 31/08/07 FOR FORMATTING IN HOURS FOR DISPLAY
							//pstmtInsert.setString(10,"N");//by ms alam on 27/06/07 for req-id :: ad7sun0016
							pstmtInsert.executeUpdate();
							pstmtInsert.clearParameters();
							pstmtInsert.close();
							pstmtInsert = null;
						}//end of if by ms alam
						lineNo++;
//						isExist = false;  //COMMENT REMOVED BY ALKA ON 01/08/07
					
					/*	totOThr = totOThr+otHr;
						hrToStr=getTimeinHrsUpdated(totOThr);
						totOThr=Double.parseDouble(hrToStr);*/
						
//						System.out.println("[AttdProcessEJB]=>totOThr=>"+totOThr+">>otHr=>"+otHr);
						System.out.println("[AttdProcessEJB]=>totOThr=>"+totOThr+">>otHr=>"+otHr + "=>totFormatOtTimeInHrs=>"+totFormatOtTimeInHrs+">>formatOtTimeInHrs=>"+formatOtTimeInHrs);
						
					}//end if 
					stDate = getAddDateInTimestamp(stDate,1);
					isExist = false;  //ADDED BY ALKA ON 01/08/07
				}
				
				
				//stDate = getAddDateInTimestamp(stDate,1);
			}//end of while loop
			
			//update empotime hdr ot_hours for all empotime_det ot_hours
			//added by ms alam on 27/06/07
//			updateEmpOtimeFor(tempTranId, tempEmpCode, tFromDate, tToDate, conn); //ALKA 17/08/07
			updateEmpOtimeFor(tempTranId, tempEmpCode, fromDt, toDate, conn);
			//end of ms alam on 27/06/07
			
		}catch(Exception e){
			errCode = "VTPROUNSUC";
			e.printStackTrace();
		return errCode;
		}
		finally{
			try{
				if(stmt != null)
					stmt = null;
				if(pstmt != null)
					pstmt = null;
				if(pstmtUpdate != null)
					pstmtUpdate = null;
				if(pstmtInsert != null)
					pstmtInsert = null;
			}catch(Exception e){				
				}
			
		}
		return errCode;
	
}
	private long getWorkTime(String punchStr) throws Exception
	{
		String timeStr=null;
		String time=null;
		ArrayList punchList = new ArrayList();
		ArrayList timeList = new ArrayList();
		long lowTimeMillSec = 0 ,highTimeMillSec = 0;
		long totalTime = 0;
		long totalInTime=0;
			
		punchList = genericUtility.getTokenList(punchStr,",");
		System.out.println("punchList :"+punchList);
		for(int i=0;i < punchList.size();i++)
			{
				System.out.println("punchList.get("+i+") :"+punchList.get(i));
				if((punchList.get(i).toString()).indexOf("*") != -1){
				    timeList.add((punchList.get(i).toString().trim()).substring(2));  //trim added at Sun - jiten 09/02/07
				}else{
				    timeList.add((punchList.get(i).toString().trim()).substring(1));  //trim added at Sun - jiten 09/02/07
				}
		    	
			}
		lowTimeMillSec = getTimeInMinit(timeList.get(0).toString());
		highTimeMillSec = lowTimeMillSec;
		for(int i=0;i < timeList.size();i++)
			{
				totalTime = getTimeInMinit(timeList.get(i).toString());
				if(totalTime < lowTimeMillSec)
					{
						lowTimeMillSec = totalTime;
					}
				if(totalTime > highTimeMillSec)
					{
						highTimeMillSec = totalTime;
					}
			}		
		totalInTime = highTimeMillSec - lowTimeMillSec;
		
		punchList.clear();
		timeList.clear();
		punchList = null;
		timeList = null;
		
		return totalInTime;
	}//end of getWorkTime
	private long getTimeInMinit(String timeStr) throws Exception
	{
	     long timinMin = 0;
	     try{
				System.out.println(">>>>>>>>>>>..  timeStr "+timeStr);
				String hr=timeStr.substring(0,timeStr.indexOf(':'));
				String min=timeStr.substring(timeStr.indexOf(':')+1);
				System.out.println("hr : "+hr+" min : "+min);		
				timinMin = Long.parseLong((NumberFormat.getInstance().parse(hr)).toString())*60;
				System.out.println("timinMin :: "+timinMin);
				timinMin = timinMin + Long.parseLong((NumberFormat.getInstance().parse(min)).toString());
				System.out.println("timinMin :: "+timinMin);
		   }catch(Exception e){System.out.println("Exception : "+e);throw e;}
		   return timinMin;
	}

	private Timestamp getAddDateInTimestamp(Timestamp date, int days)
	{
		java.sql.Timestamp retTimestamp = null;
		try
		{
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDispDateFormat());
			Calendar  cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.DATE,days);
			java.util.Date date1 = cal.getTime();
			long time = date1.getTime();
			retTimestamp= new java.sql.Timestamp(time);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		return retTimestamp;
	}//end of getAddDateInTimestamp

	private  String getTimeinHr(long min)
	{
		boolean isNeg=false;
		String retStr="";
		String str_min="";
		long convTime = 0;
        if(min < 0 )
		{
			min=-(min);
			isNeg=true;
		}
		long hr=min/60;
/*		long minute=min%60;
		str_min=Long.toString(minute);//Added by Nisar 08/02/07
*/		
		//ALKA
		double minute=min%60;
		System.out.println("minute:::: [" + minute + "]");
		NumberFormat nf = new DecimalFormat("##############0.000");
		nf.setMaximumFractionDigits(0);
		str_min=nf.format(minute/60*100);
		//ALKA
		if(str_min.length()<=1)//Added by Nisar 08/02/07
		{
			str_min="0"+str_min;
		}//Ended by Nisar 08/02/07
		if(isNeg == true)
		retStr= "-";
		retStr=retStr+hr+"."+str_min;
		System.out.println("retStr:::: [" + retStr + "]"); //ALKA
		return retStr;
	}//end of getTimeinHr .

	private String getTimeinHrsUpdated(double d)//Added by Nisar on 10/02/07
	{
		String hr=null;
		String mm=null;
		boolean isNeg=false;
		String minutes=null;
		
		NumberFormat f=NumberFormat.getInstance();
		f.setMinimumFractionDigits(2);
		String otHrToStr = f.format(d);
		if(otHrToStr.startsWith("-"))
		{
			hr=otHrToStr.substring(1,otHrToStr.indexOf("."));
			isNeg=true;
		}
		else
		{
			hr=otHrToStr.substring(0,otHrToStr.indexOf("."));
		}
		mm=otHrToStr.substring(otHrToStr.indexOf(".")+1,otHrToStr.length());
		
		int min=Integer.parseInt(mm);
		int hrs=Integer.parseInt(hr);
		if(min>59)
		{
		 hrs=hrs+1;
		 min=min-60;
		}
		hr=new Integer(hrs).toString();
		mm=new Integer(min).toString();
		if(mm.length()<=1)
		{
		 mm="0"+mm;
		}		
		if(isNeg)
			hrs=hrs*(-1);
		return hrs+"."+mm;
	}	//ended by Nisar on 10/02/07  Commented by Jiten @ sun ,uncommented by nisar on 26/02/07



private static int getDayOfWeek(String str)
	// this method take date string as input & return dayof week sunday is 1 day
{
	if(str.indexOf(' ')!= -1)
	{
		str=str.substring(0,str.indexOf(' '));
	}
	System.out.println(">>>>>>>>> year "+str.substring(0,str.indexOf('-'))); 
	System.out.println(">>>>>>>>> month "+str.substring(str.indexOf('-')+1,str.lastIndexOf('-'))); 
	System.out.println(">>>>>>>>> date "+str.substring(str.lastIndexOf('-')+1)); 
	int year=Integer.parseInt(str.substring(0,str.indexOf('-')));
	int month=Integer.parseInt(str.substring(str.indexOf('-')+1,str.lastIndexOf('-')));
	int date=Integer.parseInt(str.substring(str.lastIndexOf('-')+1));
 	Calendar cal= Calendar.getInstance();
	cal.set(year,month-1,date);
	int dno=cal.get(Calendar.DAY_OF_WEEK);
	return  dno;
}//end of getDayOfWeek .


// Modified by Piyush on 19/03/2015 [To generated tran id as per transetup].Start
private String getTranId(String empCode , Timestamp otDate , Connection conn )
{
	String tranSer = "";
	String keyString = "";
	String keyCol = "";
	String keyStringQuery = "";
	String xmlValues="";
	Statement crstmt = null;
	String tranId="";
	String workSite="";
	String empSite="";
	String paySite="";
	
	try
	{ 

		SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
		String otDateStr = sdf1.format(otDate);
		System.out.println("getTranId otDate :: " + otDate);
		System.out.println("getTranId otDateStr :: " + otDateStr);

		keyStringQuery = "SELECT WORK_SITE, EMP_SITE, PAY_SITE "   
			+ "FROM  EMPLOYEE "
			+ "WHERE EMP_CODE = '" + empCode + "'";
		
		System.out.println("Employee fetch site sql from getTranId :::"+keyStringQuery); 
		crstmt = conn.createStatement();
		rsn20 = crstmt.executeQuery(keyStringQuery);	
		if (rsn20.next())
		{
			workSite = rsn20.getString("WORK_SITE");
			empSite = rsn20.getString("EMP_SITE");
			paySite = rsn20.getString("PAY_SITE");
		}
		rsn20.close();
		rsn20 = null;
		crstmt.close();
		crstmt=null;
		keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = 'w_emp_overtime'";
		System.out.println("keyStringQuery::"+keyStringQuery);
		crstmt = conn.createStatement();
		rsn20 = crstmt.executeQuery(keyStringQuery);

		if (rsn20.next())
		{
			keyString = rsn20.getString(1);
			keyCol = rsn20.getString(2);
			tranSer = rsn20.getString(3);				
		}
		crstmt.close();
		crstmt=null;
		rsn20.close();
		rsn20=null;
		xmlValues = "";
		xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
		xmlValues = xmlValues + "<Header></Header>";
		xmlValues = xmlValues + "<Detail1>";
		xmlValues = xmlValues + "<site_code>" + workSite + "</site_code>";
		xmlValues = xmlValues + "<work_site>" + workSite + "</work_site>";
		xmlValues = xmlValues + "<emp_site>" + empSite + "</emp_site>";
		xmlValues = xmlValues + "<pay_site>" + paySite + "</pay_site>";
		xmlValues = xmlValues + "<ot_date>" + otDateStr + "</ot_date>";
		xmlValues = xmlValues +"</Detail1></Root>";
		System.out.println("xmlValues  :["+xmlValues+"]");
		TransIDGenerator tg = new TransIDGenerator(xmlValues, "SUN", CommonConstants.DB_NAME);
	    tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
	}
	catch(SQLException se)
	{				
		System.out.println("SQLException :Generating id[failed] : " + "\n" +se.getMessage());
	}
	catch(Exception ex)
	{
		System.out.println("Exception8:Generating id [failed]:" + "\n" +ex.getMessage());
	}
	return tranId;
}//end of getTranId function .

// Modified by Piyush on 19/03/2015 [To generated tran id as per transetup].End

private String getTranId(Connection conn )
{
	String tranSer = "";
	String keyString = "";
	String keyCol = "";
	String keyStringQuery = "";
	String xmlValues="";
	Statement crstmt = null;
	//ResultSet rs=null;
	String tranId="";
	
	try
	{ 
		//Tran_window name changed by msalam on 06/07/07
		keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = 'w_emp_overtime'";
		System.out.println("keyStringQuery::"+keyStringQuery);
		crstmt = conn.createStatement();
		rsn20 = crstmt.executeQuery(keyStringQuery);
		//writeLog(filePtr,"[AddProcessEJB]ResultSet n20 Opened",true);

		if (rsn20.next())
		{
			keyString = rsn20.getString(1);
			keyCol = rsn20.getString(2);
			tranSer = rsn20.getString(3);				
		}
		crstmt.close();
		crstmt=null;
		rsn20.close();
		rsn20=null;
		//writeLog(filePtr,"[AddProcessEJB]ResultSet n20 Closed",true);
		xmlValues = "";
		xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
		xmlValues = xmlValues + "<Header></Header>";
		xmlValues = xmlValues + "<Detail1>";
		xmlValues = xmlValues +"</Detail1></Root>";
		System.out.println("xmlValues  :["+xmlValues+"]");
		TransIDGenerator tg = new TransIDGenerator(xmlValues, "SUN", CommonConstants.DB_NAME);
	    tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
	}
	catch(SQLException se)
	{				
		System.out.println("SQLException :Generating id[failed] : " + "\n" +se.getMessage());
	}
	catch(Exception ex)
	{
		System.out.println("Exception8:Generating id [failed]:" + "\n" +ex.getMessage());
	}
	return tranId;
}//end of getTranId function .

private String getExistTranId(String empCode,Timestamp procDate, Connection con )
{
	String retStr = null;  	
	try
	{
		String sql="SELECT TRAN_ID FROM EMPOTIME WHERE EMP_CODE = ? AND OT_TIME_FR <= ? AND OT_TIME_TO >= ?";  // manoj
		System.out.println("SQL ::"+sql);
		System.out.println("Emp Code "+empCode);
		System.out.println("procDate "+procDate);
		
		PreparedStatement stmtn21=null;
		stmtn21=con.prepareStatement(sql);
		stmtn21.setString(1,empCode);
		stmtn21.setTimestamp(2,procDate);
		stmtn21.setTimestamp(3,procDate);
		ResultSet rsn21=null;
		rsn21=stmtn21.executeQuery();
		//writeLog(filePtr,"[AddProcessEJB]ResultSet n21 Opened",true);
		if(rsn21.next())
		{
			retStr=rsn21.getString("tran_id");
		}
		stmtn21.close();
		stmtn21=null;
		rsn21.close();
		rsn21=null;
		//writeLog(filePtr,"[AddProcessEJB]ResultSet n21 Closed",true);
	}
	catch(SQLException se)
	{				
		System.out.println("SQLException :Generating id[failed] : " + "\n" +se.getMessage());
	}
	catch(Exception ex)
	{
		System.out.println("Exception8:Generating id [failed]:" + "\n" +ex.getMessage());
	}
	return retStr;
	}//end of getExistTranId function	


	//Added by msalam on 25/06/07 
	//To check whether the record exists in Attd_reg for given (emp_code, attd_date)
	private boolean isAttdRegExistFor(String empCode, Timestamp attdDate, Connection conn)
	{
		String sql = "Select count(*) from Attd_reg where emp_Code = '" + empCode + "' and Attd_Date = ?";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int count = 0;

		try{
			System.out.println("Sql in isAttdRegExistFor :: " + sql + "\n otDate = " + attdDate + " Emp Code = " + empCode);
			//System.out.println("Sql in isAttdRegExistFor :: " + sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, attdDate);
			
			rs = pstmt.executeQuery();
			
			if(rs.next())
				count = rs.getInt(1);
			
			rs.close();
			rs = null;
			
			pstmt.close();
			pstmt = null;
		}catch(SQLException ex){
			ex.printStackTrace();
			System.out.println("Error in isAttddRegExistFor 1");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Error in isAttdRegExistFor 2");
		}
		
		System.out.println("Count in isAttdRegExistFor" + count);
		
		//if found the cound > 0 else count = 0;
		return count > 0; 
	}
	//To Check whether record exist in EMPOTIME_DET FOR given employee and ot_date
	//isEmpOTimeExistFor(tranId, lineNo, conn)
	private boolean isEmpOTimeExistFor(String empCode, Timestamp otDate, Connection conn)
	{
		String sql = "SELECT COUNT(*) FROM EMPOTIME_DET WHERE Emp_Code = '" + empCode + "' AND OT_DATE = ?";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int count = 0;

		try{
			System.out.println("Sql in isEmpOTimeExistFor :: " + sql + "\n otDate = " + otDate + " Emp Code = " + empCode);
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, otDate);
			
			rs = pstmt.executeQuery();
			
			if(rs.next())
				count = rs.getInt(1);
			
			rs.close();
			rs = null;
			
			pstmt.close();
			pstmt = null;
		}catch(SQLException ex){
			ex.printStackTrace();
			System.out.println("Error in isEmpOTimeExistFor 1");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Error in isEmpOTimeExistFor 2");
		}
		
		//if found the cound > 0 else count = 0;
		System.out.println("Count in isEmpOTimeExistFor :: " + count);
		
		return count > 0; 
	}
	private boolean isApprevedExistFor(String empCode, Timestamp otDate, Connection conn)
	{
		String sql = "SELECT COUNT(*) FROM EMPOTIME_DET WHERE Emp_Code = '" + empCode + "' AND OT_DATE = ? and approved_flag <> 'N'";
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int count = 0;

		try{
			System.out.println("Sql in isApprovedExistFor :: " + sql + "\n otDate = " + otDate + " Emp Code = " + empCode);
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, otDate);
			
			rs = pstmt.executeQuery();
			
			if(rs.next())
				count = rs.getInt(1);
			
			rs.close();
			rs = null;
			
			pstmt.close();
			pstmt = null;
		}catch(SQLException ex){
			ex.printStackTrace();
			System.out.println("Error in isEmpOTimeExistFor 1");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Error in isEmpOTimeExistFor 2");
		}
		
		//if found the cound > 0 else count = 0;
		System.out.println("Count in isEmpOTimeExistFor :: " + count);
		
		return count > 0; 
	}
	
	private void updateEmpOtimeFor(String tranId, String empCode, Timestamp fromDate, Timestamp toDate, Connection conn){
		System.out.println("fromDt :::" + fromDate + "::: toDate:" + toDate + ":");
//		String sql = " select sum(nvl(ot_time, 0)), sum(nvl(cal_ot_time, 0))  " + 
		String sql = " select sum(nvl(ot_time, 0)), sum(nvl(cal_ot_time, 0)), sum(nvl(OT_HOURS_TIME, 0)), sum(nvl(CAL_OT_HRS_TIME, 0)) " +
					"	from empotime_det  " +
					" where emp_code = ? " +
					"	and ot_date between ? and ? ";
	
		String updateSql = " update empotime set " +
							"	ot_hours = ?,  	 " +
							"	cal_ot_hours = ?, " +
							"	ot_hours_time = ?, " +
							"	cal_ot_hrs_time = ? " +
							" where tran_id = ?  " +
							"	and emp_code = ? ";
			
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		double totalOtHours = 0.0;
		double calTotOtHours = 0.0;
		double totalOtTime = 0.0;
		double calTotOtTime = 0.0;
		

		try{
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setTimestamp(2, fromDate);
			pstmt.setTimestamp(3, toDate);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				totalOtHours = rs.getDouble(1);
				calTotOtHours = rs.getDouble(2);
				totalOtTime = rs.getDouble(3);
				calTotOtTime = rs.getDouble(4);
			}

			rs.close();
			rs = null;
			
			pstmt.close();
			pstmt = null;
			
			System.out.println("Total Ot Hours for empCode = " + empCode + " Hours = " + totalOtHours + " TimeInHrs = " + totalOtTime);

			pstmt = conn.prepareStatement(updateSql);
			pstmt.setDouble(1, totalOtHours);
			pstmt.setDouble(2, calTotOtHours);
			pstmt.setDouble(3, totalOtTime);
			pstmt.setDouble(4, calTotOtTime);
			pstmt.setString(5, tranId);
			pstmt.setString(6, empCode);
			
			int updCount = 0;
			updCount = pstmt.executeUpdate();
			System.out.println("UpdCount for empCode = " + empCode);
			
			pstmt.close();
			pstmt = null;
		}catch(SQLException ex){
			ex.printStackTrace();
			System.out.println("Error in Update EmpOtime 1");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Error in Update EmpOtime 2");
		}
		//if found the cound > 0 else count = 0;
	}
	//End by msalam
	//Added by nisar on 21/02/07

	//End by msalam
	
	private String getTimeInHrsFormat(long min)
	{
		boolean isNeg=false;
		String retStr="";
		String str_min="";
        if(min < 0 )
		{
			min=-(min);
			isNeg=true;
		}
		long hr=min/60;
		long minute=min%60;
		str_min=Long.toString(minute);
		System.out.println("minute in getTimeInHrsFormat :::: [" + minute + "]");
		if(str_min.length()<=1)
		{
			str_min="0"+str_min;
		}
		if(isNeg == true)
		retStr= "-";
		retStr=retStr+hr+"."+str_min;
		System.out.println("retStr in getTimeInHrsFormat:::: [" + retStr + "]"); 
		return retStr;
	}
	
	//Added by nisar on 21/02/07
	/*private static void writeLog(File f,String ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			pw.println(ex);
			pw.close();
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}
	private static void writeLog(File f,Exception ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			ex.printStackTrace(pw);
			pw.close();
		}
		catch(Exception exWe){exWe.printStackTrace();}
	}//ended by nisar on 21/02/07*/

	//Start - function added by jaimin 13/06/2008 (AD89SUN013)
	private int compareTime(String time1, String time2)
	{
		int retVal = 0;
		int totMin1 = timeInMinute(time1);
		int totMin2 = timeInMinute(time2);
		if (totMin1 < totMin2)
		{
			retVal = -1;
		}
		else if (totMin1 > totMin2)
		{
			retVal = 1;
		}
		return retVal;
	}

	private int timeInMinute(String time)
	{
		int timeInMin = 0;
		System.out.println("Time from table ::"+time);
		if (time != null && time.trim().length() > 4 )
		{
			int strHr = Integer.parseInt(time.substring(0,2));
			int strMin = Integer.parseInt(time.substring(3));
			timeInMin = (strHr*60)+strMin;
		}
		System.out.println("Total minute :: "+timeInMin);
		return timeInMin;
	}
	//End - function added by jaimin on 13/06/2008 (AD89SUN013)

}//end of ejb
