/*
authored by Pawan 10/7/2010 to confirm the transaction
*/

package ibase.webitm.ejb.wms;

import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.*;
import ibase.webitm.ejb.fin.*;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.*;
import java.text.*;
import java.sql.*;

import javax.ejb.*;
import ibase.webitm.ejb.MasterStatefulLocal;
import javax.naming.InitialContext;


@Stateless
public class AsnConf extends ActionHandlerEJB implements AsnConfLocal, AsnConfRemote
{
	String loginEmpCode = "";
	String confDateStr = "";
	@Override
	public String confirm( String tranId, String xtraParams, String forcedFlag ) throws RemoteException,ITMException
	{	
		System.out.println("AsnConf Called........");
		
		boolean isError = false;
		int updCnt = 0;
		
		String confirmed = "";
		String sql = "";
		
		ResultSet rs = null;
		PreparedStatement pstmt = null;	
		Connection conn = null;
		String errString = "";
		//Changed by sumit 24/01/13 start.
		String suppCode = "",qtyStr = "", priceList = "";
		String itemCode = "";
		//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code.start
		String lineNo = "";
		String asnNo = "";
		//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code.end
		double quantity = 0.0, rate = 0.0;
		java.util.Date currDate = null;
		String dbDateFormat = null;
		String applDateFormat = null;
		DateFormat dateFormat = null;
		String currDateStr = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		//Changed by sumit 24/01/13 end.
		
		ITMDBAccessEJB itmdbAccess = new ITMDBAccessEJB();
		try
		{	
			
			GenericUtility genericUtility = GenericUtility.getInstance();
			
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			conn.setAutoCommit(false);
			
			SimpleDateFormat sdf = new SimpleDateFormat( genericUtility.getDBDateTimeFormat());
			Date confDate = new Date();
			confDateStr = sdf.format(confDate);
			System.out.println("confDate is :"+confDate+" confDate str is : "+confDateStr);
			sql = "SELECT CONFIRMED FROM ASN_HDR WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				confirmed = checkNull( rs.getString("CONFIRMED") );
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( confirmed != null && confirmed.equalsIgnoreCase("Y") )
			{
				errString = itmdbAccess.getErrorString("","ASNCONFEMD",loginEmpCode);
				return errString;
			}
			
			//Changed by sumit on 23/01/13 
			currDate = new java.util.Date();
			dbDateFormat = genericUtility.getDBDateFormat();
			applDateFormat = genericUtility.getApplDateFormat();
			dateFormat = new SimpleDateFormat(applDateFormat);
			currDateStr = dateFormat.format(currDate);
			SimpleDateFormat simpleDateFormatDB = new SimpleDateFormat(genericUtility.getDBDateFormat());
			Timestamp timestamp = Timestamp.valueOf(simpleDateFormatDB.format(currDate).toString() + " 00:00:00.0");
			//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code
			//sql = "SELECT AH.SUPP_CODE, AD.QUANTITY, AD.ITEM_CODE FROM ASN_HDR AH, ASN_DET AD WHERE AH.TRAN_ID = ? AND AH.TRAN_ID = AD.TRAN_ID";
			sql = "SELECT AH.SUPP_CODE, AD.QUANTITY, AD.ITEM_CODE,AD.LINE_NO,AH.ASN_NO FROM ASN_HDR AH, ASN_DET AD WHERE AH.TRAN_ID = ? AND AH.TRAN_ID = AD.TRAN_ID";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			while( rs.next())
			{
				suppCode = rs.getString("SUPP_CODE");
				quantity = rs.getDouble("QUANTITY");
				itemCode = rs.getString("ITEM_CODE");
				//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code
				lineNo = checkNull(rs.getString("LINE_NO"));
				asnNo = checkNull(rs.getString("ASN_NO"));
				System.out.println(" suppCode ["+suppCode+"] quantity ["+quantity+"] itemCode ["+itemCode+"]"+"lineNo["+lineNo+"]");
				
				sql = " SELECT PRICE_LIST FROM SUPPLIER WHERE SUPP_CODE = ?";
				pstmt1 = conn.prepareStatement(sql);
				pstmt1.setString(1, suppCode);	
				rs1 = pstmt1.executeQuery();				
				if( rs1.next() )
				{								
					priceList = rs1.getString("PRICE_LIST");
				}
				rs1.close(); rs1 = null;
				pstmt1.close(); pstmt1 = null;
				
				sql="select rate  from pricelist where item_code = ?  and price_list= ? and ? >= eff_from and ? <= valid_upto  ";
				pstmt1 = conn.prepareStatement(sql);
				pstmt1.setString(1, itemCode);// item_code
				pstmt1.setString(2,checkNull(priceList));
				pstmt1.setTimestamp(3,timestamp);
				pstmt1.setTimestamp(4,timestamp );
				rs1 = pstmt1.executeQuery();				
				if( rs1.next() )
				{								
					rate = rs1.getDouble("rate");
				}
				//Changed by Rohan on 17-June-13[WM3CSUN002] for setting rate 0 in case of rate not found in pricelist master.start
				else
				{
					rate = 0;
				}
				//Changed by Rohan on 17-June-13[WM3CSUN002] for setting rate 0 in case of rate not found in pricelist master.end
				rs1.close(); rs1 = null;
				pstmt1.close(); pstmt1 = null;
				if ( rate == 0 )
				{
					/*// 26/10/11 manoharan all the errors should be returned so that warnings can be processed
					//errString = getErrorString("rate","INVRATE",userId);
					errList.add( "INVRATE" );
					errFields.add( childNodeName.toLowerCase() );*/
					//
					//errString = itmdbAccess.getErrorString("","INVRATE",loginEmpCode);
					//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code
					errString = getError(tranId,lineNo,itemCode,"INVRATE",conn);
					System.out.println("errString"+errString);
					return errString;				
				}
				
			}
			rs.close(); rs = null;
			pstmt.close(); pstmt = null;			
			//Changed by sumit on 23/01/13  end	
			
			sql = "UPDATE ASN_HDR SET CONFIRMED = 'Y', CONF_DATE = ?, EMP_CODE__APRV = ? WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement( sql );	 
			pstmt.setTimestamp(1, Timestamp.valueOf( confDateStr ) ); 
			pstmt.setString(2, loginEmpCode); 
			pstmt.setString(3, tranId); 
			updCnt = pstmt.executeUpdate();
			if ( updCnt > 0 )
			{
				System.out.println("ASN_HDR Updated Successfully ::"+updCnt);
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}			
			
			// 16/10/11 manoharan call po generation here
			errString = generatePurcOrder(tranId, xtraParams, forcedFlag, conn);
			System.out.println("errString ::"+errString);

			if (errString.indexOf("PORCREATED") != -1 )
			{
				errString = "";
				isError = false;
			}
			else if ( errString == null || errString.trim().length() == 0 )
			{
				isError = false;
			}
			else
			{
				isError = true;
			}
			System.out.println("isError111 =["+isError+"]");
			// end 16/10/11 manoharan call po generation here
			//Changed by Gulzar on 5/10/2012
			if ( !isError )
			{
				sql = "UPDATE ASN_HDR SET CONFIRMED = 'Y', CONF_DATE = ?, EMP_CODE__APRV = ? WHERE TRAN_ID = ?";
				pstmt = conn.prepareStatement( sql );	 
				pstmt.setTimestamp(1, Timestamp.valueOf( confDateStr ) ); 
				pstmt.setString(2, loginEmpCode); 
				pstmt.setString(3, tranId); 
				updCnt = pstmt.executeUpdate();
				if ( updCnt > 0 )
				{
					System.out.println("ASN_HDR Updated Successfully ::"+updCnt);
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			//End changes by Gulzar on 5/10/2012
		}
		catch(Exception e)
		{
			isError = true;
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("isError =["+isError+"]");
				System.out.println("Commiting and Closing Connection..........");
				if ( !(isError) )
				{
					System.out.println( "inside finally if" );
					conn.commit();
					errString = itmdbAccess.getErrorString("","ASNCONFIRM",loginEmpCode);
				}
				else
				{
					System.out.println( "inside finally rollback else" );
					conn.rollback();
				}
				if( pstmt != null )
				{
					System.out.println( "inside finally if pstmt " );
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && !conn.isClosed() )
				{
					System.out.println( "inside finally if conn " );
					conn.close();
					conn = null;
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		System.out.println("errString is +++:"+errString);
		return errString;
		
	}
	
	/*public String generatePurcOrder(String tranIdAsnHdr, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("Generating Purchase order");
		boolean isError = false;
		int lineNo = 0;
		int quantity = 0;
		String confirmed = "";
		String purcOrder = "";
		String itemCode = "";
		String tranCode = "";
		String refSer = "";
		String siteCode = "";
		String siteCodeBill = "";
		String unit = "";
		String suppCode = "";
		String sysDateStr = "";
		String tranIdPurcOrder = "";
		
		String sql = "";
		
		PreparedStatement pstmt = null;
		PreparedStatement pstmtInsert = null;
		PreparedStatement pstmtUpdate = null;
		ResultSet rs = null ;	
		Connection conn = null;
		String errString = "";
		String loginSite = "";
		String userId = "";
		
		try
		{	
			GenericUtility genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSite");
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			conn.setAutoCommit(false);
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateTimeFormat());
			Date sysDate = new Date();
			sysDateStr = sdf.format(sysDate);
			System.out.println("confDate is :"+sysDate+" confDate str is : "+sysDateStr);
			sql = "SELECT CONFIRMED, PURC_ORDER, TRAN_CODE, ITEM_CODE, SITE_CODE, SUPP_CODE FORM ASN_HDR WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranIdAsnHdr);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirmed = rs.getString("CONFIRMED");
				purcOrder = rs.getString("PURC_ORDER");
				tranCode = rs.getString("TRAN_CODE");
				itemCode = rs.getString("ITEM_CODE");
				siteCode = rs.getString("SITE_CODE");
				suppCode = rs.getString("SUPP_CODE");
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( confirmed.equalsIgnoreCase("Y") )
			{ 
				int purCnt = 0;
				sql = "SELECT COUNT(PURC_ORDER) AS PURCNT FORM PORDER WHERE PURC_ORDER = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, purcOrder);
				rs = pstmt.executeQuery();
				if( rs.next() )
				{	
					purCnt = rs.getInt("PURCNT");
					if( purCnt > 0 )
					{
						errString = getErrorString("","PURORDEXST",userId);
						return errString;
					}
				}
				else
				{
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
					String winName = "w_porder";
					sql = "SELECT REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, winName);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{	
						refSer = rs.getString("REF_SER");
					}
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
					tranIdPurcOrder = generateTranId( userId, loginSite, "w_porder", refSer, conn);
					sql = "INSERT INTO PORDER (PURC_ORDER, ORD_DATE ,SITE_CODE__DLV, SITE_CODE__ORD, SITE_CODE__BILL, TAX_OPT, SUPP_CODE) VALUES ( ?, ?, ?, ?, ?, ?, ?)";
					pstmtInsert = conn.prepareStatement(sql);
					pstmtInsert.setString(1, tranIdPurcOrder);
					pstmtInsert.setTimestamp(2, Timestamp.valueOf( sysDateStr));
					pstmtInsert.setString(3, siteCode);
					pstmtInsert.setString(4, siteCode);
					pstmtInsert.setString(5, siteCodeBill);
					pstmtInsert.setString(6, "L");
					pstmtInsert.setString(6, suppCode);
					int insertCnt = pstmtInsert.executeUpdate();
					System.out.println("number of insert in porder : "+insertCnt);
					pstmtInsert.clearParameters();
					sql = "UPDATE ASN_HDR SET PURC_ORDER = ? WHERE TRAN_ID = ?";
					pstmtUpdate = conn.prepareStatement(sql);
					pstmtUpdate.setString(1, tranIdPurcOrder);
					pstmtUpdate.setString(2, tranIdAsnHdr);
					int updCnt = pstmtUpdate.executeUpdate();
					System.out.println("updated records in ASN_HDR : "+updCnt);
					sql = "SELECT AD.LINE_NO, AD.ITEM_CODE, AD.QUANTITY, I.UNIT FROM ASN_DET AD, ITEM I WHERE AD.TRAN_ID = ? AND I.ITEM_CODE = AD.ITEM_CODE";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranIdAsnHdr);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						System.out.println("Inside while");
						lineNo = rs.getInt("LINE_NO");
						itemCode = rs.getString("ITEM_CODE");
						quantity = rs.getInt("QUANTITY");
						unit = rs.getString("UNIT");
						
						sql = "INSERT INTO PORDDET ( PURC_ORDER, LINE_NO, SITE_CODE, ITEM_CODE, QUANTITY, UNIT ) VALUES ( ?, ?, ?, ?, ?, ?)";
						pstmtInsert = conn.prepareStatement(sql);
						pstmtInsert.setString(1, tranIdPurcOrder );
						pstmtInsert.setInt(2, lineNo );
						pstmtInsert.setString(3, siteCode );
						pstmtInsert.setString(4, itemCode );
						pstmtInsert.setInt(5, quantity );
						pstmtInsert.setString(6, unit );
						insertCnt = pstmtInsert.executeUpdate();
						System.out.println("number of insert in porddet : "+insertCnt);
					}	
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
				}
			}
		}
		catch(Exception e)
		{
			isError = true;
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Commiting and Closing Connection in generatePurcOrder..........");
				if ( !(isError) )
				{
					conn.commit();
					errString = getErrorString("","PORCREATED",userId);
				}
				else
				{
					conn.rollback();
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
			}
		}
		return errString;
	}*/
	@Override
	public String generatePurcOrder(String tranIdAsnHdr, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("Generating Purchase order");
		String confirmed = "";
		String purcOrder = "";
		String itemCode = "";
		String siteCode = "";
		String siteCodeBill = "";
		String unit = "";
		String suppCode = "";
		String sysDateStr = "";
		String tranCode = "";
		String retString = "";
		String loginEmpCode = "";
		String itemSer = "";
		String deptCode = "";
		String crTerm = "";
		String currCode = "";
		String dlvTerm = "";
		String address1 = "";
		String address2 = "";
		String city = "";
		String siteDescr = "";
		String remarks = "";
		String transMode = "";
		String acctCodeInv = "";
		String cctrCodeInv = "";
		String locCode = "";
		String acctCodeAp = "";
		String cctrCodeAp = "";
		String acctCodeDr = "";
		String cctrCodeDr = "";
		String acctCodeCr = "";
		String cctrCodeCr = "";
		String invAcctVal = "";
		String invAcctQcVal = "";
		String itemAcctDetr = "";
		String priceList = "";
		String sql = "";
		
		boolean isError = false;
		int lineNo = 0;
		double quantity = 0 , rate = 0d;

		PreparedStatement pstmt = null;
		PreparedStatement pstmtUpdate = null;
		ResultSet rs = null ;	
		Connection conn = null;
		String errString = "";
		String loginSite = "";
		String userId = "";

		FinCommon finCommon = null;
		
		MasterStatefulLocal masterStatefulLocal = null;
		ITMDBAccessEJB itmdbAccess = new ITMDBAccessEJB();
		DistCommon distComm = new DistCommon();

		try
		{	
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);

			GenericUtility genericUtility = GenericUtility.getInstance();
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSite");
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);

			//SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateTimeFormat());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			Date sysDate = new Date();
			sysDateStr = sdf.format(sysDate);
			String [] authencate = new String[2];
            authencate[0] = "";
            authencate[1] = "";
			System.out.println("sysDate is :"+sysDate+" sysDate str is : "+sysDateStr);
			sql = "SELECT CONFIRMED, PURC_ORDER, TRAN_CODE, SITE_CODE, SUPP_CODE FROM ASN_HDR WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranIdAsnHdr);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirmed = checkNull( rs.getString("CONFIRMED") );
				purcOrder = checkNull( rs.getString("PURC_ORDER") );
				tranCode = checkNull( rs.getString("TRAN_CODE") );
				siteCode = checkNull( rs.getString("SITE_CODE") );
				suppCode = checkNull( rs.getString("SUPP_CODE") );
			}	
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if( "Y".equalsIgnoreCase(confirmed) )
			{ 
				errString = generatePurcOrder(tranIdAsnHdr, xtraParams, forcedFlag, conn);
			}
			else
			{
				errString = itmdbAccess.getErrorString("","UNCONFDASN",userId);
				isError = true;
				return errString;
			}
			System.out.println("errString from generatePorder>> =["+errString+"]");
		}
		catch(Exception e)
		{
			isError = true;
			errString = "ERROR";
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				
				if ( !(isError) && (errString == null || errString.trim().length() == 0 ) )//retString.indexOf("Success") != -1 )
				{
					System.out.println("Commiting and Closing Connection in generatePurcOrder..........");
					conn.commit();
					errString = itmdbAccess.getErrorString("","PORCREATED",userId);
				}
				else
				{
					conn.rollback();
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}
	
	public String generatePurcOrder(String tranIdAsnHdr, String xtraParams, String forcedFlag, Connection conn) throws RemoteException,ITMException
	{
		System.out.println("Generating Purchase order");
		String confirmed = "";
		String purcOrder = "";
		String itemCode = "";
		String packCode = "";
		String siteCode = "";
		String siteCodeBill = "";
		String unit = "";
		String suppCode = "";
		String sysDateStr = "";
		String tranCode = "";
		String retString = "";
		String loginEmpCode = "";
		String itemSer = "";
		String termTable="";
		String deptCode = "";
		String crTerm = "";
		String currCode = "";
		String dlvTerm = "";
		String address1 = "";
		String address2 = "";
		String city = "";
		String siteDescr = "";
		String remarks = "";
		String transMode = "";
		String acctCodeInv = "";
		String cctrCodeInv = "";
		String locCode = "";
		String acctCodeAp = "";
		String cctrCodeAp = "";
		String acctCodeDr = "";
		String cctrCodeDr = "";
		String acctCodeCr = "";
		String cctrCodeCr = "";
		String invAcctVal = "";
		String invAcctQcVal = "";
		String itemAcctDetr = "";
		String priceList = "";
		String pricelistClg="";
		String sql = "";
		String scacCode = "";
		//changed by chaitali on 05/12/11
		String priceListStd = "";
		String postType = "";
		String tranType = ""; //changed by sankara WM3ESUN007 on 12/08/13
		double rateStd = 0d;
		//End changed by chaitali 05/12/11
		double rateClg = 0d; //Added By Mahesh Patidar on 28/06/12
		String sql1 = "";
		Date currDate = null;
		Date dueDate = null;
		int purLeadTime = 0;
		SimpleDateFormat simpleDateFormat1 = null;
		
		boolean isError = false;
		int lineNo = 0;
		double quantity = 0 , rate = 0d;

		PreparedStatement pstmt = null,pstmt1 = null;
		PreparedStatement pstmtUpdate = null;
		ResultSet rs = null ,rs1 = null;	
		String errString = "";
		String loginSite = "";
		String userId = "";
		String asnNo = "";//Added by sumit on 17/05/13
		FinCommon finCommon = null;
		
		MasterStatefulLocal masterStatefulLocal = null;
		ITMDBAccessEJB itmdbAccess = new ITMDBAccessEJB();
		DistCommon distComm = new DistCommon();

		try
		{	
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			GenericUtility genericUtility = GenericUtility.getInstance();
			simpleDateFormat1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
			finCommon = new FinCommon();
			currDate = new Date();
     
			
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode"));
			// 16/10/11 manoharan connection passed as parameter
			//ConnDriver connDriver = new ConnDriver();
			//conn = connDriver.getConnectDB("DriverITM");
			//conn.setAutoCommit(false);
			// end 16/10/11 manoharan connection passed as parameter
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			Date sysDate = new Date();
			sysDateStr = sdf.format(sysDate);
			String [] authencate = new String[2];
            authencate[0] = "";
            authencate[1] = "";
			System.out.println("sysDate is :"+sysDate+" sysDate str is : "+sysDateStr);
			//Changed by sumit on 17/05/13 added asn_no column
			//sql = "SELECT CONFIRMED, PURC_ORDER, SCAC_CODE, SITE_CODE, SUPP_CODE FROM ASN_HDR WHERE TRAN_ID = ?";
			//Changed by sankara on 12/08/13 aded tran_type column for WM3ESUN007
			//sql = "SELECT CONFIRMED, PURC_ORDER, SCAC_CODE, SITE_CODE, SUPP_CODE,ASN_NO FROM ASN_HDR WHERE TRAN_ID = ?";
			sql = " SELECT CONFIRMED, PURC_ORDER, SCAC_CODE, SITE_CODE, SUPP_CODE, ASN_NO, TRAN_TYPE FROM ASN_HDR WHERE TRAN_ID = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranIdAsnHdr);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirmed = checkNull( rs.getString("CONFIRMED") );
				purcOrder = checkNull( rs.getString("PURC_ORDER") );
				scacCode = checkNull( rs.getString("SCAC_CODE") );
				siteCode = checkNull( rs.getString("SITE_CODE") );
				suppCode = checkNull( rs.getString("SUPP_CODE") );
				//Changed by sumit on 17/05.13 
				asnNo = checkNull( rs.getString("ASN_NO") );
				//Changed by sankara on 12/08/13 for updation in pucahse order for WM3ESUN007
				tranType = checkNull( rs.getString("TRAN_TYPE") );
				System.out.println("TRANTYPE==="+tranType);
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
		
			/*
			sql = "SELECT TRAN_CODE FROM TRANSPORTER WHERE SCAC_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, scacCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				tranCode = checkNull( rs.getString("TRAN_CODE") );
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			*/
			if( confirmed.equalsIgnoreCase("Y") )
			{ 
				
				//Chnaged by Rohan on 09-07-13 for asn should allow pre-order purchase order.start
				if(("".equalsIgnoreCase(purcOrder) || purcOrder == null) && purcOrder.trim().length() <= 0)
				//Chnaged by Rohan on 09-07-13 for asn should allow pre-order purchase order.end	
				{	
					sql = "SELECT SITE_CODE__ACCT, ADD1, ADD2, CITY, DESCR FROM SITE WHERE SITE_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, siteCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						siteCodeBill = checkNull( rs.getString("SITE_CODE__ACCT") );
						address1 = checkNull( rs.getString("ADD1") );
						address2 = checkNull( rs.getString("ADD2") );
						city = checkNull( rs.getString("CITY") );
						siteDescr = checkNull( rs.getString("DESCR") );
					}	
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
				
					//Chnaged by Rohan on 09-07-13 for asn should allow pre-order purchase order.start
					/*
					int purCnt = 0;
					sql = "SELECT COUNT(PURC_ORDER) AS PURCNT FROM PORDER WHERE PURC_ORDER = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, purcOrder);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{	
						purCnt = rs.getInt("PURCNT");
					}
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
					if( purCnt > 0 )
					{	
						
						System.out.println("inside purcnt before");
						errString = itmdbAccess.getErrorString("","PURORDEXST",userId);
						System.out.println("inside purcnt before");
						return errString;
					}
					*/
				    //Chnaged by Rohan on 09-07-13 for asn should allow pre-order purchase order.end	
					remarks = "From ASN : " + tranIdAsnHdr;
					sql = "SELECT DEPT_CODE FROM EMPLOYEE WHERE EMP_CODE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, loginEmpCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						deptCode = checkNull(rs.getString( "DEPT_CODE" ));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;

					sql = "SELECT CR_TERM, CURR_CODE, DLV_TERM, PRICE_LIST,PRICE_LIST__CLG FROM SUPPLIER WHERE SUPP_CODE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, suppCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						crTerm = checkNull(rs.getString( "CR_TERM" ));
						currCode = checkNull(rs.getString( "CURR_CODE" ));
						dlvTerm = checkNull(rs.getString( "DLV_TERM" ));
						priceList = checkNull(rs.getString( "PRICE_LIST" ));
						pricelistClg= checkNull(rs.getString( "PRICE_LIST__CLG" ));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;

					/*****************sql = "SELECT CR_TERM, CURR_CODE, DLV_TERM FROM SUPPLIER WHERE SUPP_CODE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, loginEmpCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						crTerm = rs.getString( "CR_TERM" );
						currCode = rs.getString( "CURR_CODE" );
						dlvTerm = rs.getString( "DLV_TERM" );
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;*************/

					//Changes made by gulzar to calculate the exchange rate on 12/28/2011
					String currCodeBase = "";
					double exchRate = 0d;
					sql = "SELECT A.CURR_CODE FROM FINENT A, SITE B WHERE B.FIN_ENTITY = A.FIN_ENTITY AND B.SITE_CODE = ? ";
					pstmt = conn.prepareStatement( sql );
					pstmt.setString(1, loginSite );
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						currCodeBase = checkNull( rs.getString("CURR_CODE") );
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;

					exchRate = finCommon.getDailyExchRateSellBuy(currCode.trim(),"",loginSite.trim(),sysDateStr.trim(),"B", conn);
					//End changes by gulzar on 12/28/2011
					
					sql = "SELECT ASN.ITEM_CODE, ITEM.ITEM_SER ,itemser.term_table FROM ASN_DET ASN, ITEM ITEM ,itemser itemser "+
							"WHERE ASN.ITEM_CODE = ITEM.ITEM_CODE AND ASN.TRAN_ID = ? AND itemser.item_ser =ITEM.ITEM_SER";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranIdAsnHdr);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						itemSer = checkNull(rs.getString( "ITEM_SER" ));
						termTable=checkNull(rs.getString( "term_table" ));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;
					
					// modify by cpatil on 30-AUG-12 start
					//sql = "SELECT TRANS_MODE FROM TRANSPORTER_MODE WHERE TRAN_CODE = ? ";
					sql = " SELECT tm.TRANS_MODE,tm.TRAN_CODE FROM TRANSPORTER_MODE tm , transporter t " + 
						  "	where  tm.TRAN_CODE = t.TRAN_CODE and t.SCAC_CODE = ? and tm.TRANS_MODE is not null";
					
					pstmt = conn.prepareStatement(sql);
					//pstmt.setString(1, tranCode);
					pstmt.setString(1, scacCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						transMode = checkNull(rs.getString( "TRANS_MODE" ));
						tranCode = checkNull(rs.getString( "TRAN_CODE" ));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;
					
					StringBuffer xmlString= new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		            xmlString.append("<DocumentRoot><description>Datawindow Root</description><group0><description>Group0 escription</description>");
		            xmlString.append("<Header0>");
		            xmlString.append("<description>Header0 members</description>");
		            xmlString.append("<objName><![CDATA[").append("porder_insert").append("]]></objName>");
		            xmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
		            xmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
		            xmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
		            xmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
		            xmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
		            xmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
		            xmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
		            xmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
		            xmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
		            xmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
		            xmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
		            
		            xmlString.append("<Detail1 dbID='' domID=\"1\" objName=\"porder_insert\" objContext=\"1\">");
		            xmlString.append("<attribute pkNames=\"purc_order:\" status=\"N\" updateFlag=\"A\" selected=\"N\" />");
		            xmlString.append("<purc_order><![CDATA[").append("").append("]]></purc_order>");
		            xmlString.append("<pord_type><![CDATA[").append("R").append("]]></pord_type>");
		            xmlString.append("<ord_date><![CDATA[").append(sysDateStr).append("]]></ord_date>");
		            xmlString.append("<site_code__dlv><![CDATA[").append(siteCode).append("]]></site_code__dlv>");
		            xmlString.append("<site_code__ord><![CDATA[").append(siteCode).append("]]></site_code__ord>");
		            xmlString.append("<site_code__bill><![CDATA[").append(siteCodeBill).append("]]></site_code__bill>");
		            //xmlString.append("<tax_opt><![CDATA[").append("L").append("]]></tax_opt>");
		            xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
		            
		            xmlString.append("<confirmed><![CDATA[").append("Y").append("]]></confirmed>");
//		            xmlString.append("<frt_rate><![CDATA[0]]></frt_rate>");//Added By Mahesh Patidar on 04/07/12
		            xmlString.append("<conf_date><![CDATA[").append(sysDateStr).append("]]></conf_date>");
					xmlString.append("<emp_code__aprv><![CDATA[").append(loginEmpCode).append("]]></emp_code__aprv>");
		            xmlString.append("<supp_code><![CDATA[").append(suppCode).append("]]></supp_code>");
					xmlString.append("<status_date><![CDATA[").append(sysDateStr).append("]]></status_date>");
					xmlString.append("<tax_date><![CDATA[").append(sysDateStr).append("]]></tax_date>");
					xmlString.append("<dept_code><![CDATA[").append(deptCode).append("]]></dept_code>");
					xmlString.append("<emp_code><![CDATA[").append(loginEmpCode).append("]]></emp_code>");
					xmlString.append("<item_ser><![CDATA[").append(itemSer).append("]]></item_ser>");
					xmlString.append("<cr_term><![CDATA[").append(crTerm).append("]]></cr_term>");
					xmlString.append("<curr_code><![CDATA[").append(currCode).append("]]></curr_code>");
					xmlString.append("<curr_code__frt><![CDATA[").append(currCode).append("]]></curr_code__frt>");
					xmlString.append("<dlv_term><![CDATA[").append(dlvTerm).append("]]></dlv_term>");
					xmlString.append("<ord_amt><![CDATA[").append("0").append("]]></ord_amt>");
					xmlString.append("<tax_amt><![CDATA[").append("0").append("]]></tax_amt>");
					xmlString.append("<tot_amt><![CDATA[").append("0").append("]]></tot_amt>");
					xmlString.append("<frt_amt><![CDATA[").append("0").append("]]></frt_amt>");
					xmlString.append("<insurance_amt><![CDATA[").append("0").append("]]></insurance_amt>");
					xmlString.append("<adv_perc><![CDATA[").append("0").append("]]></adv_perc>");
					xmlString.append("<vouch_adv_amt><![CDATA[").append("0").append("]]></vouch_adv_amt>");
					xmlString.append("<accept_criteria><![CDATA[").append("N").append("]]></accept_criteria>");
					xmlString.append("<post_type><![CDATA[").append("S").append("]]></post_type>");
					xmlString.append("<site_add1><![CDATA[").append(address1).append("]]></site_add1>");
					xmlString.append("<site_add2><![CDATA[").append(address2).append("]]></site_add2>");
					xmlString.append("<city__site><![CDATA[").append(city).append("]]></city__site>");
					xmlString.append("<site_descr><![CDATA[").append(siteDescr).append("]]></site_descr>");
					//Changed by sumit on 17/05/13 no need to store asn no in remark column.
					//xmlString.append("<remarks><![CDATA[").append(remarks).append("]]></remarks>");
					xmlString.append("<tran_code><![CDATA[").append(tranCode).append("]]></tran_code>");
					xmlString.append("<trans_mode><![CDATA[").append(transMode).append("]]></trans_mode>");
					xmlString.append("<price_list><![CDATA[").append(priceList).append("]]></price_list>");
					xmlString.append("<price_list__clg><![CDATA[").append(pricelistClg).append("]]></price_list__clg>");
					xmlString.append("<exch_rate><![CDATA[").append(exchRate).append("]]></exch_rate>");//Changes added by gulzar on 12/28/2011
					//added by shamim as per discussion with Shri Mam curr_code__comm ??
					xmlString.append("<curr_code__comm><![CDATA[").append(currCode).append("]]></curr_code__comm>");//itemchange
					xmlString.append("<term_table><![CDATA[").append(termTable).append("]]></term_table>"); // as per itemchange
					xmlString.append("<frt_rate><![CDATA[").append(1).append("]]></frt_rate>");//item change & SINCE ALL CURRENCY ARE SAME
					//SETTING STATUS Ostatus
					xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
					//Changed by sumit on 13/05/13 added asn_no Req.Id [WM3BSUN005]
					xmlString.append("<asn_no><![CDATA[").append(asnNo).append("]]></asn_no>");					
					xmlString.append("</Detail1>");
					System.out.println("<!@#>seting status O xml " +xmlString.toString());

					finCommon = new FinCommon(); 
					

					sql = "UPDATE ASN_DET SET LINE_NO__ORD =  ?  WHERE TRAN_ID = ? AND LINE_NO = ?";
					pstmtUpdate = conn.prepareStatement(sql);

					sql = "SELECT ACCT_CODE__AP, CCTR_CODE__AP FROM SUPPLIER WHERE SUPP_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranIdAsnHdr);
					rs = pstmt.executeQuery();
					if ( rs.next() )
					{
						acctCodeAp = checkNull(rs.getString("ACCT_CODE__AP"));
						cctrCodeAp = checkNull(rs.getString("CCTR_CODE__AP"));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;

					//added by chaitali 05/12/11 
					postType = checkNull(distComm.getDisparams("999999", "POST_PORCP_SA", conn));
					//end changes by chaitali 05/12/11 

					String lineNoOrd = "";
					
					//Commented and changes below by gulzar on 12/28/2011
					String lotNo = "";

					double shipperSize = 0d, grossWeight = 0d, netWeight = 0d, tareWeight = 0d;

					int noArt = 0;

					PreparedStatement pstmtItemLotPack = null;
					ResultSet rsItemLotPack = null;

					sql  = "SELECT SHIPPER_SIZE, GROSS_WEIGHT, NET_WEIGHT FROM ITEM_LOT_PACKSIZE WHERE ITEM_CODE = ? AND LOT_NO__FROM <= ? AND LOT_NO__TO >= ? ";
					pstmtItemLotPack = conn.prepareStatement(sql);

					//sql = "SELECT AD.LINE_NO, AD.ITEM_CODE, AD.QUANTITY, I.UNIT, I.LOC_CODE, I.ITEM_SER FROM ASN_DET AD, ITEM I WHERE AD.TRAN_ID = ? AND AD.ITEM_CODE = I.ITEM_CODE ORDER BY AD.LINE_NO ";
					sql = "SELECT AD.LINE_NO, AD.ITEM_CODE, AD.QUANTITY, AD.LOT_NO, I.UNIT, I.LOC_CODE, I.ITEM_SER, I.PACK_CODE "
						+ " FROM ASN_DET AD, ITEM I WHERE AD.TRAN_ID = ? AND AD.ITEM_CODE = I.ITEM_CODE ORDER BY AD.LINE_NO ";
					//End changes by gulzar on 12/28/2011
					
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranIdAsnHdr);
					rs = pstmt.executeQuery();
					int domID = 0;
					while( rs.next())
					{
						domID++;
						lineNo = rs.getInt("LINE_NO");
						itemCode = rs.getString("ITEM_CODE");
						quantity = rs.getDouble("QUANTITY");
						unit = rs.getString("UNIT");
						locCode = rs.getString("LOC_CODE");
						itemSer = rs.getString("ITEM_SER");
						lotNo = rs.getString("LOT_NO");//Gulzar on 12/28/2011
						packCode = checkNull(rs.getString("PACK_CODE"));
						
						sql1 = " SELECT PUR_LEAD_TIME FROM ITEM WHERE ITEM_CODE = ?";
						
						pstmt1 = conn.prepareStatement(sql1);
						pstmt1.setString(1, itemCode);
						rs1 = pstmt1.executeQuery();
						if( rs1.next() )
						{
							purLeadTime = rs1.getInt( "PUR_LEAD_TIME" );
							System.out.println("PUR_LEAD_TIME ="+purLeadTime);
						}
						rs1.close();
						pstmt1.close();
						pstmt1 = null;
						rs1 = null;
						dueDate = addDays(currDate, purLeadTime) ;
						System.out.println("dueDate="+dueDate);
						
						itemAcctDetr  = finCommon.getFromAcctDetr(itemCode, itemSer, "IN", conn);
						System.out.println("manohar 09/05/12 itemAcctDetr [" +itemAcctDetr + "]") ;
						String tokens [] = itemAcctDetr.split(",");
						System.out.println("manohar 09/05/12 tokens [" + tokens + "]") ;
						if ( tokens.length >= 2)
						{
							System.out.println("manohar 09/05/12 inside getting from string array tokens [" + tokens + "]") ;
							acctCodeDr = tokens[0];
							cctrCodeDr = tokens[1];
						}
						else
						{
							acctCodeDr = itemAcctDetr.substring(0,itemAcctDetr.indexOf(",") -1);
							cctrCodeDr = itemAcctDetr.substring(itemAcctDetr.indexOf(",") + 1);
						}
						System.out.println("manohar 09/05/12 acctCodeDr [" +acctCodeDr + "] cctrCodeDr [" + cctrCodeDr + "]") ;
						tokens = null;

						invAcctVal = finCommon.getFinparams("999999", "INV_ACCT_PORCP", conn);
						if ( "NULLFOUND".equals(invAcctVal.trim()) || invAcctVal.trim().length() == 0 )
						{
							invAcctVal = "N";
						}

						invAcctQcVal = finCommon.getFinparams("999999", "INV_ACCT_QCORDER", conn);
						if ( "NULLFOUND".equals(invAcctQcVal.trim()) || invAcctQcVal.trim().length() == 0 )
						{
							invAcctQcVal = "N";
						}
						if ( "Y".equals(invAcctVal) && !"Y".equals(invAcctQcVal) )
						{
							itemAcctDetr  = finCommon.getFromAcctDetr(itemCode, itemSer, "PO", conn);
						}
						else // 16/10/11 manoharan this else part added
						{
							itemAcctDetr  = finCommon.getFromAcctDetr(itemCode, itemSer, "PORCP", conn);
						}
						
						tokens = itemAcctDetr.split(",");

						if ( tokens.length >= 2)
						{
							acctCodeCr = tokens[0];
							cctrCodeCr = tokens[1];
						}
						else
						{
							acctCodeCr = itemAcctDetr.substring(0,itemAcctDetr.indexOf(",") -1+ 1);
							cctrCodeCr = itemAcctDetr.substring(itemAcctDetr.indexOf(",") + 1);
						}
						System.out.println("manohar 09/05/12 acctCodeDr [" +acctCodeCr + "] cctrCodeDr [" + cctrCodeCr + "]") ;
						
						if ( acctCodeCr == null || acctCodeCr.trim().length() == 0 )
						{
							acctCodeCr = acctCodeAp;
							cctrCodeCr = cctrCodeAp;
						}

						rate = distComm.pickRate( priceList, sysDateStr, itemCode, " ", "L", quantity, conn );
						if (cctrCodeCr == null || "null".equals(cctrCodeCr) || cctrCodeCr.trim().length() == 0)
						{
							cctrCodeCr = "    ";
						}
						if (cctrCodeDr == null || "null".equals(cctrCodeDr) || cctrCodeDr.trim().length() == 0)
						{
							cctrCodeDr = "    ";
						}
						//added by chaitali 05/12/11 
						priceListStd = "";
						if("S".equalsIgnoreCase(postType.trim()))
						{
							priceListStd = checkNull(distComm.getDisparams("999999", "STD_PO_PL", conn));
							if( priceListStd.trim().length() > 0 )
							{
								rateStd = distComm.pickRate( priceListStd, sysDateStr, itemCode, " ", "L", conn );
							}
						}
						if ( rateStd == 0 )
						{
							rateStd = rate;
						}
						//end changes by chaitali 05/12/11 
						//added by Mahesh Patidar on 28/06/12 
						if( pricelistClg.trim().length() > 0 )
						{
							rateClg = distComm.pickRate( pricelistClg, sysDateStr, itemCode, " ", "L", conn );
						}
						if ( rateClg == 0 )
						{
							rateClg = rate;
						}
						//end changes by Mahesh Patidar 
						//Changes made by gulzar on 12/28/2011 to calculate the no of article(no_art) 
						pstmtItemLotPack.setString(1, itemCode);
						pstmtItemLotPack.setString(2, lotNo);
						pstmtItemLotPack.setString(3, lotNo);
						rsItemLotPack = pstmtItemLotPack.executeQuery();
						if ( rsItemLotPack.next() )
						{
							shipperSize =  rsItemLotPack.getDouble("SHIPPER_SIZE");
							grossWeight =  rsItemLotPack.getDouble("GROSS_WEIGHT");
							netWeight =  rsItemLotPack.getDouble("NET_WEIGHT");
							tareWeight = grossWeight - netWeight;
							if ( shipperSize > 0 )
							{
								noArt = (int)(quantity / shipperSize);
							}
						}
						rsItemLotPack.close();
						rsItemLotPack = null;
						pstmtItemLotPack.clearParameters();
						//End changes by gulzar on 12/28/2011

					
						xmlString.append("<Detail2 dbID=':' domID='" + domID + "' objName='porder' objContext='2'>");
	                    xmlString.append("<attribute pkNames='purc_order:line_no:' status='N' updateFlag='A' selected='N'/>");
	                    xmlString.append("<purc_order><![CDATA[").append("").append("]]></purc_order>");
						
						// pick right 3 char
						lineNoOrd = "   " + domID;
						lineNoOrd = lineNoOrd.substring( lineNoOrd.length()-3 );
						
	                    xmlString.append("<line_no><![CDATA[").append(lineNoOrd).append("]]></line_no>");
	                    xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
						xmlString.append("<status_date><![CDATA[").append(sysDateStr).append("]]></status_date>");
	                    xmlString.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
	                    xmlString.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
	                    xmlString.append("<quantity><![CDATA[").append(quantity).append("]]></quantity>");
	                    xmlString.append("<quantity__stduom><![CDATA[").append(quantity).append("]]></quantity__stduom>");
	                    xmlString.append("<unit><![CDATA[").append(unit).append("]]></unit>");
	                    xmlString.append("<unit__std><![CDATA[").append(unit).append("]]></unit__std>");
	                    xmlString.append("<unit__rate><![CDATA[").append(unit).append("]]></unit__rate>");
	                    xmlString.append("<rate><![CDATA[").append( rate ).append("]]></rate>");
	                    xmlString.append("<discount><![CDATA[0]]></discount>");
	                    xmlString.append("<tax_amt><![CDATA[0]]></tax_amt>");
	                    xmlString.append("<tot_amt><![CDATA[0]]></tot_amt>");
	                    xmlString.append("<dlv_qty><![CDATA[0]]></dlv_qty>");
	                    if(dueDate != null)
	                    {
	                    	xmlString.append("<dlv_date><![CDATA["+simpleDateFormat1.format(dueDate)+"]]></dlv_date>");//added by Kunal Mandhre
	                    }
	                    xmlString.append("<rate__stduom><![CDATA[").append(rate).append("]]></rate__stduom>");
	                    xmlString.append("<pack_code><![CDATA[").append(packCode).append("]]></pack_code>");//Added By Mahesh Patidar on 28/06/12
	                    //xmlString.append("<no_art><![CDATA[").append("0").append("]]></no_art>");//Commented by gulzar on 12/28/2011
	                    xmlString.append("<no_art><![CDATA[").append( noArt ).append("]]></no_art>");//changes added by gulzar on 12/28/2011
	                    //Changed By Mahesh Patidar on 28/06/12
	                    System.out.println("Rate clg value ["+rateClg+"]");
	                    xmlString.append("<rate__clg><![CDATA[").append(rateClg).append("]]></rate__clg>"); //Commented By Mahesh Patidar on 28/06/12
	                    //Ended By Mahesh Patidar
	                    //xmlString.append("<rate__clg><![CDATA[").append("0").append("]]></rate__clg>"); //Commented By Mahesh Patidar on 28/06/12
						//commented and changed by chaitali on 05/12/11
	                    //xmlString.append("<std_rate><![CDATA[").append( rate ).append("]]></std_rate>");
	                    xmlString.append("<std_rate><![CDATA[").append( rateStd ).append("]]></std_rate>");
						//End changed by chaitali on 05/12/11
	                    xmlString.append("<conv__qty_stduom><![CDATA[").append("1").append("]]></conv__qty_stduom>");
	                    xmlString.append("<conv__rtuom_stduom><![CDATA[").append("1").append("]]></conv__rtuom_stduom>");
	                    xmlString.append("<req_date><![CDATA[").append(sysDateStr).append("]]></req_date>");
	                    xmlString.append("<loc_code><![CDATA[").append(locCode).append("]]></loc_code>");
	                    xmlString.append("<acct_code__dr><![CDATA[").append(acctCodeDr).append("]]></acct_code__dr>");
	                    xmlString.append("<cctr_code__dr><![CDATA[").append(cctrCodeDr).append("]]></cctr_code__dr>");
	                    xmlString.append("<acct_code__cr><![CDATA[").append(acctCodeCr).append("]]></acct_code__cr>");
	                    xmlString.append("<cctr_code__cr><![CDATA[").append(cctrCodeCr).append("]]></cctr_code__cr>");
						xmlString.append("<operation><![CDATA[").append("0").append("]]></operation>");
						xmlString.append("<git_qty><![CDATA[").append("0").append("]]></git_qty>");
						xmlString.append("<adj_qty><![CDATA[").append("0").append("]]></adj_qty>");
						xmlString.append("<quantity__fc><![CDATA[").append("0").append("]]></quantity__fc>");
	                    xmlString.append("</Detail2>");
			            System.out.println("xmlString For generation Purchase Order:: "+xmlString.toString());
						// 12/10/11 manoharan
						pstmtUpdate.setString(1, lineNoOrd);
						pstmtUpdate.setString(2, tranIdAsnHdr);
						pstmtUpdate.setInt(3,lineNo );
						pstmtUpdate.executeUpdate();
						pstmtUpdate.clearParameters();
						// end 12/10/11 manoharan
					}	
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
					xmlString.append("</Header0></group0></DocumentRoot>");
					System.out.println("xmlString For generation Purchase Order:: "+xmlString.toString());
		            masterStatefulLocal = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local"); 
		            
		            retString = masterStatefulLocal.processRequest( authencate, siteCode, true, xmlString.toString()); // for ejb3 on 3/31/2009
		            System.out.println("retString....qqq:: "+retString);
		            
					String autoConf = "";
					sql = "SELECT AUTO_CONFIRM FROM TRANSETUP WHERE TRAN_WINDOW = 'w_porder'";
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{	
						autoConf = checkNull(rs.getString("AUTO_CONFIRM"));
					}
					rs.close(); rs = null;
					pstmt.close(); pstmt = null;

					
					if ( retString.indexOf("Success") > -1 && retString.indexOf("<TranID>") > 0 )
					{
					    String tranIdPurcOrder = retString.substring( retString.indexOf("<TranID>")+8, retString.indexOf("</TranID>"));
						System.out.println("tranId is :"+tranIdPurcOrder);
						

						if( retString.indexOf("Success") != -1 )
						{
							sql = "UPDATE ASN_HDR SET PURC_ORDER = ? WHERE TRAN_ID = ?";
							pstmtUpdate = conn.prepareStatement(sql);
							pstmtUpdate.setString(1, tranIdPurcOrder);
							pstmtUpdate.setString(2, tranIdAsnHdr);
							int updCnt = pstmtUpdate.executeUpdate();
							pstmtUpdate.close(); pstmtUpdate = null;
							System.out.println("updated records in ASN_HDR : "+updCnt);

							 // Changed by sankara on 12-08-13 for updation pord_type against generated purchase order WM3ESUN007 satrt..
							/*	sql = "UPDATE PORDER SET CONFIRMED = 'Y', EMP_CODE__APRV = ?, CONF_DATE = ?, POST_TYPE = 'S'  WHERE PURC_ORDER = ? ";
								pstmtUpdate = conn.prepareStatement(sql);
								pstmtUpdate.setString(1, loginEmpCode);
								pstmtUpdate.setTimestamp(2, Timestamp.valueOf( confDateStr ) ); 
								pstmtUpdate.setString(3, tranIdPurcOrder);
								updCnt = pstmtUpdate.executeUpdate();
								pstmtUpdate.close(); pstmtUpdate = null;
								System.out.println("updated records in PORDER : "+updCnt);   */
								
								sql = " UPDATE PORDER SET CONFIRMED = 'Y', EMP_CODE__APRV = ?, CONF_DATE = ?, POST_TYPE = 'S', PORD_TYPE = ?  WHERE PURC_ORDER = ? ";
								pstmtUpdate = conn.prepareStatement(sql);
								pstmtUpdate.setString(1, loginEmpCode);
								pstmtUpdate.setTimestamp(2, Timestamp.valueOf( confDateStr ) ); 
								pstmtUpdate.setString(3, tranType);
								pstmtUpdate.setString(4, tranIdPurcOrder);
								updCnt = pstmtUpdate.executeUpdate();
								pstmtUpdate.close(); pstmtUpdate = null;
								System.out.println("updated records in PORDER : "+updCnt);
							// Changed by sankara on 12-08-13 for updation pord_type against generated purchase order WM3ESUN007 end..
							
	
							errString = "";//Gulzar - 25/11/11
							
							// 16/10/11 manoharan connection passed as parameter
							//conn.commit();
							// end 16/10/11 manoharan connection passed as parameter
						}
						/*
						////////////////////// EDI creation
						String ediOption = "";
						String dataStr = "";
						sql = "SELECT EDI_OPTION FROM TRANSETUP WHERE TRAN_WINDOW = 'w_asn' ";
						pstmtSql = conn.prepareStatement(sql);
						rs = pstmtSql.executeQuery();
						if ( rs.next() )
						{
							ediOption = checkNull(rs.getString("EDI_OPTION"));
						}
						rs.close();rs = null;
						pstmtSql.close();pstmtSql = null;

						if ( "1".equals(ediOption.trim()) )
						{
							CreateRCPXML createRCPXML = new CreateRCPXML("w_asn","tran_id");
							dataStr = createRCPXML.getTranXML( tranId, conn );
							System.out.println( "dataStr =[ "+ dataStr + "]" );
							Document ediDataDom = genericUtility.parseString(dataStr);

							E12CreateBatchLoadEjb e12CreateBatchLoad = new E12CreateBatchLoadEjb();
							retString = e12CreateBatchLoad.createBatchLoad( ediDataDom, "w_porcp", "0", xtraParams, conn );
							createRCPXML = null;
							e12CreateBatchLoad = null;

							if( retString != null && "SUCCESS".equals(retString) )
							{
								System.out.println("retString from batchload = ["+retString+"]");
							}
						}
						/////////////////////

						if( connStatus )//Condition added - 25/11/11 - Gulzar as confirm method is called from post save component
						{
							conn.commit();
							retString = itmDBAccessLocal.getErrorString("","VTMCONF20","");
						}
						*/
					}
				}
			}
			else
			{
				errString = itmdbAccess.getErrorString("","UNCONFDASN",userId);
				return errString;
			}
		}
		catch(Exception e)
		{
			isError = true;
			// 16/10/11 manoharan connection passed as parameter
			errString = "ERROR";
			// end 16/10/11 manoharan connection passed as parameter
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				
				// 16/10/11 manoharan connection passed as parameter
				//if ( !(isError) && retString.indexOf("Success") != -1 )
				//{
				//	System.out.println("Commiting and Closing Connection in generatePurcOrder..........");
				//	//conn.commit();
				//	errString = itmdbAccess.getErrorString("","PORCREATED",userId);
				//}
				//else
				//{
				//	conn.rollback();
				//}
				// end 16/10/11 manoharan connection passed as parameter
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				// 16/10/11 manoharan connection passed as parameter
				//if( conn != null && ! conn.isClosed() )
				//{
				//	conn.close();
				//	conn = null;
				//}
				// end 16/10/11 manoharan connection passed as parameter
			}
			catch( Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		System.out.println("errString from generatePorder =["+errString+"]");
		return errString;
	}
	
	@Override
	public String generatePurcReceipt(String tranIdAsnHdr, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("Generating Purchase receipt");
		boolean isError = false;
		int lineNo = 0;
		double quantity = 0;
		String confirmed = "";
		String purcOrder = "";
		String itemCode = "";
		String siteCode = "";
		String suppCode = "";
		String unit = "";
		String status = "";
		String sysDateStr = "";
		String tranIdPurcOrder = "";
		String invoiceNo = "";
		String asnNo = "";
		String tranCode = "";
		String asnDate = "";
		String remarks = "";
		String currCodeBase = "";
		String expDate = "";
		String expDateStr = "";
		String lotNo = "";
		String loginEmpCode = "";
		String lrNo = "";
		String currCode = "";
		String itemSer = "";
		//changed by sankara on 12/08/13 added tran_type for WM3ESUN007
		String orderType = "";
		java.sql.Date asnDateDb = null;
		java.sql.Timestamp expDateDb = null;
		java.sql.Timestamp mfgDate = null;
		int selfLife = 0;
		double shipperSize = 0d, grossWeight = 0d, netWeight = 0d, tareWeight = 0d;
		double exchRate = 0d, noArt = 0d, rate = 0d, netAmt = 0d, frtAmt = 0d;
		double rateClg = 0d;
		
		String sql = "";
		
		PreparedStatement pstmtItemLotPack = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		ResultSet rsItemLotPack = null ;
		Connection conn = null;
		String errString = "";
		String loginSite = "";
		String userId = "";
		String chgTerm = "";
		String retString = "";

		MasterStatefulLocal masterStatefulLocal = null;
		
		ITMDBAccessEJB itmdbAccess = new ITMDBAccessEJB();

		FinCommon finCommon = new FinCommon();
		DistCommon distComm = new DistCommon();
		try
		{	
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);

			GenericUtility genericUtility = GenericUtility.getInstance();
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode"));
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			conn.setAutoCommit(false);
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateTimeFormat());
			Date sysDate = new Date();
			sysDateStr = sdf.format(sysDate);
			String [] authencate = new String[2];
            authencate[0] = "";
            authencate[1] = "";
			System.out.println("confDate is :"+sysDate+" confDate str is : "+sysDateStr);

			sql = "SELECT PURC_ORDER, INVOICE_NO, ASN_DATE, ASN_NO, TRAN_CODE, LR_NO FROM ASN_HDR WHERE TRAN_ID = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranIdAsnHdr );
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				purcOrder = checkNull( rs.getString("PURC_ORDER") );
				invoiceNo = checkNull( rs.getString("INVOICE_NO") );
				asnDateDb = rs.getDate("ASN_DATE");
				asnNo = checkNull( rs.getString("ASN_NO") );
				tranCode = checkNull( rs.getString("TRAN_CODE") );
				lrNo = checkNull( rs.getString("LR_NO") );

				asnDate = sdf.format(asnDateDb);
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( purcOrder == null || purcOrder.trim().length() == 0 )
			{
				errString = itmdbAccess.getErrorString("","NULLPORDER",userId);
				return errString;
			}
		// Changed by sankara on 12/08/13 added pord_type for updartion of purchase receipt WM3ESUN007	
		//	sql = "SELECT STATUS, CONFIRMED, SITE_CODE__BILL, SUPP_CODE, ITEM_SER, FRT_AMT FROM PORDER WHERE PURC_ORDER = ? ";
			sql = " SELECT STATUS, CONFIRMED, SITE_CODE__BILL, SUPP_CODE, ITEM_SER, FRT_AMT, PORD_TYPE  FROM PORDER WHERE PURC_ORDER = ? ";
			pstmt = conn.prepareStatement( sql );
			pstmt.setString(1, purcOrder );
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				status = checkNull( rs.getString("STATUS") );
				confirmed = checkNull( rs.getString("CONFIRMED") );
				siteCode = checkNull( rs.getString("SITE_CODE__BILL") );
				suppCode = checkNull( rs.getString("SUPP_CODE") );
				itemSer = checkNull( rs.getString("ITEM_SER") );
				frtAmt = rs.getDouble("FRT_AMT") ;
				status = checkNull( rs.getString("STATUS") );
				// Changed by sankara on 12/08/13 for updartion of purchase receipt WM3ESUN007	
				orderType =  checkNull( rs.getString("PORD_TYPE") );
				System.out.println("ORDERTYPE==="+orderType);
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( !"Y".equalsIgnoreCase( confirmed ) )
			{
				errString = itmdbAccess.getErrorString("","UNCONFPORED",userId);
				return errString;
			}
			if( !"O".equalsIgnoreCase( status ) )
			{
				errString = itmdbAccess.getErrorString("","CLSEDPORED",userId);
				return errString;
			}
			if( "Y".equalsIgnoreCase( confirmed ) && "O".equalsIgnoreCase( status ) )
			{ 
				remarks = "AGAINST ASN NO : " + asnNo;
				sql = "SELECT CURR_CODE FROM SUPPLIER WHERE SUPP_CODE = ? ";
				pstmt = conn.prepareStatement( sql );
				pstmt.setString(1, suppCode );
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
					currCode = checkNull( rs.getString("CURR_CODE") );
				}
				rs.close();rs = null;
				pstmt.close();pstmt = null;

				sql = "SELECT A.CURR_CODE FROM FINENT A, SITE B WHERE B.FIN_ENTITY = A.FIN_ENTITY AND B.SITE_CODE = ? ";
				pstmt = conn.prepareStatement( sql );
				pstmt.setString(1, loginSite );
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
					currCodeBase = checkNull( rs.getString("CURR_CODE") );
				}
				rs.close();rs = null;
				pstmt.close();pstmt = null;

				exchRate = finCommon.getDailyExchRateSellBuy(currCode.trim(),"",loginSite.trim(),sysDateStr.trim(),"B", conn);

				StringBuffer xmlString= new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
				xmlString.append("<DocumentRoot><description>Datawindow Root</description><group0><description>Group0 escription</description>");
				xmlString.append("<Header0>");
				xmlString.append("<description>Header0 members</description>");
				xmlString.append("<objName><![CDATA[").append("porcp").append("]]></objName>");
				xmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				xmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				xmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				xmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				xmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				xmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				xmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				xmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				xmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				xmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
				xmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");

				xmlString.append("<Detail1 dbID='' domID=\"1\" objName=\"porcp\" objContext=\"1\">");
				xmlString.append("<attribute pkNames=\"tran_id:\" status=\"N\" updateFlag=\"A\" selected=\"N\" />");
				xmlString.append("<tran_id><![CDATA[").append("").append("]]></tran_id>");
				xmlString.append("<tran_date><![CDATA[").append(sysDateStr).append("]]></tran_date>");
				xmlString.append("<eff_date><![CDATA[").append(sysDateStr).append("]]></eff_date>");
			//  Changed by sankara on 12/08/13 for set tran type  in purchase receipt Start WM3ESUN007..
				xmlString.append("<tran_type><![CDATA[").append(orderType).append("]]></tran_type>");
			//  Changed by sankara on 12/08/13 for set tran type  in purchase receipt End WM3ESUN007..	
				xmlString.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
				xmlString.append("<supp_code><![CDATA[").append(suppCode).append("]]></supp_code>");
				xmlString.append("<supp_code__ship><![CDATA[").append(suppCode).append("]]></supp_code__ship>");
				xmlString.append("<purc_order><![CDATA[").append(purcOrder).append("]]></purc_order>");
				xmlString.append("<dc_no><![CDATA[").append(invoiceNo).append("]]></dc_no>");
				xmlString.append("<invoice_no><![CDATA[").append(invoiceNo).append("]]></invoice_no>");
			//  changed by sankara on 26/09/13 for set Invoice Date start.
				xmlString.append("<invoice_date><![CDATA[").append(asnDate).append("]]></invoice_date>");
			//  changed by sankara on 26/09/13 for set Invoice Date end.	
				xmlString.append("<dc_date><![CDATA[").append(asnDate).append("]]></dc_date>");
				xmlString.append("<tran_code><![CDATA[").append(tranCode).append("]]></tran_code>");
				xmlString.append("<asn_no><![CDATA[").append(asnNo).append("]]></asn_no>");
				xmlString.append("<discount><![CDATA[").append("0").append("]]></discount>");
				xmlString.append("<frt_rate><![CDATA[0]]></frt_rate>");//Added By Mahesh Patidar on 04/07/12
				xmlString.append("<adj_amt><![CDATA[").append("0").append("]]></adj_amt>");
				xmlString.append("<curr_code><![CDATA[").append(currCode).append("]]></curr_code>");
				xmlString.append("<tran_ser><![CDATA[").append("P-RCP").append("]]></tran_ser>");
				xmlString.append("<tax_date><![CDATA[").append(sysDateStr).append("]]></tax_date>");
				xmlString.append("<rec_date><![CDATA[").append(sysDateStr).append("]]></rec_date>");
				xmlString.append("<confirmed><![CDATA[").append("N").append("]]></confirmed>");
				xmlString.append("<remarks><![CDATA[").append(remarks).append("]]></remarks>");
				xmlString.append("<vouch_created><![CDATA[").append("N").append("]]></vouch_created>");
				xmlString.append("<lr_no><![CDATA[").append( lrNo ).append("]]></lr_no>");
				xmlString.append("<lr_date><![CDATA[").append( sysDateStr ).append("]]></lr_date>");
				xmlString.append("<emp_code><![CDATA[").append( loginEmpCode ).append("]]></emp_code>");
				//xmlString.append("<status><![CDATA[").append( status ).append("]]></status>");//Changed By Mahesh Patidar on 04/07/12
				xmlString.append("<status><![CDATA[O]]></status>");//Added By Mahesh patidar on 04/07/12
				xmlString.append("<exch_rate><![CDATA[").append( exchRate ).append("]]></exch_rate>");
				xmlString.append("<curr_code__clr><![CDATA[").append( currCodeBase ).append("]]></curr_code__clr>");
				xmlString.append("<curr_code__ins><![CDATA[").append( currCodeBase ).append("]]></curr_code__ins>");
				xmlString.append("<curr_code__frt><![CDATA[").append( currCodeBase ).append("]]></curr_code__frt>");
				xmlString.append("<exch_rate__clr><![CDATA[").append( exchRate ).append("]]></exch_rate__clr>");
				xmlString.append("<exch_rate__ins><![CDATA[").append( exchRate ).append("]]></exch_rate__ins>");
				xmlString.append("<exch_rate__frt><![CDATA[").append( exchRate ).append("]]></exch_rate__frt>");
				xmlString.append("<item_ser><![CDATA[").append( itemSer ).append("]]></item_ser>");
				xmlString.append("<frt_amt><![CDATA[").append( frtAmt ).append("]]></frt_amt>");
				xmlString.append("<chg_date/>");
				xmlString.append("<chg_user/>");
				xmlString.append("<chg_term/>");
				xmlString.append("</Detail1>");

				sql  = "SELECT SHIPPER_SIZE, GROSS_WEIGHT, NET_WEIGHT FROM ITEM_LOT_PACKSIZE WHERE ITEM_CODE = ? AND LOT_NO__FROM <= ? AND LOT_NO__TO >= ? ";
				pstmtItemLotPack = conn.prepareStatement(sql);

				sql = 	"SELECT PDET.LINE_NO, PDET.ITEM_CODE, PDET.QUANTITY, PDET.UNIT, PDET.RATE, "+
						"PDET.DISCOUNT, PDET.TAX_AMT, PDET.TOT_AMT, PDET.LOC_CODE,  "+
						"PDET.REQ_DATE, PDET.DLV_QTY, PDET.STATUS, PDET.STATUS_DATE,  "+
						"PDET.UNIT__RATE, PDET.CONV__QTY_STDUOM, PDET.CONV__RTUOM_STDUOM,   "+
						"PDET.UNIT__STD, PDET.QUANTITY__STDUOM, PDET.RATE__STDUOM,   "+
						"PDET.NO_ART, PDET.ACCT_CODE__DR, PDET.CCTR_CODE__DR, PDET.ACCT_CODE__CR,   "+
						"PDET.CCTR_CODE__CR, PDET.RATE__CLG, PDET.STD_RATE, ADET.LOT_NO, ADET.EXP_DATE,   "+
						"ITEM.CANC_BO_MODE, ITEM.SHELF_LIFE , PDET.RATE__CLG "+
						"FROM PORDDET PDET, ASN_DET ADET, ITEM ITEM, ASN_HDR ASN_HDR  "+
						"WHERE ASN_HDR.PURC_ORDER =  PDET.PURC_ORDER  "+
						"AND ASN_HDR.TRAN_ID = ADET.TRAN_ID  "+
						"AND PDET.PURC_ORDER = ?  "+
						"AND PDET.LINE_NO = ADET.LINE_NO__ORD   "+
						"AND PDET.ITEM_CODE = ITEM.ITEM_CODE  ";

				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, purcOrder);
				rs = pstmt.executeQuery();
				int domID = 0;
				String lineNoRcp = "";
				String lineNoOrd = "";
				while( rs.next())
				{
					domID++;
					lineNoOrd = rs.getString("LINE_NO");
					itemCode = rs.getString("ITEM_CODE");
					quantity = rs.getDouble("QUANTITY");
					unit = rs.getString("UNIT");
					rate = rs.getDouble("RATE");
					expDateDb = rs.getTimestamp("EXP_DATE");
					selfLife = rs.getInt("SHELF_LIFE");
					lotNo = rs.getString("LOT_NO");
					rateClg = rs.getDouble("RATE__CLG");
					if ( expDateDb != null )
					{
						expDate = sdf.format(expDateDb);
					}
					mfgDate = distComm.CalcExpiry( expDateDb, ((-1)*selfLife) );
					if ( mfgDate != null )
					{
						expDateStr = sdf.format(mfgDate);
					}
					netAmt = (quantity * rate);

					pstmtItemLotPack.setString(1, itemCode);
					pstmtItemLotPack.setString(2, lotNo);
					pstmtItemLotPack.setString(3, lotNo);
					rsItemLotPack = pstmtItemLotPack.executeQuery();
					if ( rsItemLotPack.next() )
					{
						shipperSize =  rsItemLotPack.getDouble("SHIPPER_SIZE");
						grossWeight =  rsItemLotPack.getDouble("GROSS_WEIGHT");
						netWeight =  rsItemLotPack.getDouble("NET_WEIGHT");
						tareWeight = grossWeight - netWeight;
						if ( shipperSize > 0 )
						{
							noArt = (int)(quantity / shipperSize);
						}
					}
					rsItemLotPack.close();
					rsItemLotPack = null;
					pstmtItemLotPack.clearParameters();

					lineNoRcp = "   " + domID;
					lineNoRcp = lineNoRcp.substring( lineNoRcp.length()-3 );

					xmlString.append("<Detail2 dbID=':' domID='1' objName='porcp' objContext='2'>");
					xmlString.append("<attribute pkNames='tran_id:line_no:' status='N' updateFlag='A' selected='N'/>");
					xmlString.append("<tran_id/>");
					xmlString.append("<line_no><![CDATA[").append(lineNoRcp).append("]]></line_no>");
					xmlString.append("<purc_order><![CDATA[").append(purcOrder).append("]]></purc_order>");
					xmlString.append("<line_no__ord><![CDATA[").append(lineNoOrd).append("]]></line_no__ord>");	 
					xmlString.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
					xmlString.append("<quantity><![CDATA[").append(quantity).append("]]></quantity>");
					xmlString.append("<unit><![CDATA[").append(unit).append("]]></unit>");
					xmlString.append("<rate><![CDATA[").append(rs.getDouble("RATE")).append("]]></rate>");
					xmlString.append("<std_rate><![CDATA[").append(rs.getDouble("RATE")).append("]]></std_rate>");
					xmlString.append("<discount><![CDATA[").append(rs.getDouble("DISCOUNT")).append("]]></discount>");
					xmlString.append("<tax_amt><![CDATA[").append(rs.getDouble("TAX_AMT")).append("]]></tax_amt>");
					xmlString.append("<net_amt><![CDATA[").append(netAmt).append("]]></net_amt>");
					xmlString.append("<loc_code><![CDATA[").append( checkNull(rs.getString("LOC_CODE")) ).append("]]></loc_code>");
					xmlString.append("<lot_no><![CDATA[").append( checkNull(rs.getString("LOT_NO")) ).append("]]></lot_no>");
					xmlString.append("<canc_bo><![CDATA[").append( checkNull(rs.getString("CANC_BO_MODE")) ).append("]]></canc_bo>");
					xmlString.append("<vouch_qty><![CDATA[").append( "0" ).append("]]></vouch_qty>");
					xmlString.append("<acct_code__dr><![CDATA[").append( checkNull(rs.getString("ACCT_CODE__DR")) ).append("]]></acct_code__dr>");
					xmlString.append("<cctr_code__dr><![CDATA[").append( checkNull(rs.getString("CCTR_CODE__DR")) ).append("]]></cctr_code__dr>");
					xmlString.append("<acct_code__cr><![CDATA[").append( checkNull(rs.getString("ACCT_CODE__CR")) ).append("]]></acct_code__cr>");
					xmlString.append("<cctr_code__cr><![CDATA[").append( checkNull(rs.getString("CCTR_CODE__CR")) ).append("]]></cctr_code__cr>");
					xmlString.append("<unit__rate><![CDATA[").append( checkNull(rs.getString("UNIT__RATE")) ).append("]]></unit__rate>");
					xmlString.append("<conv__qty_stduom><![CDATA[").append( checkNull(rs.getString("CONV__QTY_STDUOM")) ).append("]]></conv__qty_stduom>");
					xmlString.append("<conv__rtuom_stduom><![CDATA[").append( checkNull(rs.getString("CONV__RTUOM_STDUOM")) ).append("]]></conv__rtuom_stduom>");
					xmlString.append("<unit__std><![CDATA[").append( checkNull(rs.getString("UNIT__STD")) ).append("]]></unit__std>");
					xmlString.append("<quantity__stduom><![CDATA[").append( checkNull(rs.getString("QUANTITY__STDUOM")) ).append("]]></quantity__stduom>");
					xmlString.append("<rate__stduom><![CDATA[").append( checkNull(rs.getString("RATE__STDUOM")) ).append("]]></rate__stduom>");
					xmlString.append("<no_art><![CDATA[").append( noArt ).append("]]></no_art>");
					xmlString.append("<batch_no><![CDATA[").append( checkNull(rs.getString("LOT_NO")) ).append("]]></batch_no>");
					xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
					xmlString.append("<potency_perc><![CDATA[").append("0").append("]]></potency_perc>");
					xmlString.append("<challan_qty><![CDATA[").append(quantity).append("]]></challan_qty>");
					xmlString.append("<supp_challan_qty><![CDATA[").append(quantity).append("]]></supp_challan_qty>");
					xmlString.append("<realised_qty><![CDATA[").append(quantity).append("]]></realised_qty>");
					xmlString.append("<excess_short_qty><![CDATA[").append("0").append("]]></excess_short_qty>");
					xmlString.append("<additional_cost><![CDATA[").append("0").append("]]></additional_cost>");
					xmlString.append("<rate__clg><![CDATA[").append(rateClg).append("]]></rate__clg>");//Added By Mahesh Patidar on 03/07/12
					//xmlString.append("<rate__clg><![CDATA[").append("0").append("]]></rate__clg>");//Commented By Mahesh Patidar on 03/07/12
					xmlString.append("<effect_stock><![CDATA[").append("Y").append("]]></effect_stock>");
					xmlString.append("<retest_date><![CDATA[").append(expDate).append("]]></retest_date>");
					xmlString.append("<expiry_date><![CDATA[").append(expDate).append("]]></expiry_date>");
					xmlString.append("<mfg_date><![CDATA[").append(expDateStr).append("]]></mfg_date>");
					xmlString.append("<gross_weight><![CDATA[").append(grossWeight * noArt).append("]]></gross_weight>");
					xmlString.append("<tare_weight><![CDATA[").append(tareWeight * noArt).append("]]></tare_weight>");
					xmlString.append("<net_weight><![CDATA[").append(netWeight * noArt).append("]]></net_weight>");
					xmlString.append("</Detail2>");
				}
				pstmtItemLotPack.close();
				pstmtItemLotPack = null;
				xmlString.append("</Header0></group0></DocumentRoot>");
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				System.out.println("xmlString..in generatePurcReceipt: "+xmlString.toString() );
				
				masterStatefulLocal = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local"); 
				retString = masterStatefulLocal.processRequest( authencate, siteCode, true, xmlString.toString()); 

				System.out.println("retString..in generatePurcReceipt: "+retString);
			}
		}
		catch(Exception e)
		{
			isError = true;
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Commiting and Closing Connection in generatePurcReceipt..........");
				if ( !(isError) && retString.indexOf("Success") != -1 )
				{
					conn.commit();
					errString = itmdbAccess.getErrorString("","PRPTCRETED",userId);
				}
				else
				{
					conn.rollback();
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}

	private String checkNull(String input)
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	public static java.util.Date addDays(java.util.Date date, int days) //added by Kunal on 01/09/12 
	{
		java.sql.Date calculatedDate = null;
		if (date != null) 
		{
			final GregorianCalendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(Calendar.DATE,days);
			calculatedDate = new java.sql.Date(calendar.getTime().getTime());
		}

		return calculatedDate;
	}
	//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code.start
	private  String getError(String tranID,String lineNo,String itemCode,String Code,Connection conn)  throws ITMException, Exception
    {
        String mainStr ="";
        
        try
        {
        	String errString = "";
        	errString =  new ITMDBAccessEJB().getErrorString("",Code,"","",conn);
			String begPart = errString.substring(0,errString.indexOf("<message>")+9);
			String endDesc = errString.substring(errString.indexOf("</description>"));
			mainStr= begPart+"Invalid Data "+"</message><description>";
			mainStr= mainStr+"Tran ID: ["+tranID+"] Line No: ["+lineNo+"] Item Code: ["+itemCode+"]" +endDesc;
			System.out.println("mainStr:::::::::::::::::: "+mainStr);
			begPart = null;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new ITMException(e);
        }
        return mainStr;
    }
	//Changed by Rohan on 11-07-13 for generate erraor with asn no,line no and item code.end
}
