package ibase.webitm.ejb.adm;

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import java.util.Date;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


@SuppressWarnings({"unused", "deprecation"})
@Stateless
public class ITDeclarationIC extends ValidatorEJB implements ITDeclarationICRemote, ITDeclarationICLocal {

	static E12GenericUtility genericUtility = new E12GenericUtility();

	
	String acctPrd = "", empCode = "";;

	@Override
	public String wfValData(String xmlString, String xmlStringHdr, String xmlStringAll, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException {
		String retString = "";
		Document dom = null, dom1 = null, domAll = null;
		try {
			System.out.println("\n\txmlString[" + xmlString + "]\n\txmlStringHdr[" + xmlStringHdr + "]\n\txmlStringAll[" + xmlStringAll + "]\n\tobjContext[" + objContext + "]\n\teditFlag[" + editFlag + "]\n");
			if (xmlString != null && xmlString.trim().length() > 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlStringHdr != null && xmlStringHdr.trim().length() > 0) {
				dom1 = genericUtility.parseString(xmlStringHdr);
			}
			if (xmlStringAll != null && xmlStringAll.trim().length() > 0) {
				domAll = genericUtility.parseString(xmlStringAll);
			}
			retString = wfValData(dom, dom1, domAll, objContext, editFlag, xtraParams);
		} catch (Exception e) {
			System.out.println(":::" + this.getClass().getSimpleName() + "::" + e.getMessage());
			e.getMessage();
		}
		return retString;
	}

	@Override
	public String wfValData(Document dom, Document domHdr, Document domAll, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException {
		String errString = "", sql = "", acct_prd = "", childNodeName = "", userId = "", emp_code__decl = "", ad_code = "", pay_site = "", cadre = "", grade = "", adm_env = "";
		Connection conn = null;
		NodeList parentNodeList = null, childNodeList = null;
		Node parentNode = null, childNode = null;
		int ctr = 0, childNodeLength = 0, currentFormNo = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			AdmCommon admCommon = new AdmCommon();
			ConnDriver con = new ConnDriver();
			conn = con.getConnectDB("Driver");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}
			switch (currentFormNo) {
			case 1: {
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeLength = childNodeList.getLength();

				for (ctr = 0; ctr < childNodeLength; ctr++) {
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					
					if(childNodeName.equalsIgnoreCase("tran_id")) {
						String key_flag = "";
						sql = "select key_flag from transetup where tran_window = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, "w_emp_itdecl_byac");
						rs = pstmt.executeQuery();
						if(rs.next()) {
							key_flag = checkNull(rs.getString("key_flag")).trim();
						} else {
							key_flag = "A";
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						String tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom)).trim();
						if("M".equalsIgnoreCase(key_flag)) {
							if(tran_id.length() <= 0) {
								errString = getErrorString("tran_id", "VETRNID1", userId);
								break;
							} else {
								sql = "select tran_id from emp_itdecl_hdr where tran_id = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, tran_id);
								rs = pstmt.executeQuery();
								if(rs.next()) {
									errString = getErrorString("tran_id", "VTRANEXIST", userId);
									break;
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}
						} else if ("A".equalsIgnoreCase(key_flag)){
							if(tran_id.length() > 0) {
								sql = "select tran_id from emp_itdecl_hdr where tran_id = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, tran_id);
								rs = pstmt.executeQuery();
								if(rs.next()) {
									errString = getErrorString("tran_id", "VTRANEXIST", userId);
									break;
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}
						}
					}

					if (childNodeName.equalsIgnoreCase("acct_prd")) {
						acct_prd = checkNull(genericUtility.getColumnValue(childNodeName.toLowerCase(), dom));
						emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__decl", dom));
						pay_site = checkNull(genericUtility.getColumnValue("pay_site", dom));
						grade = checkNull(genericUtility.getColumnValue("grade", dom));
						cadre = checkNull(genericUtility.getColumnValue("cadre", dom));
						adm_env = checkNull(genericUtility.getColumnValue("adm_env", dom));
						if (acct_prd.trim().length() > 0) {
							sql = "select code from acctprd where code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, acct_prd);
							rs = pstmt.executeQuery();
							if (!rs.next()) {
								errString = getErrorString("acct_prd", "VMFENACP04", userId);
								break;
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							//TODO Check for Allowed extra days for Declaration.
							String strExtraDay = checkNull(admCommon.getEnv("999999", "EXTRA_DAYS_IT_DECL", conn)).trim();
							int intExtraDays = 0;
							java.sql.Timestamp toDate = null;
							
							if ("NULLFOUND".equalsIgnoreCase(strExtraDay)) {
								intExtraDays = 0;
							} else {
								try{
									intExtraDays = Integer.parseInt(strExtraDay);
								} catch(Exception e) {
									intExtraDays=0;
								}
							}
							
							sql = "SELECT TO_DATE + " + intExtraDays + " as lastDate FROM ACCTPRD WHERE CODE=?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, acct_prd);
							rs = pstmt.executeQuery();
							if (rs.next()) {
								toDate = rs.getTimestamp("lastDate");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
							String todateString = sdf.format(toDate);
							boolean futuredate = checkFutureDate(todateString);
							if (!futuredate ) {
								errString = getErrorString("acct_prd", "NOTACCTPRD", userId);
								break;
							}
							
							/*if ("A".equalsIgnoreCase(editFlag)) {
								sql = "select tran_id from emp_itdecl_hdr where acct_prd = ? and emp_code__decl = ? and qtr_no = 9 and decl_type = 'D'";
								System.out.println("SQL for Validation record Existence[" + sql + "] in ADD Mode");
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, acct_prd);
								pstmt.setString(2, emp_code__decl);
								rs = pstmt.executeQuery();
								if (rs.next()) {
									errString = getErrorString("acct_prd", "DECLEXIST", userId);
									break;
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								
								String tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom)).trim();
								if(tran_id.length() > 0) {
									int count = 0;
									System.out.println("Validation for tran_id [" + tran_id + "] in ADD Mode");
									sql = "select count(*) as count from emp_itdecl_hdr where tran_id = ?";
									pstmt = conn.prepareStatement(sql);
									pstmt.setString(1, tran_id);
									rs = pstmt.executeQuery();
									if (rs.next()) {
										
										errString = getErrorString("tran_id", "DECLEXIST", userId);
										break;
									}
									rs.close();
									rs = null;
									pstmt.close();
									pstmt = null;
								}
							} else {
								String tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom));
								sql = "select tran_id from emp_itdecl_hdr where acct_prd = ? and emp_code__decl = ?  and qtr_no = 9 and decl_type = 'D' and tran_id <> ?";
								System.out.println("SQL for Validation record Existence[" + sql + "] in EDIT Mode");
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, acct_prd);
								pstmt.setString(2, emp_code__decl);
								pstmt.setString(3, tran_id);
								rs = pstmt.executeQuery();
								if (rs.next()) {
									errString = getErrorString("acct_prd", "DECLEXIST", userId);
									break;
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}*/
						} else {
							errString = getErrorString("acct_prd", "VMFENACP03", userId);
							break;
						}
					}

					if(childNodeName.equalsIgnoreCase("adm_env")) {
						adm_env = checkNull(genericUtility.getColumnValue("adm_env", dom)).trim();
						pay_site = checkNull(genericUtility.getColumnValue("pay_site", dom));
						cadre = checkNull(genericUtility.getColumnValue("cadre", dom));
						grade = checkNull(genericUtility.getColumnValue("grade", dom));
						
						if(adm_env.length() > 0) {
							String admEnv = admCommon.getAdmEnv(pay_site, cadre, grade, "AD_CODE_DECL_TYPE", new Timestamp(Calendar.getInstance().getTimeInMillis()), conn);
							System.out.println("\n\t admEnv["+admEnv+"] \n\t " + adm_env);
							if("NULLFOUND".equalsIgnoreCase(adm_env)) {
								admEnv = admCommon.getEnv("999999", "AD_CODE_DECL_TYPE", conn);
								if("NULLFOUND".equalsIgnoreCase(adm_env)) {
									errString = getErrorString("", "VSENVAR1", userId);
									break;
								} else if(!admEnv.equalsIgnoreCase(adm_env)) {
									errString = getErrorString("", "VSENVAR1", userId);
									break;
								}
								System.out.println("\n\t admEnv["+admEnv+"] \n\t " + adm_env);
							} else if(!admEnv.equalsIgnoreCase(adm_env)) {
								errString = getErrorString("", "VSENVAR1", userId);
								break;
							}
							System.out.println("\n\t admEnv["+admEnv+"] \n\t " + adm_env);
						} else {
							errString = getErrorString("", "VSENVAR1", userId);
							break;
						}
						
						
						
					}
					
					if (childNodeName.equalsIgnoreCase("emp_code__decl")) {
						java.sql.Date relieve_date = null;
						
						emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__decl", dom));
						acct_prd = checkNull(genericUtility.getColumnValue("acct_prd", dom));
						if (emp_code__decl.trim().length() == 0) {
							errString = getErrorString("emp_code__decl", "VTEMPCDNUL", userId);
							break;
						} else {
							sql = "select emp_code, relieve_date from employee where emp_code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, emp_code__decl);
							rs = pstmt.executeQuery();
							if (!rs.next()) {
								errString = getErrorString("emp_code__decl", "VTEMPCDINV", userId);
								break;
							} else {
								relieve_date = rs.getDate("relieve_date");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							String confirmed = "";
							sql = "SELECT CONFIRMED FROM FULLFINAL_HDR WHERE EMP_CODE = ? AND CASE WHEN CONFIRMED IS NULL THEN 'N' ELSE CONFIRMED END <> 'X'";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, emp_code__decl);
							rs = pstmt.executeQuery();
							if (rs.next()) {
								confirmed = rs.getString("CONFIRMED");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							if (relieve_date != null || confirmed.equalsIgnoreCase("Y")) {
								errString =  getErrorString("tran_date","VTEMPRELFS",userId);
								break;
							}
							
							
							
							
							
							sql = "select tran_id from emp_itdecl_hdr where qtr_no = '9' and decl_type ='D'  and confirmed = 'N' and emp_code__decl = ? and acct_prd = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, emp_code__decl);
							pstmt.setString(2, acct_prd);
							rs = pstmt.executeQuery();
							if (rs.next()) {
								errString = getErrorString("emp_code__decl", "VTEMP4", userId);
								break;
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
					}
					
					if (childNodeName.equalsIgnoreCase("emp_code__ac")) {
						emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__ac", dom));
						pay_site = checkNull(genericUtility.getColumnValue("pay_site", dom));
						if (emp_code__decl.trim().length() == 0) {
							errString = getErrorString("emp_code__ac", "VTEMPCDNUL", userId);
							break;
						} else {
							sql = "select site_code from site_itdecl_aprvr where ? in (emp_code__aprv,emp_code__aprv_alt1,emp_code__aprv_alt2) and site_code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, emp_code__decl);
							pstmt.setString(2, pay_site);
							rs = pstmt.executeQuery();
							if (!rs.next()) {
								errString = getErrorString("", "VTIVDECLAC", userId);
								break;
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
					}
				}
				int det2Count = domAll.getElementsByTagName("Detail2") .getLength();
				System.out.println("Number of Detail2 records: " + det2Count);
			}
				break;
			case 2: {
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeLength = childNodeList.getLength();
				for (ctr = 0; ctr < childNodeLength; ctr++) {
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();

					if (childNodeName.equalsIgnoreCase("amount_decl")) {
						String str_amount = genericUtility.getColumnValue("amount_decl", dom);
						str_amount = str_amount == null ? "0" : str_amount.trim();
						ad_code = checkNull(genericUtility.getColumnValue("ad_code", dom)).trim();
						boolean isNegativeAllowed = checkNegativeAllowance(ad_code, conn);
						System.out.println("Looking for ad_code [" + ad_code + "] isNegativeAllowed:::[" + isNegativeAllowed + "] for [" + childNodeName + "]");
						double tempAmt = 0;
						try {
							tempAmt = Double.parseDouble(str_amount);
						} catch (Exception e) {
							tempAmt = 0;
						}
						if (!isNegativeAllowed) {
							if (tempAmt < 0) {
								errString = getErrorString("amount_decl", "VMAMT1", userId);
								break;
							}
						}
					}
					if (childNodeName.equalsIgnoreCase("ad_code")) {
						ad_code = checkNull(genericUtility.getColumnValue("ad_code", dom)).trim();
						if (ad_code.length() <= 0) {
							errString = getErrorString("ad_code", "VMADDNAL", userId);
							break;
						} else {
							sql = "select i.ad_code from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code and i.ad_code = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, ad_code);
							rs = pstmt.executeQuery();
							if(!rs.next()){
								System.out.println("AD_CODE IS INVALID : [" + ad_code + "]");
								errString = getErrorString("ad_code", "VMAD3", userId);
								break;
							} else {
								System.out.println("AD_CODE IS VALID : [" + ad_code + "]");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
					}
					if (childNodeName.equalsIgnoreCase("amount_proof")) {
						String str_amount = genericUtility.getColumnValue("amount_proof", dom);
						str_amount = str_amount == null ? "0" : str_amount.trim();
						ad_code = checkNull(genericUtility.getColumnValue("ad_code", dom)).trim();
						boolean isNegativeAllowed = checkNegativeAllowance(ad_code, conn);
						System.out.println("Looking for ad_code [" + ad_code + "] isNegativeAllowed:::[" + isNegativeAllowed + "] for [" + childNodeName + "]");
						double tempAmt = 0;
						try {
							tempAmt = Double.parseDouble(str_amount);
						} catch (Exception e) {
							tempAmt = 0;
						}
						if (!isNegativeAllowed) {
							if (tempAmt < 0) {
								errString = getErrorString("amount_proof", "VMAMT1", userId);
								break;
							}
						}
					}
				}
			}
				break;
			}
		} catch (Exception e) {
			System.out.println(":::" + this.getClass().getSimpleName() + ":::" + e.getMessage());
			errString = getErrorString("", "VTINEX", userId);
			e.printStackTrace();
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				System.out.println("Closed all Database Resource...!");
			} catch (Exception e) {
				System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]::wfValData::[" + e.getMessage()+"]");
			}
		}
		return errString;
	}

	private boolean checkFutureDate(String strDate) throws ITMException {
		boolean result = false;
		try {
			E12GenericUtility genericUtility = new E12GenericUtility();
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
			Date finEffDate = sdf1.parse(genericUtility.getValidDateTimeString(strDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()));
			Date currDate = cal.getTime();
			currDate.setHours(0);
			currDate.setMinutes(0);
			currDate.setSeconds(0);
			finEffDate.setHours(0);
			finEffDate.setMinutes(0);
			finEffDate.setSeconds(0);
			String currDateS = sdf1.format(currDate);
			currDate=sdf1.parse(currDateS);
			System.out.println("Current Date of System [" + currDateS + "] ::: Eff. Date from XML [" + finEffDate + "]");
			System.out.println("compareTo::::::::"+currDate.compareTo(finEffDate));
			if( currDate.compareTo(finEffDate) <= 0) {
				result =true;
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ITMException(e);
		}
		return result;
	}

	private boolean checkNegativeAllowance(String ad_code, Connection conn) {
		boolean isNegativeAllowed = false;
		String tempStr = "";
		String sql = "select allow_negative from itdecl_fmt where ad_code = ? ";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, ad_code);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				tempStr = checkNull(rs.getString("allow_negative")).trim();
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if ("Y".equalsIgnoreCase(tempStr)) {
				isNegativeAllowed = true;
			}

		} catch (Exception e) {
			isNegativeAllowed = false;
		}
		return isNegativeAllowed;
	}

	private String checkNull(String input) {
		return input == null ? "" : input;
	}

	public String itemChanged(String xmlString, String xmlStringHdr,
			String xmlStringAll, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException,
			ITMException {

		Document dom = null, domHdr = null, domAll = null;
		String valueXmlString = "";
		try {
			if (xmlString != null && xmlString.trim().length() > 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlStringHdr != null && xmlStringHdr.trim().length() > 0) {
				domHdr = genericUtility.parseString(xmlStringHdr);
			}
			if (xmlStringAll != null && xmlStringAll.trim().length() > 0) {
				domAll = genericUtility.parseString(xmlStringAll);
			}
			valueXmlString = itemChanged(dom, domHdr, domAll, objContext, currentColumn, editFlag, xtraParams);
		} catch (Exception e) {
			System.out.println("Exception [" + this.getClass().getSimpleName() + "] : [itemChanged(S)] " + e.getMessage());
		}
		return valueXmlString;

	}

	
	public String itemChanged(Document dom, Document dom1, Document dom2,
			String objContext, String currentColumn, String editFlag,
			String xtraParams) throws RemoteException, ITMException {

		String sql = "", acct_prd = "", emp_code__decl = "", emp_code__ac = "", emp_name = "", empac_name = "", pay_site = "", it_no = "", email_id = "", str_amount = "", grade = "", cadre = "", adm_env = "";
		int currentFormNo = 0, seq_no = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = new StringBuffer();

		String empLoginCode = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
		SimpleDateFormat sdf = null;
		Calendar cal = Calendar.getInstance();
		try {
			AdmCommon admCommon = new AdmCommon();
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("Driver");

			// String userId =
			// genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");

			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}

			System.out.println("[" + this.getClass().getSimpleName() + "] [itemChanged(D)]:currentFormNo:" + currentFormNo);
			System.out.println("currentColumn:::::" + currentColumn);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\" encoding=''?>\r\n<Root>\r\n<header>\r\n<editFlag>");
			valueXmlString.append(editFlag).append("</editFlag>\r\n</header>\r\n");
			sdf = new SimpleDateFormat(genericUtility.getDispDateFormat());
			String today = sdf.format(cal.getTime());
			switch (currentFormNo) {
			case 1: {
				valueXmlString.append("<Detail1>\r\n");
				valueXmlString.append("<chg_date><![CDATA[").append(today).append("]]></chg_date>");

				if (currentColumn.trim().equals("itm_default")) {
					String key_flag = "";
					sql = "select key_flag from transetup where tran_window = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, "w_emp_itdecl_byac");
					rs = pstmt.executeQuery();
					if(rs.next()) {
						key_flag = checkNull(rs.getString("key_flag")).trim();
					} else {
						key_flag = "A";
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					sql = "select code from acctprd where sysdate between fr_date and to_date";
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if (rs.next()) {
						acct_prd = checkNull(rs.getString("code"));
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					sql = "select ddf_get_masters_name('EMPLOYEE', e.emp_code,'FML') as empac_name from employee e where e.emp_code = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, empLoginCode);
					rs = pstmt.executeQuery();
					if (rs.next()) {
						empac_name = rs.getString("empac_name");
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;

					/*
					 * sql =
					 * "select ea.site_code as pay_site, e.it_no as it_no, ea.emp_code__aprv as emp_code__ac, ddf_get_masters_name('EMPLOYEE', ea.emp_code__aprv,'FML') as empac_name, "
					 * +
					 * " e.email_id_off as email_id, ddf_get_masters_name('EMPLOYEE', e.emp_code,'FML') as emp_name "
					 * +
					 * " from site_itdecl_aprvr ea, employee e where ea.site_code in (SELECT employee.pay_site FROM employee WHERE employee.emp_code = ?) and e.emp_code = ? "
					 * ;
					 * 
					 * pstmt = conn.prepareStatement(sql); pstmt.setString(1,
					 * empLoginCode); pstmt.setString(2, empLoginCode); rs =
					 * pstmt.executeQuery();
					 * 
					 * if(rs.next()) { pay_site =
					 * checkNull(rs.getString("pay_site")); it_no =
					 * checkNull(rs.getString("it_no")); emp_code__ac =
					 * checkNull(rs.getString("emp_code__ac")); empac_name =
					 * checkNull(rs.getString("empac_name")); emp_name =
					 * checkNull(rs.getString("emp_name")); email_id =
					 * checkNull(rs.getString("email_id")); } rs.close(); rs =
					 * null; pstmt.close(); pstmt = null;
					 */
					
					if("M".equalsIgnoreCase(key_flag)) {
						valueXmlString.append("<tran_id protect = '0'/>");
					}

					valueXmlString.append("<tran_date><![CDATA[").append(today).append("]]></tran_date>");
					valueXmlString.append("<acct_prd><![CDATA[").append(acct_prd).append("]]></acct_prd>");
					valueXmlString.append("<emp_code__ac><![CDATA[").append(empLoginCode).append("]]></emp_code__ac>");
					valueXmlString.append("<empac_name><![CDATA[").append(empac_name).append("]]></empac_name>");
				}

				if (currentColumn.trim().equals("itm_defaultedit")) {/*
					emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__decl", dom));
					acct_prd = checkNull(genericUtility.getColumnValue("acct_prd", dom));
					pay_site = checkNull(genericUtility.getColumnValue("pay_site", dom));
					cadre = checkNull(genericUtility.getColumnValue("cadre", dom));
					grade = checkNull(genericUtility.getColumnValue("grade", dom));
					
					adm_env = admCommon.getAdmEnv(pay_site, cadre, grade, "AD_CODE_DECL_TYPE", new Timestamp(Calendar.getInstance().getTimeInMillis()), conn);
					if("NULLFOUND".equalsIgnoreCase(adm_env)) {
						adm_env = admCommon.getEnv("999999", "AD_CODE_DECL_TYPE", conn);
						if("NULLFOUND".equalsIgnoreCase(adm_env)) {
							adm_env = "";
						}
					}
					valueXmlString.append("<adm_env><![CDATA[").append(adm_env).append("]]></adm_env>");
					valueXmlString.append("<emp_code__decl protect = '1'><![CDATA[").append(emp_code__decl).append("]]></emp_code__decl>");
					valueXmlString.append("<acct_prd protect = '1'><![CDATA[").append(acct_prd).append("]]></acct_prd>");
				*/}

				if (currentColumn.trim().equals("emp_code__decl")) {
					emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__decl", dom)).trim();
					acct_prd = checkNull(genericUtility.getColumnValue("acct_prd", dom));
					if (emp_code__decl.length() > 0) {
						sql = "select pay_site, it_no, ddf_get_masters_name('EMPLOYEE', emp_code,'FML') as emp_name,  email_id_off as email_id, grade, cadre from employee where emp_code = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, emp_code__decl);
						rs = pstmt.executeQuery();
						if (rs.next()) {
							emp_name = checkNull(rs.getString("emp_name"));
							email_id = checkNull(rs.getString("email_id"));
							pay_site = checkNull(rs.getString("pay_site"));
							it_no = checkNull(rs.getString("it_no"));
							grade = checkNull(rs.getString("grade"));
							cadre = checkNull(rs.getString("cadre"));
						} else {
							emp_name = "";
							email_id = "";
							pay_site = "";
							it_no = "";
							grade = "";
							cadre = "";
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						valueXmlString.append("<emp_name><![CDATA[").append(emp_name).append("]]></emp_name>");
						valueXmlString.append("<email_id><![CDATA[").append(email_id).append("]]></email_id>");
						valueXmlString.append("<pay_site><![CDATA[").append(pay_site).append("]]></pay_site>");
						valueXmlString.append("<it_no><![CDATA[").append(it_no).append("]]></it_no>");
						valueXmlString.append("<grade><![CDATA[").append(grade).append("]]></grade>");
						valueXmlString.append("<cadre><![CDATA[").append(cadre).append("]]></cadre>");
						
						adm_env = admCommon.getAdmEnv(pay_site, cadre, grade, "AD_CODE_DECL_TYPE", new Timestamp(Calendar.getInstance().getTimeInMillis()), conn);
						if("NULLFOUND".equalsIgnoreCase(adm_env)) {
							adm_env = admCommon.getEnv("999999", "AD_CODE_DECL_TYPE", conn);
							if("NULLFOUND".equalsIgnoreCase(adm_env)) {
								adm_env = "";
							}
						}
						sql = "select nvl(max(seq_no), 0) + 1 as seq_no from emp_itdecl_hdr where qtr_no = '9' and decl_type ='D' and emp_code__decl = ? and acct_prd = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, emp_code__decl);
						pstmt.setString(2, acct_prd);
						rs = pstmt.executeQuery();
						if (rs.next()) {
							seq_no = rs.getInt("seq_no");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						valueXmlString.append("<seq_no><![CDATA[").append(seq_no).append("]]></seq_no>");
						valueXmlString.append("<adm_env><![CDATA[").append(adm_env).append("]]></adm_env>");
					} else {
						valueXmlString.append("<emp_name/>");
						valueXmlString.append("<email_id/>");
						valueXmlString.append("<pay_site/>");
						valueXmlString.append("<it_no/>");
						valueXmlString.append("<grade/>");
						valueXmlString.append("<cadre/>");
					}
					
				}
				valueXmlString.append("</Detail1>\r\n");
			}
				break;
			case 2: {
				valueXmlString.append("<Detail2>\r\n");
				System.out.println("*Before itm_default OF CASE 2.");
				
				if(currentColumn.trim().equals("itm_default")) {
					String tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom2, "1"));
					String key_flag = "";
					sql = "select key_flag from transetup where tran_window = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, "w_emp_itdecl_byac");
					rs = pstmt.executeQuery();
					if(rs.next()) {
						key_flag = checkNull(rs.getString("key_flag")).trim();
					} else {
						key_flag = "A";
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					if("M".equalsIgnoreCase(key_flag)){
						valueXmlString.append("<tran_id>").append("<![CDATA[" + tran_id + "]]>").append("</tran_id>");
					}
					
					String ad_code = checkNull(genericUtility.getColumnValue("amount_decl", dom)).trim();
					String ad_descr = "";
					if(ad_code.length() > 0) {
						sql = "select i.description as ad_descr from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code where i.ad_code = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, ad_code);
						rs = pstmt.executeQuery();
						
						if(rs.next()) {
							ad_descr = checkNull(rs.getString("ad_descr"));
						} else {
							ad_descr = "";
						}
						valueXmlString.append("<ad_descr><![CDATA[").append(ad_descr).append("]]></ad_descr>");
					}
				}
				
				if (currentColumn.trim().equals("amount_decl")) {
					str_amount = checkNull(genericUtility.getColumnValue("amount_decl", dom)).trim();
					if (str_amount.length() == 0) {
						valueXmlString.append("<amount_decl><![CDATA[0]]></amount_decl>");
					}
				}
				if (currentColumn.trim().equals("amount_proof")) {
					str_amount = checkNull(genericUtility.getColumnValue("amount_proof", dom)).trim();
					if (str_amount.length() == 0) {
						valueXmlString.append("<amount_proof><![CDATA[0]]></amount_proof>");
					}
				}
				valueXmlString.append("</Detail2>\r\n");
			}
				break;
			}
			valueXmlString.append("</Root>\r\n");
		} catch (Exception e) {
			System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]:[" + e.getMessage()+"]");
			e.printStackTrace();
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				System.out.println("Closed all Database Resource...!");
			} catch (Exception e) {
				System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]::itemChanged::[" + e.getMessage()+"]");
			}
		}
		return valueXmlString.toString();

	}

	public String postSaveRec(String xmlString1, String domId, String objContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException {
		Document dom = null;
		String errString = "";
		try {
			if (xmlString1 != null && xmlString1.trim().length() > 0) {
				dom = genericUtility.parseString(xmlString1);
				errString = executePostSaveRec(dom, domId, objContext, editFlag, xtraParams, conn);
			}
		} catch (Exception e) {
			System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]::postSaveRec(S)::[" + e.getMessage()+"]");
			throw new ITMException(e);
		}
		return errString;
	}

	private String executePostSaveRec(Document dom, String domID, String objContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException {
		
		String declType = "", tranID = "", errString = "", chgUser = "", chgTerm = "", remarks = "", tranIdNew = "", empAdStatus = "", selectSql = "", updateSql = "", adCode = "", empAdAprv = "", insertSql = "", tranIDDom = "";
		double amountDecl = 0d, amountProof = 0d, amountDeclOld = 0d, amountProofOld = 0d, amountOrg = 0d, proofAmtOrg = 0d;
		int updCnt = 0, insCnt = 0;

		ResultSet rs = null, rs1 = null;
		PreparedStatement pstmt = null, pstmt1 = null, pstmtUpd = null, pstmtIns = null;

		try {
			AdmCommon admCommon = new AdmCommon();
			System.out.println("Parametes received in postSave redord of emp_itdecl_byac \n\t domID ["+domID+"]\n\t objContext["+objContext+"]\n\t editFlag ["+editFlag+"]\n\t xtraParams ["+xtraParams+"]");
			
			conn.setAutoCommit(false);
			if (dom != null) {
				tranIDDom = genericUtility.getColumnValue("tran_id", dom);
			}
			String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			empAdAprv = admCommon.getEnv("999999", "EMP_AD_APRV", conn);


			if (empAdAprv.equals("NULLFOUND") || empAdAprv.equals("N")) {
				empAdStatus = "Y";
			} else {
				empAdStatus = "N";
			}

			int count = 0;
			selectSql = "SELECT COUNT(1) AS LINE_NO FROM EMP_ITDECL_DET WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(selectSql);
			pstmt.setString(1, tranIDDom);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				count = rs.getInt("LINE_NO");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			int dom2Length = dom.getElementsByTagName("Detail2").getLength();
			
			if (count == 0) {
				errString = getErrorString("", "VTITPOSV01", userId);
				return errString;
			} else if (count != dom2Length){
				errString = getErrorString("", "VTITPOSV01", userId);
				return errString;
			} else{
				System.out.println("DOM and INSERT have same records.. \\123456789");
			}
			

			selectSql = "SELECT ACCT_PRD, EMP_CODE__DECL, IT_NO, DECL_TYPE, CHG_USER, CHG_TERM FROM EMP_ITDECL_HDR WHERE TRAN_ID = ? ";
			pstmt = conn.prepareStatement(selectSql);
			pstmt.setString(1, tranIDDom);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				acctPrd = rs.getString("ACCT_PRD");
				empCode = rs.getString("EMP_CODE__DECL");
				declType = rs.getString("DECL_TYPE");
				chgUser = rs.getString("CHG_USER");
				chgTerm = rs.getString("CHG_TERM");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			selectSql = "SELECT MAX(TRAN_ID) AS TRAN_ID FROM EMP_IT_DECLARATION WHERE EMP_CODE = ? AND ACCT_PRD = ? ";
			pstmt = conn.prepareStatement(selectSql);
			pstmt.setString(1, empCode);
			pstmt.setString(2, acctPrd);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				tranID = rs.getString("TRAN_ID");
				tranIdNew = tranID;
			}
			if (tranID == null) {
				tranID = "";
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			selectSql = "SELECT AD_CODE, AMOUNT_DECL, AMOUNT_PROOF, AMOUNT_DECL__OLD, AMOUNT_PROOF__OLD FROM EMP_ITDECL_DET WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(selectSql);
			pstmt.setString(1, tranIDDom);
			rs = pstmt.executeQuery();

			if (declType != null && "D".equalsIgnoreCase(declType)) {
				selectSql = "SELECT AMOUNT, AMOUNT_PROOF FROM EMP_IT_DECLARATION WHERE EMP_CODE = ? AND ACCT_PRD = ? AND AD_CODE = ? AND TRAN_ID = ? for update nowait";
				pstmt1 = conn.prepareStatement(selectSql);
				while (rs.next()) {
					System.out.println("\n\tTRAN_ID[" + tranID + "]\n\t TRAN_ID Length[" + tranID.trim().length() + "]");
					if (tranID.trim().length() == 0) {
						System.out.println("TRAN_ID is BLANK from EMP_IT_DECLARATION");
					}
					adCode = rs.getString("AD_CODE");
					amountDecl = rs.getDouble("AMOUNT_DECL");
					amountProof = rs.getDouble("AMOUNT_PROOF");
					amountDeclOld = rs.getDouble("AMOUNT_DECL__OLD");
					amountProofOld = rs.getDouble("AMOUNT_PROOF__OLD");
					
					
					pstmt1.setString(1, empCode);
					pstmt1.setString(2, acctPrd);
					pstmt1.setString(3, adCode);
					pstmt1.setString(4, tranID);
					rs1 = pstmt1.executeQuery();

					if (rs1.next()) {
						amountOrg = rs1.getDouble("AMOUNT");
						proofAmtOrg = rs1.getDouble("AMOUNT_PROOF");
						
						if(amountDeclOld == amountOrg && amountProofOld == proofAmtOrg) {
							if (amountDecl != amountOrg || amountProof != proofAmtOrg) {
								updateSql = "UPDATE EMP_IT_DECLARATION SET TRAN_DATE = ?, AMOUNT = ?, AMOUNT_OLD = ?, AMOUNT_PROOF = ?, AMOUNT_PROOF_OLD = ?,  "
										+ " CHG_DATE = ?, CHG_USER = ?, CHG_TERM = ? WHERE TRAN_ID = ? AND EMP_CODE = ? AND ACCT_PRD = ? AND AD_CODE = ? ";

								pstmtUpd = conn.prepareStatement(updateSql);
								pstmtUpd.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
								pstmtUpd.setDouble(2, amountDecl);
								pstmtUpd.setDouble(3, amountOrg);
								pstmtUpd.setDouble(4, amountProof);
								pstmtUpd.setDouble(5, proofAmtOrg);
								pstmtUpd.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis()));
								pstmtUpd.setString(7, chgUser);
								pstmtUpd.setString(8, chgTerm);
								pstmtUpd.setString(9, tranID);
								pstmtUpd.setString(10, empCode);
								pstmtUpd.setString(11, acctPrd);
								pstmtUpd.setString(12, adCode);
								updCnt = pstmtUpd.executeUpdate();

								if (updCnt >= 1) {
									System.out.println("Updated delcaration amount into EMP_IT_DECLARATION Successfully :::: " + updCnt);
								}
								pstmtUpd.close();
								pstmtUpd = null;

								updateSql = "UPDATE EMP_ITDECL_DET SET AMOUNT_DECL__OLD = ?,  AMOUNT_PROOF__OLD = ? "
										+ " WHERE TRAN_ID = ? AND AD_CODE = ? ";
								pstmtUpd = conn.prepareStatement(updateSql);
								pstmtUpd.setDouble(1, amountOrg);
								pstmtUpd.setDouble(2, proofAmtOrg);
								pstmtUpd.setString(3, tranIDDom);
								pstmtUpd.setString(4, adCode);
								updCnt = pstmtUpd.executeUpdate();

								if (updCnt >= 1) {
									System.out.println("Updated Delcaration Old Amount Into EMP_ITDECL_DET Successfully.....:: " + updCnt);
								}
								pstmtUpd.close();
								pstmtUpd = null;
							}
						} else {
							System.out.println("Record Mismatch OLD DECL[" + amountDeclOld +"] DECL from IT_DECLARATION["+ amountOrg  +"]OLD PROOF["+ amountProofOld  +"]PROOF from IT_DECLARATION["+  proofAmtOrg + "]");
							errString = getErrorString("", "VTIVDEPRUP", userId);
							conn.rollback();
							break;
						}
						
						/*if (amountDecl != amountOrg || amountProof != proofAmtOrg) {
							updateSql = "UPDATE EMP_IT_DECLARATION SET TRAN_DATE = ?, AMOUNT = ?, AMOUNT_OLD = ?, AMOUNT_PROOF = ?, AMOUNT_PROOF_OLD = ?,  "
									+ " CHG_DATE = ?, CHG_USER = ?, CHG_TERM = ? WHERE TRAN_ID = ? AND EMP_CODE = ? AND ACCT_PRD = ? AND AD_CODE = ? ";

							pstmtUpd = conn.prepareStatement(updateSql);
							pstmtUpd.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
							pstmtUpd.setDouble(2, amountDecl);
							pstmtUpd.setDouble(3, amountOrg);
							pstmtUpd.setDouble(4, amountProof);
							pstmtUpd.setDouble(5, proofAmtOrg);
							pstmtUpd.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis()));
							pstmtUpd.setString(7, chgUser);
							pstmtUpd.setString(8, chgTerm);
							pstmtUpd.setString(9, tranID);
							pstmtUpd.setString(10, empCode);
							pstmtUpd.setString(11, acctPrd);
							pstmtUpd.setString(12, adCode);
							updCnt = pstmtUpd.executeUpdate();

							if (updCnt >= 1) {
								System.out.println("Updated delcaration amount into EMP_IT_DECLARATION Successfully :::: " + updCnt);
							}
							pstmtUpd.close();
							pstmtUpd = null;

							updateSql = "UPDATE EMP_ITDECL_DET SET AMOUNT_DECL__OLD = ?,  AMOUNT_PROOF__OLD = ? "
									+ " WHERE TRAN_ID = ? AND AD_CODE = ? ";
							pstmtUpd = conn.prepareStatement(updateSql);
							pstmtUpd.setDouble(1, amountOrg);
							pstmtUpd.setDouble(2, proofAmtOrg);
							pstmtUpd.setString(3, tranIDDom);
							pstmtUpd.setString(4, adCode);
							updCnt = pstmtUpd.executeUpdate();

							if (updCnt >= 1) {
								System.out.println("Updated Delcaration Old Amount Into EMP_ITDECL_DET Successfully.....:: " + updCnt);
							}
							pstmtUpd.close();
							pstmtUpd = null;
						}*/
					} else {
						if (amountDecl != 0 || amountProof != 0) {
							if (tranIdNew == null || tranIdNew.trim().length() == 0 || tranIdNew.equals("*")) {
								tranIdNew = generateTranId(
										"w_emp_it_declaration", conn);
							}
							amountDeclOld = 0;
							amountProofOld = 0;

							System.out.println("tranIdNew ::" + tranIdNew);
							insertSql = "INSERT INTO EMP_IT_DECLARATION(TRAN_ID, TRAN_DATE, ACCT_PRD, "
									+ "EMP_CODE, AD_CODE, AMOUNT, STATUS, CHG_DATE, CHG_USER, CHG_TERM, "
									+ "AMOUNT_PROOF, AMOUNT_OLD, AMOUNT_PROOF_OLD, REMARK) "
									+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
							pstmtIns = conn.prepareStatement(insertSql);
							pstmtIns.setString(1, tranIdNew);
							pstmtIns.setTimestamp(2, new java.sql.Timestamp(
									System.currentTimeMillis()));
							pstmtIns.setString(3, acctPrd);
							pstmtIns.setString(4, empCode);
							pstmtIns.setString(5, adCode);
							pstmtIns.setDouble(6, amountDecl);
							pstmtIns.setString(7, empAdStatus);
							pstmtIns.setTimestamp(8, new java.sql.Timestamp(
									System.currentTimeMillis()));
							pstmtIns.setString(9, chgUser);
							pstmtIns.setString(10, chgTerm);
							pstmtIns.setDouble(11, amountProof);
							pstmtIns.setDouble(12, amountDeclOld);
							pstmtIns.setDouble(13, amountProofOld);
							pstmtIns.setString(14, remarks);
							insCnt = pstmtIns.executeUpdate();
							if (insCnt == 1) {
								System.out
										.println("Inserted Into EMP_IT_DECLARATION Successfully.....:: "
												+ insCnt);
							}
							pstmtIns.close();
							pstmtIns = null;
						}
					}
					rs1.close();
					rs1 = null;
					pstmt1.clearParameters();
				}
				pstmt1.close();
				pstmt1 = null;
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			if(errString.trim().length() > 0){
				conn.rollback();
			} else {
				updateSql = "update EMP_ITDECL_HDR set conf_date = sysdate where tran_id = ?";
				pstmtUpd = conn.prepareStatement(updateSql);
				pstmtUpd.setString(1, domID);
				int cnt = pstmtUpd.executeUpdate();

				if (cnt >= 1) {
					System.out.println("Updated CONFIRM_DATE into EMP_ITDECL_HDR Successfully.....:: " + cnt);
				}
				pstmtUpd.close();
				pstmtUpd = null;
				
			}
		} catch (SQLException se) {
			try {
				conn.rollback();
			} catch (Exception se1) {
			}
			System.out.println("Exception in EJB["
					+ this.getClass().getSimpleName() + "]:[" + se.getMessage()
					+ "]");
			se.printStackTrace();
			throw new ITMException(se);
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception e1) {
			}
			System.out.println("Exception in EJB["
					+ this.getClass().getSimpleName() + "]:[" + e.getMessage()
					+ "]");
			e.printStackTrace();
			throw new ITMException(e);
		} finally {
			try {
				if (rs1 != null) {
					rs1.close();
					rs1 = null;
				}
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt1 != null) {
					pstmt1.close();
					pstmt1 = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (pstmtUpd != null) {
					pstmtUpd.close();
					pstmtUpd = null;
				}
				if (pstmtIns != null) {
					pstmtIns.close();
					pstmtIns = null;
				}
			} catch (Exception e) {
				System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]::postSaveRec(D)::[" + e.getMessage()+"]");
			}
		}
		System.out.println("Returning from EJB["+this.getClass().getSimpleName()+"]::postSaveRec(S)::[" + errString+"]");
		return errString;
	}

	private String generateTranId(String windowName, Connection conn)
			throws ITMException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "";
		String tranId = "";
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues = "";
		String paySiteCode = "";
		String effectiveDate = "";

		java.sql.Date effDate = null;

		try {
			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString(1, windowName);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				keyString = rs.getString("KEY_STRING");
				keyCol = rs.getString("TRAN_ID_COL");
				tranSer = rs.getString("REF_SER");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("keyString :" + keyString);
			System.out.println("keyCol :" + keyCol);
			System.out.println("tranSer :" + tranSer);

			selSql = "SELECT PAY_SITE FROM EMPLOYEE WHERE EMP_CODE =  ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString(1, empCode);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				paySiteCode = rs.getString("PAY_SITE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			selSql = "SELECT FR_DATE FROM ACCTPRD WHERE CODE = ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString(1, acctPrd);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				effDate = rs.getDate("FR_DATE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			effectiveDate = genericUtility.getValidDateString(
					effDate.toString(), genericUtility.getDBDateFormat(),
					genericUtility.getApplDateFormat());
			xmlValues = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues + "<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + paySiteCode
					+ "</site_code>";
			xmlValues = xmlValues + "<tran_date>" + effectiveDate
					+ "</tran_date>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :[" + xmlValues + "]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE",
					CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
			System.out.println("tranId :" + tranId);
		} catch (SQLException ex) {
			System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]:[" + ex.getMessage()+"]");
			ex.printStackTrace();
			throw new ITMException(ex);
		} catch (Exception e) {
			System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]:[" + e.getMessage()+"]");
			e.printStackTrace();
			throw new ITMException(e);
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
			} catch (Exception e) {
				System.out.println("Exception in EJB["+this.getClass().getSimpleName()+"]:[" + e.getMessage()+"]");
			}
		}
		return tranId;
	}
	
	@Override
	public String preSave(String domString, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException {
		System.out.println("\npreSave [S] Created by Tajuddin Mahadi\ndomString: [" + domString + "]\neditFlag: [" + editFlag + "]\nxtraParams: [" + xtraParams + "]");
		String sql = "", errString = "", errCode = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Document dom = null;
		try {
			AdmCommon admCommon = new AdmCommon();
			String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			dom = genericUtility.parseString(domString);
			String tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom, "1"));
			System.out.println("preSave : : : tran_id ["+ tran_id+"]");
			int detailNodeLength = dom.getElementsByTagName("Detail2").getLength();
			if(tran_id.length() > 0) {
				System.out.println("Came in EDIT mode");
				String updateFlag = "";
				if(detailNodeLength <= 0) {
					errCode = "VTINVDET";
					errString = getErrorString("", errCode, userId);
					return errString;
				} else if(detailNodeLength > 0) {
					for (int cnt = 0; cnt < detailNodeLength; cnt++) {
						Node pNode = dom.getElementsByTagName("Detail2").item(cnt);
						Node cNode = null;
						String cNodeName = "";
						NodeList pNodeList = pNode.getChildNodes();
						for (int n = 0; n < pNodeList.getLength(); n++) {
							cNode = pNodeList.item(n);
							cNodeName = cNode.getNodeName();
				            cNodeName = cNodeName == null ? "" : cNodeName.trim();
				            if ("attribute".equalsIgnoreCase(cNodeName)) {
				            	updateFlag = cNode.getAttributes().getNamedItem("updateFlag").getNodeValue();
				                updateFlag = updateFlag == null ? "" : updateFlag.trim();
				                if ("D".equalsIgnoreCase(updateFlag)) {
				                	errCode = "VTCDELDET";
				    				errString = getErrorString("", errCode, userId);
				    				return errString;
				                }
				            }
						}
					}
				}
			} else {
				System.out.println("Cam in Add Mode");
				if(detailNodeLength == 0) {
					errCode = "VTINVDET";
					errString = getErrorString("", errCode, userId);
					return errString;
				} else {
					String pay_site = genericUtility.getColumnValue("pay_site", dom, "1");
					String cadre = genericUtility.getColumnValue("cadre", dom, "1");
					String grade = genericUtility.getColumnValue("grade", dom, "1");
					String admEnv = admCommon.getAdmEnv(pay_site, cadre, grade, "AD_CODE_DECL_TYPE", new Timestamp(Calendar.getInstance().getTimeInMillis()), conn);
					int sqlCount = 0;
					if("NULLFOUND".equalsIgnoreCase(admEnv)) {
						admEnv = admCommon.getEnv("999999", "AD_CODE_DECL_TYPE", conn);
					}
					
					
					
					if("A".equalsIgnoreCase(admEnv)) {
						sql = "select count(*) as count from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code where i.access_to = 'A' order by i.seq_no";
					} else if("E".equalsIgnoreCase(admEnv)) {
						sql = "select count(*) as count from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code where i.access_to is null order by i.seq_no";
					} else if("B".equalsIgnoreCase(admEnv)) {
						sql = "select count(*) as count from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code order by i.seq_no";
					}
					
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					
					if(rs.next()) {
						sqlCount = rs.getInt("count");
					}
					
					if(sqlCount != detailNodeLength) {
						System.out.println("Deleted some ad_code manually in ADD Mode: Count from sql:[" + sqlCount + "] from dom[" + detailNodeLength + "]");
						errCode = "VTCDELDET";
	    				errString = getErrorString("", errCode, userId);
	    				return errString;
					}
					
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new ITMException(e);
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}
}
