package ibase.webitm.ejb.mfg.adv;
/**
 * Developed by Alka Shah -> 28/03/07
 */
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.mfg.ExplodeBom;
import ibase.webitm.ejb.mfg.MfgCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class RcpBackflushMultiAct extends ActionHandlerEJB implements  RcpBackflushMultiActLocal , RcpBackflushMultiActRemote //SessionBean
{

	/*public void ejbCreate() throws RemoteException, CreateException {
	}

	public void ejbRemove() {
	}

	public void ejbActivate() {
	}

	public void ejbPassivate() {
	}*/

	public String actionHandler() throws RemoteException, ITMException {
		return "";
	}

	public String actionHandler(String actionType, String xmlString,
			String xmlString1, String objContext, String xtraParams)
			throws RemoteException, ITMException {
		Document dom = null;
		Document dom1 = null;

		String retString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				System.out.println("XML String :" + xmlString);
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				System.out.println("XML String1 :" + xmlString1);
				dom1 = genericUtility.parseString(xmlString1);
			}

			System.out.println("actionType:" + actionType + ":");

			if (actionType.equalsIgnoreCase("Stock")) {
				retString = actionStock(dom, dom1, xtraParams);
			}
		} catch (Exception e) {
			System.out
					.println("Exception :RcpBackflushMultiActEJB :actionHandler(String xmlString):"
							+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out
				.println("returning String from RcpBackflushMultiActEJB : actionHandler"
						+ retString);
		return retString;
	}

	public String actionHandlerTransform(String actionType, String xmlString,
			String xmlString1, String objContext, String xtraParams,
			String selDataStr) throws RemoteException, ITMException {
		System.out.println("actionHandlerTransform is calling.............");
		Document dom = null;
		Document dom1 = null;
		Document selDataDom = null;

		String retString = null;
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = GenericUtility.getInstance().parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = GenericUtility.getInstance().parseString(xmlString1);
			}
			if (selDataStr != null && selDataStr.length() > 0) {
				selDataDom = GenericUtility.getInstance().parseString(
						selDataStr);
			}

			System.out.println("actionType:" + actionType + ":");

			if (actionType.equalsIgnoreCase("Stock")) {
				retString = stockTransform(dom, dom1, objContext, xtraParams,
						selDataDom);
			}
		} catch (Exception e) {
			System.out
					.println("Exception :RcpBackflushMultiActEJB :actionHandlerTransform(String xmlString):"
							+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out
				.println("returning String from RcpBackflushMultiActEJB : actionHandlerTransform"
						+ retString);
		return retString;
	}

	private String actionStock(Document dom, Document dom1, String xtraParams) throws RemoteException, ITMException 
    {
		String available = null, backflushType = null, trackShelfLife = null;
		String siteCode = null, itemCode = null, qcReqd = null;
		String sql = null;
		String expDate1 = "", retestDate1 = "",mfgDate1 = "";//updated by nisar on 11/08/07
		//CHANGES DONE BY ALKA 31/07/07 FOR DATE PARSING ERROR AND AVAILABLE QUANTITY TO BE DISPLAYED 
//        Timestamp retestDt = null;
		String retestDt = "";
		String iDescr = "";//added by nisar on 26/09/07
//		java.sql.Date expDate = null, retestDate = null,mfgDate = null;
		double totalQty = 0, allocQty = 0;
//		CHANGES DONE ENDED BY ALKA 31/07/07 FOR DATE PARSING ERROR AND AVAILABLE QUANTITY TO BE DISPLAYED 
		Timestamp expDate = null, retestDate = null, mfgDate = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Connection conn = null;
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");

		if (dom == null) {
			valueXmlString.append("</Root>\r\n");
			return valueXmlString.toString();
		}

		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();

		try {
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
//			available = "Y";  //CHANGED BY ALKA 31/07/07 AS INSTR FUNCTION REPLACED BY IN();
			available = "('Y')";
			siteCode = genericUtility.getColumnValue("site_code", dom1);
			itemCode = genericUtility.getColumnValue("item_code", dom);
			backflushType = genericUtility.getColumnValue("backflush_type", dom1);
			sql = "SELECT (CASE WHEN QC_REQD IS NULL THEN 'N' ELSE QC_REQD END), "
				+ " (CASE WHEN TRACK_SHELF_LIFE IS NULL THEN 'N' ELSE TRACK_SHELF_LIFE END) "
				+ " FROM ITEM WHERE ITEM_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				qcReqd =  rs.getString(1);
				trackShelfLife = rs.getString(2);
			}
			rs.close();
			pstmt.close();
			
			if (trackShelfLife != null && trackShelfLife.equalsIgnoreCase("N") && qcReqd != null && qcReqd.equalsIgnoreCase("N"))
			{
//				retestDt = Timestamp.valueOf("1910-01-01 00:00:00");// CHANGED BY ALKA ON 31/07/07 AS ERROR OCCURING FOR PARSING DATE
				retestDt = genericUtility.getValidDateString("01/01/1910","dd/mm/yyyy", genericUtility.getApplDateFormat());
				System.out.println("retestDt in if :::: " + retestDt);
			}
			else //				ADDED BY ALKA ON 14/07/07 AS ERROR OCCURING FOR PARSING DATE
			{
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				java.util.Date date = sdf.parse(new Timestamp(System.currentTimeMillis()).toString());
	            retestDate = Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
	            retestDt = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(retestDate).toString();
	            System.out.println("retestDt in else :::: " + retestDt);
			}
//			ADDITION BY ALKA 31/07/07 ENDED
			if (backflushType.equalsIgnoreCase("R"))
			{
//				available = "Y,N";//CHANGED BY ALKA 31/07/07 AS INSTR FUNCTION REPLACED BY IN();
				available = "('Y','N')";
			}
			
			sql = " SELECT  A.ITEM_SER, A.ITEM_CODE, A.UNIT, A.LOC_CODE, A.LOT_NO, A.LOT_SL, A.QUANTITY, " 
				+ " (CASE WHEN A.ALLOC_QTY IS NULL THEN 0 ELSE A.ALLOC_QTY END) ALLOC_QTY, A.SITE_CODE, "
				+ " A.EXP_DATE , A.RETEST_DATE, A.RATE, A.MFG_DATE, A.SITE_CODE__MFG, A.PACK_CODE, A.GRADE, "
				+ " A.DIMENSION, A.GROSS_WEIGHT, A.TARE_WEIGHT, A.NET_WEIGHT,C.DESCR FROM STOCK A, INVSTAT B ,ITEM C "
				+ " WHERE (A.INV_STAT = B.INV_STAT) AND C.ITEM_CODE = A.ITEM_CODE "
				+ " AND (( A.ITEM_CODE = '"+itemCode+"' ) AND (A.SITE_CODE = '"+siteCode+"' ) AND (A.QUANTITY > 0) AND (A.QUANTITY - " 
				+ " (CASE WHEN A.ALLOC_QTY IS NULL THEN 0 ELSE A.ALLOC_QTY END) > 0 ) "
//				+ " AND (INSTR('" + available + "',B.AVAILABLE) > 0) AND (A.EXP_DATE IS NULL OR (A.EXP_DATE > ? )) " //CHANGED BY ALKA 31/07/07 AS INSTR FUNCTION REPLACED BY IN();
				+ " AND B.AVAILABLE IN " + available + " AND (A.EXP_DATE IS NULL OR (A.EXP_DATE > ? )) "
				+ " AND ( A.LOT_NO NOT IN ( SELECT LOT_NO FROM QC_ORDER WHERE SITE_CODE = '"+siteCode+"' AND ITEM_CODE = '"+itemCode+"' "
				+ " AND STATUS = 'U' )) AND ( B.STAT_TYPE <> 'S' ))";
			
			pstmt = conn.prepareStatement(sql);
			/*if(retestDt == null){
                pstmt.setNull(1,Types.TIMESTAMP);
            }else{
                pstmt.setTimestamp(1,retestDt);
            }CHANGED BY ALKA ON 14/07/07 AS ERROR OCCURING FOR PARSING DATE*/
			pstmt.setTimestamp(1, Timestamp.valueOf(genericUtility.getValidDateString(retestDt, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat())+ " 00:00:00"));
			System.out.println("sql :: "+ sql);
			System.out.println("Setting parameters ::: itemCode :::[" + itemCode + "] siteCode :::["+ siteCode + "]");
			System.out.println("Setting parameters ::: available :::[" + available + "] retestDt :::["+ retestDt + "]");
			rs = pstmt.executeQuery();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			while (rs.next())
			{
				iDescr = rs.getString("DESCR")==null?"":rs.getString("DESCR");//added by nisar on 26/09/07
//				expDate = rs.getDate(10);
				expDate = rs.getTimestamp(10);
				if (expDate != null)
				{
					expDate1 = sdf.format(expDate);
					System.out.println("expDate1 :"+expDate1);
				}
//				retestDate = rs.getDate(11);
				retestDate = rs.getTimestamp(11);
				if (retestDate != null)
				{
					retestDate1 = sdf.format(retestDate); 
					System.out.println("retestDate1 :"+retestDate1);
				}
                
//                mfgDate = rs.getDate(13);
                mfgDate = rs.getTimestamp(13);
                if(mfgDate != null){
                    mfgDate1 = sdf.format(mfgDate);
                }
				
				if(mfgDate1==null)//added by nisar on 11/08/07 set mfgDate1 to "" if mfgDate1 is null
				{
					mfgDate1="";
				}
				valueXmlString.append("<Detail>\r\n");
				valueXmlString.append("<item_ser>").append("<![CDATA[").append(rs.getString(1).trim()).append("]]>").append("</item_ser>\r\n");			
				valueXmlString.append("<item_code>").append("<![CDATA[").append(rs.getString(2).trim()).append("]]>").append("</item_code>\r\n");			
				valueXmlString.append("<item_descr>").append("<![CDATA[").append(iDescr.trim()).append("]]>").append("</item_descr>\r\n");//added by nisar on 26/09/07			
				valueXmlString.append("<unit>").append("<![CDATA[").append(rs.getString(3)).append("]]>").append("</unit>\r\n");			
				valueXmlString.append("<loc_code>").append("<![CDATA[").append(rs.getString(4).trim()).append("]]>").append("</loc_code>\r\n");			
				valueXmlString.append("<lot_no>").append("<![CDATA[").append(rs.getString(5).trim()).append("]]>").append("</lot_no>\r\n");			
				valueXmlString.append("<lot_sl>").append("<![CDATA[").append(rs.getString(6).trim()).append("]]>").append("</lot_sl>\r\n");			
/*				COMMENTED BY ALKA 31/07/07 TO SHOW THE AVAILABLE QUANTITY INSTEAD OF TOTAL QUANTITY
 * 				valueXmlString.append("<quantity>").append("<![CDATA[").append(rs.getDouble(7)).append("]]>").append("</quantity>\r\n");
				valueXmlString.append("<alloc_qty>").append("<![CDATA[").append(rs.getDouble(8)).append("]]>").append("</alloc_qty>\r\n");*/
//				ADDED BY ALKA 31/07/07 TO SELECT THE AVAILABLE QUANTITY
				totalQty = rs.getDouble(7);
				allocQty = rs.getDouble(8);
				valueXmlString.append("<quantity>").append("<![CDATA[").append(totalQty - allocQty).append("]]>").append("</quantity>\r\n");
//				ADDITION BY ALKA 31/07/07 ENDED TO SELECT THE AVAILABLE QUANTITY
				valueXmlString.append("<site_code>").append("<![CDATA[").append(rs.getString(9).trim()).append("]]>").append("</site_code>\r\n");
                valueXmlString.append("<exp_date><![CDATA[").append(expDate1).append("]]></exp_date>\r\n");                                
//                expDate1 = null;
//                if(retestDate1 != null && retestDate1.trim().length() > 0){
                    valueXmlString.append("<retest_date><![CDATA[").append(retestDate1).append("]]></retest_date>\r\n");
//                }
//                retestDate1 = null;
				valueXmlString.append("<rate><![CDATA[").append(rs.getDouble(12)).append("]]></rate>\r\n");
////				if(mfgDate1==null || mfgDate1.trim().length()==0)
////				{
//                	valueXmlString.append("<mfg_date><![CDATA[").append(" ").append("]]></mfg_date>\r\n");
//
//				}
//				else
//				{
                	valueXmlString.append("<mfg_date><![CDATA[").append(mfgDate1).append("]]></mfg_date>\r\n");
//            	}
//                mfgDate1 = null;
                String siteCodeMfg = rs.getString(14);
				valueXmlString.append("<site_code__mfg><![CDATA[").append(siteCodeMfg == null ? " ":siteCodeMfg.trim()).append("]]></site_code__mfg>\r\n");
                String packCode = rs.getString(15);
				valueXmlString.append("<pack_code><![CDATA[").append(packCode == null ? " ":packCode).append("]]></pack_code>\r\n");
                String grade = rs.getString(16);
				valueXmlString.append("<grade><![CDATA[").append(grade == null ? " ":grade).append("]]></grade>\r\n");
                String dimension =( rs.getString(17)==null ? " " :rs.getString(17));
				valueXmlString.append("<dimension><![CDATA[").append(dimension != null ? dimension:"").append("]]></dimension>\r\n");
				valueXmlString.append("<gross_weight>").append("<![CDATA[").append(rs.getDouble(18)).append("]]>").append("</gross_weight>\r\n");
				valueXmlString.append("<tare_weight>").append("<![CDATA[").append(rs.getDouble(19)).append("]]>").append("</tare_weight>\r\n");
				valueXmlString.append("<net_weight>").append("<![CDATA[").append(rs.getDouble(20)).append("]]>").append("</net_weight>\r\n");
                valueXmlString.append("</Detail>\r\n");
			}
			pstmt.close();
			rs.close();
			valueXmlString.append("</Root>\r\n");
		}//try end
		catch (SQLException sqx) {
			System.out.println("The SQLException occurs in RcpBackflushMultiActEJB for Stock button :" + sqx);
			throw new ITMException(sqx);
		} catch (Exception e) {
			System.out.println("The Exception occure in RcpBackflushMultiActEJB  for Stock button:" + e);
			throw new ITMException(e);
		} finally {
			try {
				conn.close();
				conn = null;
			}catch (Exception e) {}
		}
		System.out.println("valueXmlString return from actionStock :"	+ valueXmlString.toString());
		return valueXmlString.toString();
	}

	private String stockTransform(Document dom, Document dom1, String objContext, String xtraParams, Document selDataDom) throws ITMException 
    {
		System.out.println("stockTransform is calling.............");
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		
		String sql = null, errCode = "", errString = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String tranId = null, itemCode = null, itemDescr = null,  unit = null;
		String stkLocCode = null,stkLotNo = null, stkLotSl = null, locDescr = null;
		String siteCode = null, dimension = null, grossWeight = null, tareWeight = null, netWeight = null;
		String expDate = null, mfgDate = null, siteCodeMfg = null, packCode = null, grade = null; 
		double quantity = 0, remainingQty = 0, inputQty = 0, stkQty = 0, rate = 0;
		Node currDetail = null, currDetail1 = null;
		double allocQty =0.0;

		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try {
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;

			tranId = genericUtility.getColumnValue("tran_id", dom1);
			siteCode = genericUtility.getColumnValue("site_code", dom1);
			itemCode = genericUtility.getColumnValue("item_code", dom);
			itemDescr = genericUtility.getColumnValue("item_descr", dom);
			quantity = Double.parseDouble(genericUtility.getColumnValue("quantity", dom));

			NodeList detailList = selDataDom.getElementsByTagName("Detail");
			int noOfDetails = detailList.getLength();
			System.out.println("noOfDetails ...................................... :" + noOfDetails);
			for (int ctr = 0; ctr < noOfDetails; ctr++) {
				currDetail = detailList.item(ctr);
				System.out.println("ctr.................................................  :" + ctr);
				stkQty = stkQty + Double.parseDouble((genericUtility.getColumnValueFromNode("quantity",	currDetail)));
//				allocQty = allocQty+Double.parseDouble((genericUtility.getColumnValueFromNode("alloc_qty",	currDetail)));  //COMMENTED BY ALKA 31/07/07 AS ONLY AVAILABLE QUANTITY WILL BE SHOWN IN THE POPUP FOR STOCK
			}
			
			System.out.println("stkQty  :" + stkQty);
/*COMMENTED BY ALKA 31/07/07 AS ONLY AVAILABLE QUANTITY WILL BE SHOWN IN THE POPUP FOR STOCK
 * 			System.out.println("allocQty  :" + allocQty);
			stkQty = stkQty - allocQty;
			System.out.println("AvalibleStock  :" +stkQty);
*/
			//			if (stkQty < quantity)
			if (quantity != 0 && stkQty < quantity) //CHANGED BY ALKA 19/07/07 FOR HANDLING NO QUANTITY ENTERED.
			{
				errCode = "VTSTOCK1";
				errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				conn.close();
				conn = null;
				return errString;
			}
			//			remainingQty = quantity;  //COMMENTED BY ALKA AS THE FOLLOWING LOGIC IS ADDED
//			ADDED BY ALKA ON 19/07/07 FOR SELECTED STOCK TO BE ENTERED IN THE DETAIL IF THE QUANTITY IS 0
			if (quantity == 0)
			{
				remainingQty = stkQty;
			}
			else
			{
				remainingQty = quantity;
			}
			System.out.println("quantity at the start of the forloop :::: " + quantity);
			System.out.println("remainingQty at the start of the forloop :::: " + remainingQty);
//			ADDITION ENDED BY ALKA 19/07/07
			if (noOfDetails >= 0)  
			{
				for (int ctr = 0; ctr < noOfDetails && remainingQty > 0; ctr++) 
				{
					valueXmlString.append("<Detail>\r\n");
					currDetail1 = detailList.item(ctr);
					stkLocCode = genericUtility.getColumnValueFromNode("loc_code", currDetail1);
					stkLotNo = genericUtility.getColumnValueFromNode("lot_no", currDetail1);
					stkLotSl = genericUtility.getColumnValueFromNode("lot_sl", currDetail1);
					unit = genericUtility.getColumnValueFromNode("unit", currDetail1);
					expDate = genericUtility.getColumnValueFromNode("exp_date", currDetail1);
					rate = Double.parseDouble(genericUtility.getColumnValueFromNode("rate", currDetail1));
					mfgDate = genericUtility.getColumnValueFromNode("mfg_date", currDetail1);
					siteCodeMfg = genericUtility.getColumnValueFromNode("site_code__mfg", currDetail1);
					packCode = genericUtility.getColumnValueFromNode("pack_code", currDetail1);
					grade = genericUtility.getColumnValueFromNode("grade", currDetail1);
					dimension = genericUtility.getColumnValueFromNode("dimension", currDetail1);
					grossWeight = genericUtility.getColumnValueFromNode("gross_weight", currDetail1);
					tareWeight = genericUtility.getColumnValueFromNode("tare_weight", currDetail1);
					netWeight = genericUtility.getColumnValueFromNode("net_weight", currDetail1);
					
//					stkQty = Double.parseDouble(genericUtility.getColumnValueFromNode("quantity", currDetail1))-Double.parseDouble(genericUtility.getColumnValueFromNode("alloc_qty", currDetail1));
					stkQty = Double.parseDouble(genericUtility.getColumnValueFromNode("quantity", currDetail1));
					System.out.println("stkQty==>  :" + stkQty);
				
					sql = "SELECT DESCR FROM LOCATION WHERE LOC_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, stkLocCode);
					rs = pstmt.executeQuery();
					if (rs.next())
					{
						locDescr = rs.getString(1);
					}
					rs.close();
					pstmt.close(); 

					if (stkQty >= remainingQty)
					{
						inputQty = remainingQty;
						remainingQty = 0;
					}
					else if (stkQty < remainingQty)
					{
						inputQty = stkQty;
						remainingQty = remainingQty - stkQty;
					}
					
					valueXmlString.append("<tran_id isSrvCallOnChg='0'>").append("<![CDATA[").append(tranId).append("]]>").append("</tran_id>\r\n");
					valueXmlString.append("<item_code isSrvCallOnChg='0'>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>\r\n");
					valueXmlString.append("<item_descr isSrvCallOnChg='0'>").append("<![CDATA[").append(itemDescr).append("]]>").append("</item_descr>\r\n");
					valueXmlString.append("<unit isSrvCallOnChg='0'>").append("<![CDATA[").append(unit).append("]]>").append("</unit>\r\n");
					valueXmlString.append("<loc_code isSrvCallOnChg='0'>").append("<![CDATA[").append(stkLocCode).append("]]>").append("</loc_code>\r\n");
					valueXmlString.append("<location_descr isSrvCallOnChg='0'>").append("<![CDATA[").append(locDescr).append("]]>").append("</location_descr>\r\n");
					valueXmlString.append("<lot_no isSrvCallOnChg='0'>").append("<![CDATA[").append(stkLotNo).append("]]>").append("</lot_no>\r\n");
					valueXmlString.append("<lot_sl isSrvCallOnChg='0'>").append("<![CDATA[").append(stkLotSl).append("]]>").append("</lot_sl>\r\n");
					valueXmlString.append("<quantity isSrvCallOnChg='0'>").append("<![CDATA[").append(inputQty).append("]]>").append("</quantity>\r\n");
					valueXmlString.append("<rate isSrvCallOnChg='0'>").append("<![CDATA[").append(rate).append("]]>").append("</rate>\r\n");
					valueXmlString.append("<amount isSrvCallOnChg='0'>").append("<![CDATA[").append(inputQty*rate).append("]]>").append("</amount>\r\n");
					if(mfgDate!=null && mfgDate.trim().length()!=0)
					{
						valueXmlString.append("<mfg_date isSrvCallOnChg='0'>").append("<![CDATA[").append(mfgDate).append("]]>").append("</mfg_date>\r\n");
					}
					valueXmlString.append("<site_code__mfg isSrvCallOnChg='0'>").append("<![CDATA[").append(siteCodeMfg).append("]]>").append("</site_code__mfg>\r\n");
					valueXmlString.append("<pack_code isSrvCallOnChg='0'>").append("<![CDATA[").append(packCode).append("]]>").append("</pack_code>\r\n");
					valueXmlString.append("<grade isSrvCallOnChg='0'>").append("<![CDATA[").append(grade).append("]]>").append("</grade>\r\n");
					valueXmlString.append("<dimension isSrvCallOnChg='0'>").append("<![CDATA[").append(dimension).append("]]>").append("</dimension>\r\n");
					valueXmlString.append("<gross_weight isSrvCallOnChg='0'>").append("<![CDATA[").append(grossWeight).append("]]>").append("</gross_weight>\r\n");
					valueXmlString.append("<tare_weight isSrvCallOnChg='0'>").append("<![CDATA[").append(tareWeight).append("]]>").append("</tare_weight>\r\n");
					valueXmlString.append("<net_weight isSrvCallOnChg='0'>").append("<![CDATA[").append(netWeight).append("]]>").append("</net_weight>\r\n");			
					valueXmlString.append("</Detail>");	
					if (remainingQty == 0)
					{
						break;
					}
				}// for end
			}// end if
			valueXmlString.append("</Root>");
		}// end try
		catch (ITMException itme) {
			throw itme;
		} catch (Exception e) {
			throw new ITMException(e);
		} finally {
			try {
				System.out.println("Closing Connection...");
				conn.close();
				conn = null;
			} catch (Exception e) {
			}
		}
		System.out.println("valueXmlString from :" + valueXmlString.toString());
		return valueXmlString.toString();
	}

	private String allocateItem(Document dom1, String siteCode, String itemCode, double quantity, String xtraParams)throws RemoteException, ITMException
	{
		String locDescr = null, itemDescr = null, sql = "", siteDescr = null, tranId = null;
		String stkLocCode = null, stkLotNo = null, stkLotSl = null, unit = null;
		String convReqd = null, bkflshType = null, convQty = null, convRate = null;
		double remainingQty = 0d, inputQty = 0d, stkQtyLot = 0d, rate = 0;

		PreparedStatement pstmt = null;
		Connection conn = null;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		MfgCommon mfgCommon = new MfgCommon();
		DistCommon distCommon = new DistCommon();

		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;

			System.out.println("[Allocating .....]");

			sql = "SELECT DESCR FROM ITEM WHERE ITEM_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				itemDescr = rs.getString(1);
			}
			
			sql = " SELECT (CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END) - " 
				+ " (CASE WHEN A.ALLOC_QTY IS NULL THEN 0 ELSE A.ALLOC_QTY END), A.UNIT, A.LOC_CODE, A.LOT_NO, "
				+ " A.LOT_SL, A.RATE FROM STOCK A, LOCATION B, INVSTAT C WHERE A.LOC_CODE = B.LOC_CODE "
				+ " AND ((CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END) - " 
				+ " (CASE WHEN A.ALLOC_QTY IS NULL THEN 0 ELSE A.ALLOC_QTY END)) > 0 AND B.INV_STAT = C.INV_STAT "
				+ " AND A.SITE_CODE = ? AND A.ITEM_CODE = ? "
				+ " AND (CASE WHEN A.ALLOC_QTY IS NULL THEN 0 ELSE A.ALLOC_QTY END) >= 0 AND C.AVAILABLE = 'Y' "
				+ " ORDER BY (CASE WHEN A.EXP_DATE IS NULL THEN A.CREA_DATE ELSE A.EXP_DATE END), A.CREA_DATE, " 
				+ " A.LOT_NO , A.LOT_SL";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				stkQtyLot = rs.getDouble(1);
				unit = rs.getString(6);
				stkLocCode = rs.getString(1);
				stkLotNo = rs.getString(2);
				stkLotSl = rs.getString(3);
				rate = rs.getDouble(5);
				
				remainingQty = quantity;
				if (stkQtyLot >=  remainingQty)
				{
					inputQty = remainingQty;
					remainingQty = 0;
				}
				else 
				{
					inputQty = stkQtyLot;
					remainingQty = remainingQty - inputQty;
				}
				sql = "SELECT DESCR FROM LOCATION WHERE LOC_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, stkLocCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					locDescr = rs.getString(1);
				}
				rs.close();
				pstmt.close();
				siteDescr = genericUtility.getColumnValue("site_descr", dom1);
				tranId = genericUtility.getColumnValue("tran_id", dom1);
				bkflshType = genericUtility.getColumnValue("backflush_type", dom1);
				valueXmlString.append("<Detail>\r\n");
				valueXmlString.append("<tran_id>").append("<![CDATA[").append(tranId).append("]]>").append("</tran_id>\r\n");
				valueXmlString.append("<site_code>").append("<![CDATA[").append(siteCode).append("]]>").append("</site_code>\r\n");
				valueXmlString.append("<site_descr>").append("<![CDATA[").append(siteDescr).append("]]>").append("</site_descr>\r\n");
				valueXmlString.append("<item_code>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>\r\n");
				valueXmlString.append("<item_descr>").append("<![CDATA[").append(itemDescr).append("]]>").append("</item_descr>\r\n");
				valueXmlString.append("<unit>").append("<![CDATA[").append(unit).append("]]>").append("</unit>\r\n");
				valueXmlString.append("<loc_code>").append("<![CDATA[").append(stkLocCode).append("]]>").append("</loc_code>\r\n");
				valueXmlString.append("<location_descr>").append("<![CDATA[").append(locDescr).append("]]>").append("</location_descr>\r\n");
				valueXmlString.append("<unit__doc>").append("<![CDATA[").append(unit).append("]]>").append("</unit__doc>\r\n");
				valueXmlString.append("<lot_no>").append("<![CDATA[").append(stkLotNo).append("]]>").append("</lot_no>\r\n");
				valueXmlString.append("<lot_sl>").append("<![CDATA[").append(stkLotSl).append("]]>").append("</lot_sl>\r\n");
				valueXmlString.append("<quantity>").append("<![CDATA[").append(inputQty).append("]]>").append("</quantity>\r\n");
				valueXmlString.append("<rate>").append("<![CDATA[").append(rate).append("]]>").append("</rate>\r\n");
				
				convReqd = mfgCommon.getEnvMfg("999999", "RBKFSH_CONV_REQD", conn);
				if (convReqd.equalsIgnoreCase("NULLFOUND"))
				{
					convReqd = "Y";
				}
				if (convReqd.equalsIgnoreCase("Y") && bkflshType.equalsIgnoreCase("J"))
				{
					ArrayList convQtyList = new ArrayList();
					ArrayList convRateList = new ArrayList();
					convQtyList = distCommon.getConvQuantityFact(unit, "", itemCode, inputQty, 0, conn);
					convQty = (String)convQtyList.get(1);
					convRateList = distCommon.getConvQuantityFact(unit, "", itemCode, rate, 0, conn);
					convRate = (String)convRateList.get(1);
					valueXmlString.append("<conv_qty_doc>").append("<![CDATA[").append("0").append("]]>").append("</conv_qty_doc>\r\n");
					valueXmlString.append("<qty_doc>").append("<![CDATA[").append(convQty).append("]]>").append("</qty_doc>\r\n");
					valueXmlString.append("<rate_doc>").append("<![CDATA[").append(convRate).append("]]>").append("</rate_doc>\r\n");
				}
				valueXmlString.append("</Detail>");	
				if (remainingQty == 0)
				{
					break;
				}

			}
			valueXmlString.append("</Root>\r\n");
		}//try end
		catch (SQLException sqx)
		{
			System.out.println("The SQLException occurs in RcpBackflushMultiActEJB :(Allocate) Button :"+sqx);
			sqx.printStackTrace();
			throw new ITMException(sqx);
		}
		catch (Exception e)
		{
			System.out.println("The Exception occurs in RcpBackflushMultiActEJB : (Allocate) Button :"+e);
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch (Exception e){}
		}
		System.out.println("valueXmlString return from RcpBackflushMultiActEJB :"+valueXmlString.toString());
		return valueXmlString.toString();
	}	
	
	private String getCurrdateAppFormat()
	{
		String currAppdate = null;
		java.sql.Timestamp currDate = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			Object date = null;
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println("currDate :::: [" + currDate + "]");
			System.out.println(genericUtility.getDBDateFormat());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
			System.out.println("currDate :::: [" + currDate + "]");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
			
			System.out.println("currDate :::: [" + currDate + "]");
			
		}
		catch(Exception e)
		{
		System.out.println("Exception in getCurrdateAppFormat"+e.getMessage());
		}
		return (currAppdate);
	}
}