/*
Component   : process component
Auther		: Gulzar
Created On  : 21/09/11
*/

package ibase.webitm.ejb.wms;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.system.config.*;
import ibase.utility.CommonConstants;
//import ibase.webitm.ejb.dis.adv.InvHoldRelConf;
import ibase.webitm.ejb.dis.adv.InvHoldRelConf;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.Date;

import org.w3c.dom.*;
import javax.ejb.*;
import java.util.*;
import java.text.SimpleDateFormat;

@Stateless
public class NearExpiryPrc extends ProcessEJB implements NearExpiryPrcLocal,NearExpiryPrcRemote
{
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	/**
	* The public method is parsed the xmlString to Document object and call an overloded method
	* Returns message string if exists else returns null in XML format
	* @param xmlDataHdr contains the header form data in XML format
	* @param xmlDataAll contains the data of all the forms in XML format
	* @param windowName represents window name
	* @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	*/
	public String process(String xmlDataHdr, String xmlDataAll, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("NearExpiryPrc called.............!");
		Document hdrDom = null, allDom = null;
		String  retString = null;
		try
		{	
			if(xmlDataHdr != null && xmlDataHdr.trim().length() > 0)
			{
				System.out.println("XML String :"+xmlDataHdr);
				GenericUtility genericUtility = GenericUtility.getInstance();
				hdrDom = genericUtility.parseString(xmlDataHdr);				
			}
			if(xmlDataAll != null && xmlDataAll.trim().length() > 0)
			{
				GenericUtility genericUtility = GenericUtility.getInstance();
				allDom = genericUtility.parseString(xmlDataAll);				
			}
			retString = process(hdrDom,allDom,windowName,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception :NearExpiryPrc : process(String xmlString):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		System.out.println("returning from Process "+retString);
	    return retString;
	}

	/**
	* The public method contain business logic for process
	* Returns message string (success or failed) if exists else returns null in XML format
	* @param dom contains the header form data as a document object model
	* @param xmlString2 contains the data of all the forms as a document object model
	* @param windowName represents window name
	* @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	*/
	public String process(Document hdrDom,Document allDom,String windowName,String xtraParams) throws RemoteException,ITMException
	{
		String salesPerson = "";
		String itemCode = "";
		String retString = "";
		String selectSql = "";
		String locCode = "";
		String siteCode = "";
		String lotNo = "";
		String lotSl = "";
		String dataVal1 = "";
		String dataVal2 = "";
		String reservLoc = "";
		String lockORTransfer = "";
		String nexpLoc = "";
		String expLoc = "";
		String tranID = "";
		String loginSiteCode = "";
		String userId = "";
		String chgTerm = "";
		String acctCodeInv = "";
		String cctrCodeInv = "";
		String insertSql = "";
		String defReasCode = "";
		//Changed by sumit sarkar on 24/06/12 START
		String dStoreInvstat ="";
		String casePickLoc ="";
		String activePickLoc = "";
		String siteCodeFromDisPa = "";
		String forInvState = "";
		StringBuffer stringBuffer = new StringBuffer();
		int count1 = 0;
		//Changed by sumit sarkar on 24/06/12 END

		int count = 0;
		int updCnt = 0;
		int lineNo = 0;

		double quantity = 0d;
		double allocQty = 0d;
		double noArt = 0d;
		double minSelfLife = 0d;

		boolean isError = false;
		
		Connection conn = null;
		ResultSet rsStock = null;
		ResultSet rsItem = null;
		PreparedStatement pstmtStock = null;
		PreparedStatement pstmtItem = null;
		String holdStatus="",sql="";
		PreparedStatement pstmt=null;
		ResultSet rs =null;


		HashMap strAllocate = null;

		GenericUtility genericUtility = GenericUtility.getInstance();

		ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
		InvAllocTraceBean invAllocTrace = new InvAllocTraceBean();

		try
		{
			ConnDriver connDriver = new ConnDriver(); 
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			conn.setAutoCommit(false);
			
			DistCommon distComm = new DistCommon();
			
			//Changed By Pragyan as the veriable name RESERV_LOC  has been changed to RESERV_LOCATION
			//reservLoc = distComm.getDisparams("999999","RESERV_LOC",conn);
			//Changed by sumit sarkar on 04/07/12 commenting, because of no use.
			//reservLoc = distComm.getDisparams("999999","RESERV_LOCATION",conn);
			
			lockORTransfer = distComm.getDisparams("999999","LOCK_OR_TRANSFER",conn);
			//Changed by sumit sarkar on 24/06/12 uncomment below code and change var_name in parameter. start.
			//nexpLoc = distComm.getDisparams("999999","NEAREXP_LOC",conn);
			//expLoc = distComm.getDisparams("999999","EXP_LOC",conn);
			//casePickLoc  = distComm.getDisparams("999999","CASE_PICK_INVSTAT",conn);
			//activePickLoc  = distComm.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
			nexpLoc = distComm.getDisparams("999999","NEAR_EXP_LOCK",conn);
			expLoc = distComm.getDisparams("999999","EXP_LOCK",conn);
			//dStoreInvstat = distComm.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
			siteCodeFromDisPa = distComm.getDisparams("999999","FOR_LOGIN_SITE",conn);
			forInvState = checkNull(distComm.getDisparams("999999","FOR_INV_STAT",conn));
			System.out.println("nexpLoc ->["+nexpLoc+"] expLoc ->["+expLoc+"] ");
			System.out.println(" for inv_stat -> "+forInvState);
			//Changed by sumit sarkar on 24/06/12 uncomment below code and change var_name in parameter. start.

			dataVal1 = genericUtility.getColumnValue("lock_code_exp",hdrDom);
			dataVal2 = genericUtility.getColumnValue("lock_code_nexp",hdrDom);
			siteCode = genericUtility.getColumnValue("site_code",hdrDom);
			
			//Changed by sumit sarkar on 21/06/12 insert CHECK_PHYSCAN_VALUE function in sql start.
			/*selectSql = "SELECT A.ITEM_CODE, A.SITE_CODE, A.LOC_CODE, A.LOT_NO, A.LOT_SL, A.NO_ART, " +
						"C.ITEM_SER, A.QUANTITY, A.UNIT, A.GRADE, A.EXP_DATE, A.LTRAN_DATE,"+
						"A.REMARKS, D.INV_STAT, A.PACK_CODE, A.ALLOC_QTY, A.MFG_DATE," +
						"A.SITE_CODE__MFG, A.POTENCY_PERC, A.RATE, A.GROSS_RATE, A.RETEST_DATE,"+
						"A.CONV__QTY_STDUOM, A.UNIT__ALT, A.BATCH_NO, A.ACCT_CODE__INV,A.CCTR_CODE__INV "+
						"FROM STOCK A, INVSTAT B, ITEM C, LOCATION D "+
						"WHERE A.LOC_CODE = D.LOC_CODE AND D.INV_STAT = B.INV_STAT "+
						"AND A.ITEM_CODE = C.ITEM_CODE AND B.AVAILABLE = 'Y' "+
						"AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' " +
						//"AND (A.QUANTITY - A.ALLOC_QTY - CASE WHEN A.HOLD_QTY IS NULL THEN 0 ELSE A.HOLD_QTY END) > 0 "+ //Commented by gulzar on 1/12/2012
						"AND (CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END) > 0 "+//Changed by gulzar on 1/12/2012
						"AND D.INV_STAT = ? AND A.SITE_CODE = ? AND A.EXP_DATE IS NOT NULL ";*/
			
			stringBuffer.append("(");
			if(forInvState == null || "".equalsIgnoreCase(forInvState.trim()))
			{				
				stringBuffer.append("''");
			}
			StringTokenizer st3 = new StringTokenizer(forInvState, ",");
			
			while (st3.hasMoreElements()) 
			{
				stringBuffer.append("'").append(st3.nextElement()).append("'");				
				if(st3.hasMoreElements())
				{
					stringBuffer.append(",");
				}
			}
			stringBuffer.append(")");
			
			System.out.println("Created input string --> "+stringBuffer);
		
			
			//SQL For expiry process 
			System.out.println(" Calling expiry process *******************************");
			selectSql = "SELECT A.ITEM_CODE, A.SITE_CODE, A.LOC_CODE, A.LOT_NO, A.LOT_SL, A.NO_ART, " +
						"C.ITEM_SER, A.QUANTITY, A.UNIT, A.GRADE, A.EXP_DATE, A.LTRAN_DATE,"+
						"A.REMARKS, D.INV_STAT, A.PACK_CODE, A.ALLOC_QTY, A.MFG_DATE," +
						"A.SITE_CODE__MFG, A.POTENCY_PERC, A.RATE, A.GROSS_RATE, A.RETEST_DATE,"+
						"A.CONV__QTY_STDUOM, A.UNIT__ALT, A.BATCH_NO, A.ACCT_CODE__INV,A.CCTR_CODE__INV "+
						"FROM STOCK A, INVSTAT B, ITEM C, LOCATION D "+
						"WHERE A.LOC_CODE = D.LOC_CODE AND D.INV_STAT = B.INV_STAT "+
						"AND A.ITEM_CODE = C.ITEM_CODE AND B.AVAILABLE = 'Y' "+
						"AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' " +
						//"AND (A.QUANTITY - A.ALLOC_QTY - CASE WHEN A.HOLD_QTY IS NULL THEN 0 ELSE A.HOLD_QTY END) > 0 "+ //Commented by gulzar on 1/12/2012
						"AND (CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END) > 0 "+//Changed by gulzar on 1/12/2012
						//Changed by sumit sarkar on 24/06/12 putting condition of dStoreInvstat (DSO, pso, active pick, case pick)
						//"AND D.INV_STAT = ? AND A.EXP_DATE IS NOT NULL "+
						" AND D.INV_STAT IN "+stringBuffer.toString()+" AND A.EXP_DATE IS NOT NULL "+
						" AND A.EXP_DATE IS NOT NULL "+
						//Changed by sumit sarkar on 03/07/12 
						" AND nvl(CHECK_PHYSCAN_VALUE(A.ITEM_CODE, A.SITE_CODE, A.LOC_CODE, A.LOT_NO, A.LOT_SL, ? , ?),0) <> 1 " +
						" AND A.EXP_DATE <= SYSDATE ";
			
			if( "YES".equalsIgnoreCase(siteCodeFromDisPa))
			{
				//taking site as a login site code 
				selectSql = selectSql + " AND A.SITE_CODE =  '"+siteCode+"'";
			}
			
				
			System.out.println(" selectSql ["+selectSql+"]");
			
			//Changed by sumit sarkar on 21/06/12 insert CHECK_PHYSCAN_VALUE function in sql end.
			
			pstmtStock = conn.prepareStatement(selectSql);
			//Changed by sumit sarkar on 22/06/12 to comment bellow parameter and add nexpLoc, expLoc parameter start.
			//pstmtStock.setString(1, reservLoc);
			//pstmtStock.setString(2, siteCode);
			/*pstmtStock.setString(2, dStoreInvstat);
			pstmtStock.setString(3, casePickLoc);
			pstmtStock.setString(4, activePickLoc);	*/		
			pstmtStock.setString(1, expLoc);
//	shamim 	pstmtStock.setString(2, nexpLoc);
			pstmtStock.setString(2, expLoc);
			//Changed by sumit sarkar on 22/06/12 to comment bellow parameter and add nexpLoc, expLoc parameter end.
			rsStock = pstmtStock.executeQuery();

			InvHoldGen holdGen = new InvHoldGen();
			ArrayList stockExpList = new ArrayList();
			ArrayList stockNexpList = new ArrayList();
			ArrayList lockRelList = new ArrayList();
			java.sql.Timestamp currDate = new java.sql.Timestamp( System.currentTimeMillis() );
			java.sql.Timestamp expDateCalc = null;
			java.sql.Timestamp expDateStock = null;

			selectSql = "SELECT MIN_SHELF_LIFE FROM ITEM WHERE ITEM_CODE = ? ";
			pstmtItem = conn.prepareStatement(selectSql);

			while (rsStock.next())
			{
				HashMap dataMap = new HashMap();
				itemCode = rsStock.getString("ITEM_CODE");
				siteCode = rsStock.getString("SITE_CODE");
				locCode = rsStock.getString("LOC_CODE");
				lotNo = rsStock.getString("LOT_NO");
				lotSl = rsStock.getString("LOT_SL");
				expDateStock = rsStock.getTimestamp("EXP_DATE");
				quantity = rsStock.getDouble("QUANTITY");
				allocQty = rsStock.getDouble("ALLOC_QTY");
				noArt = rsStock.getDouble("NO_ART");
				acctCodeInv = rsStock.getString("ACCT_CODE__INV");
				cctrCodeInv = rsStock.getString("CCTR_CODE__INV");
				
				/*if ( currDate.compareTo(expDateStock) >= 0 )//Check for Expired stock
				{
					count++;
					dataMap.put( "item_code", itemCode );
					dataMap.put( "site_code", siteCode );
					dataMap.put( "loc_code", locCode );
					dataMap.put( "lot_no", lotNo );
					dataMap.put( "lot_sl", lotSl );
					dataMap.put( "loc_code__to", dataVal1 );//expired location to which stock will be transfer
					dataMap.put( "quantity", ""+quantity );
					dataMap.put( "alloc_qty", ""+allocQty );
					dataMap.put( "no_art", ""+noArt );
					dataMap.put( "acct_code__inv", acctCodeInv );
					dataMap.put( "cctr_code__inv", cctrCodeInv );
					stockExpList.add(dataMap);
				}
				else//Check for Near Expiry stock
				{
					pstmtItem.setString( 1, itemCode );
					rsItem = pstmtItem.executeQuery();
					if ( rsItem.next() )
					{
						minSelfLife = rsItem.getDouble("MIN_SHELF_LIFE");
					}
					pstmtItem.clearParameters();
					if ( minSelfLife == 0 )
					{
						continue;
					}
					expDateCalc = distComm.CalcExpiry( currDate, minSelfLife );
					
					if ( expDateCalc.compareTo(expDateStock) >= 0 )
					{
						count++;
						dataMap.put( "item_code", itemCode );
						dataMap.put( "site_code", siteCode );
						dataMap.put( "loc_code", locCode );
						dataMap.put( "lot_no", lotNo );
						dataMap.put( "lot_sl", lotSl );
						dataMap.put( "loc_code__to", dataVal2 );//near expiry location to which stock will be transfer
						dataMap.put( "quantity", ""+quantity );
						dataMap.put( "alloc_qty", ""+allocQty );
						dataMap.put( "no_art", ""+noArt );
						dataMap.put( "acct_code__inv", acctCodeInv );
						dataMap.put( "cctr_code__inv", cctrCodeInv );
						stockNexpList.add(dataMap);
						System.out.println("**********************"+stockNexpList);
					}
				}*/
				
				count++;
				dataMap.put( "item_code", itemCode );
				dataMap.put( "site_code", siteCode );
				dataMap.put( "loc_code", locCode );
				dataMap.put( "lot_no", lotNo );
				dataMap.put( "lot_sl", lotSl );
				dataMap.put( "loc_code__to", dataVal1 );//expired location to which stock will be transfer
				dataMap.put( "quantity", ""+quantity );
				dataMap.put( "alloc_qty", ""+allocQty );
				dataMap.put( "no_art", ""+noArt );
				dataMap.put( "acct_code__inv", acctCodeInv );
				dataMap.put( "cctr_code__inv", cctrCodeInv );
				stockExpList.add(dataMap);
				System.out.println("stockExpList**********************"+stockExpList);
				//check for  lock 
				System.out.println("..............check for lock..................");
				sql ="select D.HOLD_STATUS ,D.tran_id ,D.line_no from INV_HOLD H, INV_HOLD_DET D where H.tran_id= D.tran_id and H.lock_code =? and D.ITEM_CODE  =? and D.SITE_CODE= ? and D.LOC_CODE=?  and D.LOT_NO= ? "
					+"	and D.LOT_SL =? ";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1, nexpLoc);
				pstmt.setString(2, itemCode);
				pstmt.setString(3, siteCode);
				pstmt.setString(4, locCode);
				pstmt.setString(5, lotNo);
				pstmt.setString(6, lotSl);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					holdStatus=rs.getString(1);
					if("H".equalsIgnoreCase(holdStatus))
					{
						HashMap lockRelMap = new HashMap();
						lockRelMap.put("tran_id", rs.getString("tran_id"));
						lockRelMap.put("line_no", rs.getString("line_no"));
						lockRelList.add(lockRelMap);
						System.out.println("lockRelList**********************"+lockRelList);
					}
				}
				pstmt.close();
				pstmt=null;
				rs.close();
				rs=null;
				
				
				//Changed by sumit sarkar
			}
			if ( rsStock != null)
			{
				rsStock.close();
				rsStock = null;
			}
			if ( pstmtStock != null )
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			
			
			//Changed by sumit sarkar on 03/06/12  SQL For near expiry process start.
			System.out.println(" Calling near expiry *******************************");
			selectSql = "";
			selectSql = "SELECT A.ITEM_CODE, A.SITE_CODE, A.LOC_CODE, A.LOT_NO, A.LOT_SL, A.NO_ART, " +
						"C.ITEM_SER, A.QUANTITY, A.UNIT, A.GRADE, A.EXP_DATE, A.LTRAN_DATE,"+
						"A.REMARKS, D.INV_STAT, A.PACK_CODE, A.ALLOC_QTY, A.MFG_DATE," +
						"A.SITE_CODE__MFG, A.POTENCY_PERC, A.RATE, A.GROSS_RATE, A.RETEST_DATE,"+
						"A.CONV__QTY_STDUOM, A.UNIT__ALT, A.BATCH_NO, A.ACCT_CODE__INV,A.CCTR_CODE__INV "+
						"FROM STOCK A, INVSTAT B, ITEM C, LOCATION D "+
						"WHERE A.LOC_CODE = D.LOC_CODE AND D.INV_STAT = B.INV_STAT "+
						"AND A.ITEM_CODE = C.ITEM_CODE AND B.AVAILABLE = 'Y' "+
						"AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' " +
						//"AND (A.QUANTITY - A.ALLOC_QTY - CASE WHEN A.HOLD_QTY IS NULL THEN 0 ELSE A.HOLD_QTY END) > 0 "+ //Commented by gulzar on 1/12/2012
						"AND (CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END) > 0 "+//Changed by gulzar on 1/12/2012
						//Changed by sumit sarkar on 24/06/12 putting condition of dStoreInvstat (DSO, pso, active pick, case pick)
						//"AND D.INV_STAT = ? AND A.EXP_DATE IS NOT NULL "+
						" AND D.INV_STAT IN "+stringBuffer.toString()+" AND A.EXP_DATE IS NOT NULL AND A.EXP_DATE > SYSDATE"+
						//Changed by sumit sarkar on 03/07/12  start
						" AND nvl(CHECK_PHYSCAN_VALUE(A.ITEM_CODE, A.SITE_CODE, A.LOC_CODE, A.LOT_NO, A.LOT_SL, ? , ?),0) <> 1 " +
						" AND A.EXP_DATE <= ADD_MONTHS(SYSDATE,C.MIN_SHELF_LIFE) ";
			if( "YES".equalsIgnoreCase(siteCodeFromDisPa))
			{
				//taking site as a login site code 
				selectSql = selectSql + " AND A.SITE_CODE =  '"+siteCode+"'";
			}
			// otherwise for all site code.
			System.out.println(" selectSql ["+selectSql+"]");
			
			pstmtStock = conn.prepareStatement(selectSql);
			/*pstmtStock.setString(1, reservLoc);			
			pstmtStock.setString(2, dStoreInvstat);
			pstmtStock.setString(3, casePickLoc);
			pstmtStock.setString(4, activePickLoc);*/			
//shamim		pstmtStock.setString(1, expLoc);
			pstmtStock.setString(1, nexpLoc);
			pstmtStock.setString(2, nexpLoc);			
			rsStock = pstmtStock.executeQuery();
			
			while (rsStock.next())
			{
				HashMap dataMap = new HashMap();
				itemCode = rsStock.getString("ITEM_CODE");
				siteCode = rsStock.getString("SITE_CODE");
				locCode = rsStock.getString("LOC_CODE");
				lotNo = rsStock.getString("LOT_NO");
				lotSl = rsStock.getString("LOT_SL");
				expDateStock = rsStock.getTimestamp("EXP_DATE");
				quantity = rsStock.getDouble("QUANTITY");
				allocQty = rsStock.getDouble("ALLOC_QTY");
				noArt = rsStock.getDouble("NO_ART");
				acctCodeInv = rsStock.getString("ACCT_CODE__INV");
				cctrCodeInv = rsStock.getString("CCTR_CODE__INV");
				
				count1++;
				dataMap.put( "item_code", itemCode );
				dataMap.put( "site_code", siteCode );
				dataMap.put( "loc_code", locCode );
				dataMap.put( "lot_no", lotNo );
				dataMap.put( "lot_sl", lotSl );
				dataMap.put( "loc_code__to", dataVal2 );//near expiry location to which stock will be transfer
				dataMap.put( "quantity", ""+quantity );
				dataMap.put( "alloc_qty", ""+allocQty );
				dataMap.put( "no_art", ""+noArt );
				dataMap.put( "acct_code__inv", acctCodeInv );
				dataMap.put( "cctr_code__inv", cctrCodeInv );
				stockNexpList.add(dataMap);
				
				
				
				System.out.println("stockNexpList **********************"+stockNexpList);
			}
			if ( rsStock != null)
			{
				rsStock.close();
				rsStock = null;
			}
			if ( pstmtStock != null )
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			
			
			
			//Changed by sumit sarkar on 03/06/12  SQL For near expiry process end.
			
			System.out.println("count = ["+count+"] count1 = ["+count1+"]");
			if ( !isError  )
			{
				System.out.println(" lockORTransfer = ["+lockORTransfer.trim()+"]");
				siteCode = genericUtility.getColumnValue("site_code",hdrDom);
				if ( "L".equalsIgnoreCase(lockORTransfer.trim()) ) //For Locking
				{
					//calling for Expiry lock
					System.out.println(" in side lockORTransfer for count > 0  ");
					System.out.println(" stockExpList.size() -> ["+stockExpList.size()+"] and count -> ["+count+"]");
					if ( stockExpList.size() > 0 && count > 0)
					{
						//changes by shamim start 
						//as per discussion with manoharan Sir :- genrate inv-Release transaction and confirm it
						if(lockRelList.size() >0)
						{
							System.out.println("going to insert in inv_hold__Rel ");
							retString=genInvRelTrans(lockRelList, xtraParams, conn);
							System.out.println("retString" +retString);
							
						}
						if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
						{
							isError = true;
						}
						System.out.println("going to insert in inv_hold EXPIRED");
		
						retString = holdGen.generateHoldTrans( dataVal1, "EXPIRED","EXP", siteCode, stockExpList, xtraParams, conn );
					}
					if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
					{
						isError = true;
					}
					/*else 
					{
						//calling for Near Expiry lock
						if ( stockNexpList.size() > 0 )
						{
							retString = holdGen.generateHoldTrans( dataVal2, "NEAREXPIRY","NEXP", siteCode, stockNexpList, xtraParams, conn );
						}
						if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
						{
							isError = true;
						}
					}*/				
				
					System.out.println("in count1 > 0 if loop");
					System.out.println("stockNexpList.size() ["+stockNexpList.size()+"] and count1 -> ["+count1+"]");
					if ( stockNexpList.size() > 0 && count1 > 0 )
					{
						System.out.println("going to insert in inv_hold for NEAREXPIRY ");
						retString = holdGen.generateHoldTrans( dataVal2, "NEAREXPIRY","NEXP", siteCode, stockNexpList, xtraParams, conn );
					}
					if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
					{
						isError = true;
					}
									
				}
				if ( "T".equalsIgnoreCase(lockORTransfer.trim()) ) //For Transfer
				{
					if ( stockExpList.size() > 0 && count > 0 )
					{
						retString = inventoryTransfer( stockExpList, "w_stock_transfer", xtraParams, conn );
					}
					if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
					{
						isError = true;
						//return retString;
					}
					if ( stockNexpList.size() > 0 && count1 > 0)
					{
						retString = inventoryTransfer( stockNexpList, "w_stock_transfer", xtraParams, conn );
					}
					if ( retString != null && retString.trim().length() > 0 && retString.trim().equalsIgnoreCase("ERROR") )
					{
						isError = true;
						//return retString;
					}
				}
			}
		}
		catch(SQLException se)
		{
			isError = true;
			System.out.println("Exception : NearExpiryPrc : process()" +se.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			isError = true;
			System.out.println("Exception :NearExpiryPrc :process():"+e.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				invAllocTrace = null;
				//Changed by sumit on 05/07/12 change the condition.
				//if ( count == 0 )
				if ( count == 0 && count1 == 0)
				{
					retString = itmDBAccess.getErrorString("","NODATAERR","");
				}
				else if ( !isError )
				{
					System.out.println("COMMITING the changes......");
					conn.commit();
					retString = itmDBAccess.getErrorString("","PRCSUCCESS","");
				}
				else
				{
					System.out.println("ROLLBACK the changes......");
					conn.rollback();
					retString = itmDBAccess.getErrorString("","PRCFAILED","");
				}
				System.out.println("Closing Database Connection......");
				if (rsItem != null)
				{
					rsItem.close();
					rsItem = null;
				}
				if (pstmtItem != null)
				{
					pstmtItem.close();
					pstmtItem = null;
				}
				if (rsStock != null)
				{
					rsStock.close();
					rsStock = null;
				}
				if (pstmtStock != null)
				{
					pstmtStock.close();
					pstmtStock = null;
				}
				if ( conn != null && !conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}catch(Exception se){}
		}
		System.out.println("retString........:: " + retString);
		return retString;  	
	}
	public String inventoryTransfer( ArrayList stockList, String windowName,String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		String salesPerson = "";
		String itemCode = "";
		String retString = "";
		String selectSql = "";
		String locCode = "";
		String siteCode = "";
		String lotNo = "";
		String lotSl = "";
		String locCodeTo = "";
		String reservLoc = "";
		String nexpLoc = "";
		String expLoc = "";
		String tranID = "";
		String loginSiteCode = "";
		String userId = "";
		String chgTerm = "";
		String acctCodeInv = "";
		String cctrCodeInv = "";
		String insertSql = "";
		String defReasCode = "";

		int count = 0;
		int updCnt = 0;
		int lineNo = 0;

		double quantity = 0d;
		double allocQty = 0d;
		double noArt = 0d;
		double minSelfLife = 0d;

		boolean isError = false;
		
		ResultSet rsStock = null;
		ResultSet rsItem = null;
		PreparedStatement pstmtStock = null;
		PreparedStatement pstmtItem = null;
		PreparedStatement pstmtHdr = null;
		PreparedStatement pstmtDet = null;

		HashMap strAllocate = null;

		GenericUtility genericUtility = GenericUtility.getInstance();

		ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
		InvAllocTraceBean invAllocTrace = new InvAllocTraceBean();

		try
		{
			DistCommon distComm = new DistCommon();
			defReasCode = distComm.getDisparams("999999","DEFAULT_REAS_CODE",conn);

			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginSiteCode" );
			userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );

			java.sql.Timestamp currDate = new java.sql.Timestamp( System.currentTimeMillis() );
			java.sql.Timestamp expDateCalc = null;
			java.sql.Timestamp expDateStock = null;

			insertSql = "INSERT INTO STOCK_TRANSFER(TRAN_ID, TRAN_DATE, SITE_CODE, REF_SER__FOR, CONFIRMED, CHG_DATE, CHG_TERM, CHG_USER, SITE_CODE__FR, SITE_CODE__TO, REAS_CODE) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
			pstmtHdr = conn.prepareStatement(insertSql);

			insertSql = "INSERT INTO STOCK_TRANSFER_DET(TRAN_ID, LINE_NO, ITEM_CODE, QUANTITY, LOC_CODE__FR, LOC_CODE__TO, LOT_NO__FR, LOT_NO__TO, LOT_SL__FR, LOT_SL__TO, ACCT_CODE__CR, ACCT_CODE__DR, CCTR_CODE__DR, CCTR_CODE__CR, NO_ART) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			pstmtDet = conn.prepareStatement(insertSql);
			
			//generate the tran id for w_stock_transfer
			tranID = generateTranId( "w_stock_transfer", conn );
			
			//Insert into header table i.e stock_transfer
			pstmtHdr.setString( 1, tranID );
			pstmtHdr.setTimestamp( 2, currDate );
			pstmtHdr.setString( 3, loginSiteCode );
			pstmtHdr.setString( 4, "XFRX" );
			pstmtHdr.setString( 5, "N" );
			pstmtHdr.setTimestamp( 6, currDate );
			pstmtHdr.setString( 7, chgTerm );
			pstmtHdr.setString( 8, userId );
			pstmtHdr.setString( 9, siteCode );
			pstmtHdr.setString( 10, siteCode );
			pstmtHdr.setString( 11, defReasCode );
			updCnt = pstmtHdr.executeUpdate();
			pstmtHdr.close();
			pstmtHdr = null;

			for ( int ctr = 0; ctr < stockList.size(); ctr++ )
			{
				lineNo++;
				HashMap dataMap = null;
				dataMap = (HashMap)stockList.get(ctr);
				
				itemCode = "";
				siteCode = "";
				locCode = "";
				lotNo = "";
				lotSl = "";
				acctCodeInv = "";
				cctrCodeInv = "";
				locCodeTo = "";

				quantity = 0d;
				allocQty = 0d;
				noArt = 0d;
				
				if ( dataMap.get("item_code") != null )
				{
					itemCode = (String)dataMap.get("item_code");
				}
				if ( dataMap.get("site_code") != null )
				{
					siteCode = (String)dataMap.get("site_code");
				}
				if ( dataMap.get("loc_code") != null )
				{
					locCode = (String)dataMap.get("loc_code");
				}
				if ( dataMap.get("loc_code__to") != null )
				{
					locCodeTo = (String)dataMap.get("loc_code__to");
				}
				if ( dataMap.get("lot_no") != null )
				{
					lotNo = (String)dataMap.get("lot_no");
				}
				if ( dataMap.get("lot_sl") != null )
				{
					lotSl = (String)dataMap.get("lot_sl");
				}
				if ( dataMap.get("quantity") != null )
				{
					quantity = Double.parseDouble(dataMap.get("quantity").toString());
				}
				if ( dataMap.get("alloc_qty") != null )
				{
					allocQty = Double.parseDouble(dataMap.get("alloc_qty").toString());
				}
				if ( dataMap.get("no_art") != null )
				{
					noArt = Double.parseDouble(dataMap.get("no_art").toString());
				}
				if ( dataMap.get("acct_code__inv") != null )
				{
					acctCodeInv = (String)dataMap.get("acct_code__inv");
				}
				if ( dataMap.get("cctr_code__inv") != null )
				{
					cctrCodeInv = (String)dataMap.get("cctr_code__inv");
				}
				pstmtDet.setString( 1, tranID );
				pstmtDet.setInt( 2, lineNo );
				pstmtDet.setString( 3, itemCode );
				pstmtDet.setDouble( 4, (quantity - allocQty) );
				pstmtDet.setString( 5, locCode );
				pstmtDet.setString( 6, locCodeTo );//expired / Near Expiry location to which stock will be transfer
				pstmtDet.setString( 7, lotNo );
				pstmtDet.setString( 8, lotNo );
				pstmtDet.setString( 9, lotSl );
				pstmtDet.setString( 10, lotSl );
				pstmtDet.setString( 11, acctCodeInv );
				pstmtDet.setString( 12, acctCodeInv );
				pstmtDet.setString( 13, cctrCodeInv );
				pstmtDet.setString( 14, cctrCodeInv );
				pstmtDet.setDouble( 15, noArt );

				pstmtDet.addBatch();
				pstmtDet.clearParameters();
				dataMap.clear();

				strAllocate = new HashMap();

				strAllocate.put("tran_date",currDate);
				strAllocate.put("ref_ser","XFRX");
				strAllocate.put("ref_id",tranID);
				strAllocate.put("ref_line", "" + lineNo);
				strAllocate.put("site_code",siteCode);
				strAllocate.put("item_code",itemCode);
				strAllocate.put("loc_code",locCode);
				strAllocate.put("lot_no",lotNo);
				strAllocate.put("lot_sl",lotSl);
				strAllocate.put("alloc_qty",new Double(quantity));
				strAllocate.put("chg_user",userId);
				strAllocate.put("chg_term",chgTerm);
				strAllocate.put("chg_win","w_stock_transfer");

				retString = invAllocTrace.updateInvallocTrace(strAllocate, conn);
				strAllocate = null;
				System.out.println("retString ::: " + retString);
				if (retString != null && retString.trim().length() > 0 )
				{
					isError = true;
					retString = "ERROR";
					return retString;
				}
			}
			pstmtDet.executeBatch();
			pstmtDet.clearBatch();
		}
		catch(BatchUpdateException buex)
        {
			isError = true;
			retString = "ERROR";
			int [] updateCounts = buex.getUpdateCounts();
			for (int i = 0; i < updateCounts.length; i++)
			{
				System.err.println("  Statement " + i + ":" + updateCounts[i]);
			}
			System.err.println(" Message: " + buex.getMessage());
			System.err.println(" SQLSTATE: " + buex.getSQLState());
			System.err.println(" Error code: " + buex.getErrorCode());
			SQLException ex = buex.getNextException();
			while (ex != null)
			{ 
				System.err.println("SQL exception:");
				System.err.println(" Message: " + ex.getMessage());
				System.err.println(" SQLSTATE: " + ex.getSQLState());
				System.err.println(" Error code: " + ex.getErrorCode());
				ex = ex.getNextException();
			}
        }
		catch(SQLException se)
		{
			isError = true;
			retString = "ERROR";
			System.out.println("Exception : NearExpiryPrc : process()" +se.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			//throw new ITMException(se);
		}
		catch(Exception e)
		{
			isError = true;
			retString = "ERROR";
			System.out.println("Exception :NearExpiryPrc :process():"+e.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			//throw new ITMException(e);
		}
		finally
		{
			try
			{
				invAllocTrace = null;
				strAllocate = null;
				if ( isError )
				{
					System.out.println("ROLLBACK the changes......");
					conn.rollback();
					retString = "ERROR";
				}
				System.out.println("Closing Database Connection......");
				if (rsItem != null)
				{
					rsItem.close();
					rsItem = null;
				}
				if (pstmtItem != null)
				{
					pstmtItem.close();
					pstmtItem = null;
				}
				if (rsStock != null)
				{
					rsStock.close();
					rsStock = null;
				}
				if (pstmtStock != null)
				{
					pstmtStock.close();
					pstmtStock = null;
				}
				if (pstmtHdr != null)
				{
					pstmtHdr.close();
					pstmtHdr = null;
				}
				if (pstmtDet != null)
				{
					pstmtDet.close();
					pstmtDet = null;
				}

			}catch(Exception se){}
		}
		System.out.println("retString........:: " + retString);
		return retString;  	
	}
	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 = ? ";
				//System.out.println("selSql :"+selSql);
			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);

			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +        "<tran_id></tran_id>";
			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 ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + 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){}
		}
        return tranId;
     }//generateTranTd()
	
	private String checkNull(String str)
	{
		if(str == null)
		{
			str = "";
		}
		
		return str;
	}
	private String  genInvRelTrans(ArrayList nexpLoc,String xtraParams ,Connection conn) throws ITMException
	{
//		String invHoldRelSql="",invHoldRelDetSql="";
//		PreparedStatement pRelHdr=null ,pRelDet=null;
//		java.sql.Timestamp currDate =null;
//		Date date =null;
//		String userId="";
//		GenericUtility genericUtility =GenericUtility.getInstance(); 
		String tranIdRel = "";
		String lineNoRel = "";
		String itemCode = "";
		String lotNo = "";
		String sql = "";
		String invHoldRelSql = "";
		String invHoldRelDetSql = "";
		String siteCode = "";
		String confirmed = "";
		String empCode = "";
		String remark = "";
		String itemCodeDet = "";
		String lotNoDet = "";
		int lineNo = 0;
		String tranIdGenerate = "";
		String errString="";

		boolean flag = false;

		int count = 0;
		int updCnt = 0;
//		int ctr = 0;

		java.sql.Timestamp chgDate = null,currDate = null;
		Date date = null;
		String chgTerm = "";
		String userId = "";
		String lotStatus = "";
		int []batchUpd =null;

		Document dom = null;

		PreparedStatement pStmt = null;
		PreparedStatement pRelHdr = null;
		PreparedStatement pRelDet = null;
		ResultSet rs = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessLocal = new ITMDBAccessEJB();
		
		try
		{
			invHoldRelSql = "INSERT INTO INV_HOLD_REL(TRAN_ID, TRAN_DATE, SITE_CODE, REMARKS, CONFIRMED, EMP_CODE__APRV,CHG_USER ,CHG_DATE, CHG_TERM) VALUES(?,?,?,?,?,?,?,?,?)";
			pRelHdr = conn.prepareStatement(invHoldRelSql);
			invHoldRelDetSql = "INSERT INTO INV_HOLD_REL_DET(TRAN_ID, LINE_NO, TRAN_ID__HOLD, LINE_NO__HOLD, REMARKS) VALUES(?,?,?,?,?)";
			pRelDet = conn.prepareStatement(invHoldRelDetSql);

			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );
			siteCode =  genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			confirmed = "N";
			empCode = "";

			SimpleDateFormat sdfAppl = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String currDateStr = sdfAppl.format(currDate);

			tranIdGenerate = generateTranId( "w_inv_hold_rel", siteCode, currDateStr, conn );

			pRelHdr.setString( 1, tranIdGenerate );
			pRelHdr.setTimestamp( 2, currDate );
			pRelHdr.setString( 3, siteCode );
			pRelHdr.setString( 4, " " );
			pRelHdr.setString( 5, confirmed );
			pRelHdr.setString( 6, empCode );
			pRelHdr.setString( 7, userId );
			pRelHdr.setTimestamp( 8, currDate );
			pRelHdr.setString( 9, chgTerm );

			updCnt = pRelHdr.executeUpdate();
			pRelHdr.clearParameters();
			if( updCnt > 0 )
			{					
				System.out.println( updCnt + " rows updated successfully FOR "+tranIdGenerate );
			}
			//making details
			HashMap dataMap = new HashMap();

			for ( int ctr = 0; ctr < nexpLoc.size(); ctr++ )
			{
				lineNo++;
				dataMap = (HashMap)nexpLoc.get(ctr);
				
				
				pRelDet.setString( 1, tranIdGenerate );
				pRelDet.setInt( 2,lineNo);
				pRelDet.setString( 3, (String)dataMap.get("tran_id"));
				pRelDet.setString( 4, (String)dataMap.get("line_no") );
				pRelDet.setString( 5, remark );
				pRelDet.addBatch();

				dataMap.clear(); 
			}
			batchUpd = pRelDet.executeBatch();
			System.out.println("nos of row updated "+batchUpd);
//			if(batchUpd.length >0)
//				conn.commit();
			InvHoldRelConf invHoldRelConf = new InvHoldRelConf();
			errString = invHoldRelConf.confirm( tranIdGenerate, xtraParams, "",conn,false);
			if (errString.indexOf("VTCNFSUCC") > -1)
			{
				errString = "";
			}
			
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}
	private String generateTranId( String windowName, String siteCode, String tranDateStr, 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 = ? ";
			//System.out.println("selSql :"+selSql);
			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);

			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +		"<tran_id></tran_id>";
			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues +		"<tran_date>" + tranDateStr + "</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 ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + 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)
			{

			}
		}
		return tranId;
	}//generateTranTd()
	//checkLock
//	private String checkLock(String itmCode, String siteCode ,String lockCode , String lotNo, String lotSl,Connection conn)throws ITMException
//	{
//		String holdStatus="",sql="";
//		PreparedStatement pstmt=null;
//		ResultSet rs =null;
//		try{
//			sql ="select HOLD_STATUS from INV_HOLD_DET where ITEM_CODE  =? and SITE_CODE= ? and LOC_CODE=?  and LOT_NO= ?"
//					+" and LOT_SL =? ";
//			pstmt=conn.prepareStatement(sql);
//			pstmt.setString(1, itmCode);
//			pstmt.setString(2, siteCode);
//			pstmt.setString(3, lockCode);
//			pstmt.setString(4, lotNo);
//			pstmt.setString(5, lotSl);
//			if(rs.next())
//			{
//				holdStatus=rs.getString(1);
//			}
//			
//			
//		}catch(Exception e)
//		{
//			e.printStackTrace();
//			throw new ITMException(e);
//		}
//		
//		return holdStatus;
//	}

}
