package ibase.webitm.ejb.mfg;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import org.w3c.dom.*;
import java.util.Calendar;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class WOMultiReceipt extends ValidatorEJB implements  WOMultiReceiptLocal,  WOMultiReceiptRemote //SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException
    {
        System.out.println("WOMultiReceiptEJB is Creating..........");
    }
    public void ejbRemove()
    {
        System.out.println("WOMultiReceiptEJB is Removing..........");
    }
    public void ejbActivate()
    {
        System.out.println("WOMultiReceiptEJB is Activating..........");
    }
    public void ejbPassivate()
    {	
        System.out.println("WOMultiReceiptEJB is Passivating..........");
    }*/
    public String wfValData()throws RemoteException, ITMException
    {
        return "";
    }
    public String itemChanged()throws RemoteException, ITMException
    {
        return "";
    }
    public String postSaveRec()throws RemoteException,ITMException
	{
		return "";
	}
    
    public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
    {
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;	
		String errString = "";
		System.out.println("***********************Validation Start MPSOrder**************************");
		try
		{
			System.out.println("xmlString:::"+xmlString);
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);			
		}
		catch(Exception e)
		{
			System.out.println("Exception : MPSOrder : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
    }
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr=0;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		String childNodeName = null;
		String errString = "";
		String errCode = "";
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null,pstmt1 = null;
		ResultSet rs = null,rs1 = null;
		String sql = "";
		String userId = ""; 		
		java.util.Date orderDate = null, dueDate = null,mfg_date=null,tran_date=null,date_start =null,expDate=null,tranDate=null,dateStart=null,dateCompl=null ;
		String itemCode = null;		
		String siteCode = null;
		String childNodeValue = null ;
		int cnt = 0;
		String saleOrder =  null, lineNo = null, tranId = null, bomCode = null,confirmed = null, active = null ; 
		String workOrder = null, temp = null, cctrCodeWp = null,routeCode = null, unit = null, status = null;
		String mfgType = null ;
		double quantity = 0, qtyRecived = 0, qtyWorkOrder = 0, qtyMpsOrder = 0, qtySordDet = 0,currentBatchQty=0;
		double	minBatchQty = 0;
		double	maxBatchQty = 0,std_qty=0;
		int currentFormNo=0;
		int childNodeListLength,lineLength=0;
		String loginSite = "",operation="",locCode ="";
		String tranType="",modName="" ;
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			stmt = conn.createStatement();
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			GenericUtility genericUtility = GenericUtility.getInstance(); 
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println(" ***********Validation for  - Detail  "+currentFormNo);
			switch(currentFormNo)
			{
				case 1 :
					System.out.println("Validation for Detail 1 WOMultiReceiptEJB..........");
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
				    childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{	
						
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNode.getFirstChild()!= null)
						{
							childNodeValue = childNode.getFirstChild().getNodeValue();
						}
						if(childNodeName.equalsIgnoreCase("tran_date"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							String ordDate = genericUtility.getColumnValue("tran_date", dom);
							orderDate = sdf.parse(ordDate);
							siteCode = genericUtility.getColumnValue("site_code", dom);
							errCode = nfCheckPeriod("PUR", orderDate, siteCode);
							if(errCode != null && errCode.trim().length() != 0)
							{
								errString = getErrorString("tran_date",errCode,userId);
								break ;
							}	
						}
//						if(childNodeName.equalsIgnoreCase("item_code"))
//						{
//							   
//							System.out.println(" Validaion   for field "+childNodeName);
//							itemCode = genericUtility.getColumnValue("item_code", dom);
//							siteCode = genericUtility.getColumnValue("site_code", dom);
//							workOrder = genericUtility.getColumnValue("work_order", dom);
//							operation  = genericUtility.getColumnValue("operation", dom);
//							tranId = genericUtility.getColumnValue("tran_id", dom);
//							tranId = tranId == null ? "" : tranId ;
//							 tranType = genericUtility.getColumnValue("tran_type", dom);
//								//public String isItem(String siteCode, String itemCode, String modName,Connection conn)
//							//errCode = nfCheckPeriod(siteCode, itemCode,modName ,conn);	 ////////modname
//							if(errCode != null && errCode.trim().length() != 0)
//							{
//								errString = getErrorString("item_code",errCode,userId);
//								break ;
//							}
//							
//							
//						}
								
						if(childNodeName.equalsIgnoreCase("unit"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							unit = genericUtility.getColumnValue("unit", dom);
							if(unit == null || unit.trim().length() == 0)
							{
								errCode = "VMUNIT1";
								errString = itmDBAccessEJB.getErrorString("","VMUNIT1","BASE","",conn);
								break ;
							}
							else
							{
								cnt = isValueExist("uom", "unit",unit, conn);
								if(cnt == 0)
								{
									errCode = "VMROUTE1";
									errString = itmDBAccessEJB.getErrorString("","VMROUTE1","BASE","",conn);
									break ;
								}
							}
						}
						if(childNodeName.equalsIgnoreCase("item_code"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							itemCode = genericUtility.getColumnValue("item_code", dom);
							
								cnt = isValueExist("item", "item_code",itemCode, conn);
								if(cnt == 0)
								{
									errCode = "VMITEM1";
									errString = itmDBAccessEJB.getErrorString("","VMITEM1","BASE","",conn);
									break ;
								}
							
						}
						if(childNodeName.equalsIgnoreCase("work_order"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							workOrder = genericUtility.getColumnValue("work_order", dom);
							int count=0;
								cnt = isValueExist("workorder", "work_order",workOrder, conn);
								if(cnt == 0)
								{
									errCode = "VTWORDER7";
									errString = itmDBAccessEJB.getErrorString("","VTWORDER7","BASE","",conn);
									break ;
								}
								//count=0;
//								sql ="select count(*)  from workorder_receipt where work_order ='"+workOrder+"' and "
//								      +" confirmed ='Y' "; 
//									System.out.println("sql-------------"+sql);
//
//									pstmt =  conn.prepareStatement(sql);
//									rs = pstmt.executeQuery();
//									if(rs.next())
//									{
//										count=rs.getInt(1);
//										
//									}
//									rs.close();
//									pstmt.close();
//									System.out.println("count-------------"+count);
//
//									if(count != 0)
//									{
//										errCode = "VTWOCONF";
//										errString = itmDBAccessEJB.getErrorString("","VTWOCONF","BASE");
//										break ;
//									}
							
						}
						if(childNodeName.equalsIgnoreCase("loc_code"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							locCode = genericUtility.getColumnValue("loc_code", dom);
							
								cnt = isValueExist("location", "loc_code",locCode, conn);
								if(cnt == 0)
								{
									errCode = "VMLOCGRCON";
									errString = itmDBAccessEJB.getErrorString("","VMLOCGRCON","BASE","",conn);
									break ;
								}
							
						}
						if(childNodeName.equalsIgnoreCase("exp_date"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							expDate = getDateObject(genericUtility.getColumnValue("exp_date",dom));
							tranDate = getDateObject(genericUtility.getColumnValue("tran_date",dom));
							if(expDate!=null)
							{
								if( expDate.before(tranDate) )
								{
									System.out.println(" expDate..................... "+expDate);
									errCode = "VTEXPDT";
									errString  = getErrorString("exp_date",errCode,userId);
									break ;
								}
							}
						}
						if(childNodeName.equalsIgnoreCase("date__compl"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							dateStart = getDateObject(genericUtility.getColumnValue("date__start",dom));
							dateCompl = getDateObject(genericUtility.getColumnValue("date__compl",dom));
//							if( dateCompl == null  )
//							{
//								errCode = "VTCOMPLDT";
//								//ls_errcode = gf_error_location(ls_errcode)
//								errString  = getErrorString("date__compl",errCode,userId);
//								break ;
//							}
						    if(dateCompl!=null && dateStart!=null)
							{
								if( dateCompl.before(dateStart))
								{
									errCode = "VTCOMPLDT";
									//ls_errcode = gf_error_location(ls_errcode)
									errString  = getErrorString("date__compl",errCode,userId);
									break ;
								}
							}
						}	
						if(childNodeName.equalsIgnoreCase("date_start"))
						{
							System.out.println(" Validaion   for field "+childNodeName);
							date_start = getDateObject(genericUtility.getColumnValue("date_start",dom));
							//mfg_date = getDateObject(genericUtility.getColumnValue("mfg_date",dom));
							if( date_start == null  )
							{
								errCode = "INVSTRDT";
								//ls_errcode = gf_error_location(ls_errcode)
								errString  = getErrorString("date_start",errCode,userId);
								break ;
							}
							
						}	
				
						
					}break;    //END FOR		
				case 2 :
						
					System.out.println("Validation for Detail 2 ..........");
					parentNodeList = dom.getElementsByTagName("Detail2");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						cnt = 0;
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNode.getFirstChild()!= null)
						{
							childNodeValue = childNode.getFirstChild().getNodeValue();
						}
						
						if(childNodeName.equalsIgnoreCase("item_code"))
						{
							System.out.println(" Validaion   for field "+childNodeName);		 
							cnt = isValueExist("item", "item_code", childNodeValue, conn);
							if(cnt == 0)
							{
								errCode = "VMITEM1";
								errString = itmDBAccessEJB.getErrorString("","VMITEM1","BASE","",conn);
								break;								
							}
						}
						if(childNodeName.equalsIgnoreCase("pack_code"))
						{
							System.out.println(" Validaion   for field "+childNodeName);		 
							cnt = isValueExist("packing", "pack_code", childNodeValue, conn);
							if(cnt == 0)
							{
								errCode = "VTPKCD1";
								errString = itmDBAccessEJB.getErrorString("","VTPKCD1","BASE","",conn);
								break;								
							}
						}
					}//END FOR
					break;			
			}//END SWITCH
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
			System.out.println(" MPSOrder Validation End and Connection is Closed");
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}//END OF VALIDATION 	

  public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
  {
	  Document dom = null;
	  Document dom1 = null;
	  Document dom2 = null;
	  String valueXmlString = "";
	  try
	  {
		  dom = parseString(xmlString); 
		  System.out.println("xmlString" + xmlString);
		  dom1 = parseString(xmlString1); 
		  if(xmlString2.trim().length() > 0 )
		  {
			  dom2 = parseString(xmlString2);
		  }
		  valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
	  }
	  catch(Exception e)
	  {
		  System.out.println("Exception : [MPSOrder][itemChanged(String,String)] :==>\n"+e.getMessage());
	  }
	  return valueXmlString; 
  }

  public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
  {		
			StringBuffer valueXmlString = new StringBuffer();
			NodeList parentNodeList = null;
			NodeList childNodeList = null;
			Node parentNode = null;
			Node childNode = null;
			int ctr=0;
			String columnValue = null;
			String childNodeName = null;
			String errString = "";
			String errCode = "";
			Connection conn = null;
			Statement stmt = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String sql = "";
			String userId = ""; 
			String itemCode = "";	
			String siteCode = "";
			double yieldPerc = 0,currentBatchQty=0 ;
			java.util.Date orderDate = null,rdate=null;
			String loginSite = "";
			String itemDescr = "", unit = "", siteDescr = "" ;		
			int currentFormNo=0;
			int childNodeListLength,shelf_life=0;
			boolean flag = false;					  
			int k = 0,opr=0;
			java.util.Date  currDate = new  java.util.Date();
			String packCode ="",packDescr="",grossWeight="",tareWeight="";
			String tranId="",ls_loc="",ordDate = "",tranDate="",startDate ="",startDate1="",startDate2="",startDate3="";
			String qcReqd ="",workOrder ="",var_value="",tranType="",feedbackReqd="",tranIdMps="",refNo="",unitStd="";
			double quantity=0,quantityMps=0,netweight=0,grossWeightNbr =0,tareWeightNbr=0,sum_quantity=0,potency_perc=0;
			String fname="",lname="",mname="";
			String locCode="",site_code__own="",item_ser="",descr="",mfg_date_on="",track_shelf_life="";
			Timestamp relDate =null,expDate=null,mfgDateStart=null;
			GenericUtility genericUtility = GenericUtility.getInstance();
			try
			{	
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());    
				ConnDriver conndriver = new ConnDriver();
				conn = conndriver.getConnectDB("DriverITM");
				loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
				//tranDate = sdf.format(currDate);
				if(objContext != null && objContext.trim().length() > 0)
				k = Integer.parseInt(objContext);
				System.out.println("FORM NO:::" + k);
				valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
				valueXmlString.append(editFlag).append("</editFlag></header>");
				System.out.println("****************ITEMCHANGE FOR CASE"+k+"*******************");
				switch(k)
				{
					case 1 :																	
							parentNodeList = dom.getElementsByTagName("Detail1");
							parentNode = parentNodeList.item(0);
							childNodeList = parentNode.getChildNodes();
							ctr = 0;
							valueXmlString.append("<Detail1>");
							childNodeListLength = childNodeList.getLength();
							do
							{
								childNode = childNodeList.item(ctr);
								childNodeName = childNode.getNodeName();
								if(childNodeName.equals(currentColumn))
								{
									if (childNode.getFirstChild() != null)
									{
										columnValue=childNode.getFirstChild().getNodeValue().trim();
									}
								}
								ctr++;
							}
							while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
							if (currentColumn.trim().equals("itm_defaultedit"))
							{		
								workOrder = genericUtility.getColumnValue("work_order", dom);
								sql ="select sum(nvl(quantity,0)) from workorder_receipt where work_order ='"+workOrder+"' and "
								      +" tran_type ='F' "; 
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										sum_quantity=  rs.getDouble(1);
										
									}
									rs.close();
									pstmt.close();
								valueXmlString.append("<c_crevqty>").append("<![CDATA[" + sum_quantity+ "]]>").append("</c_crevqty>");	
								tranType = genericUtility.getColumnValue("tran_type", dom);
								if(tranType.equalsIgnoreCase("B"))
								{
								}
								if(tranType.equalsIgnoreCase("F"))
								{
									valueXmlString.append("<operation protect=\"1\"></operation>\r\n");	
								}		
							}
							if(currentColumn.trim().equalsIgnoreCase("itm_default"))
							{
								tranDate = getCurrdateAppFormat();
								siteDescr = getFieldValue("descr", "site", "site_code",loginSite, conn);
								siteDescr = siteDescr == null ? "" : siteDescr ;
								valueXmlString.append("<tran_date>").append("<![CDATA[" + tranDate + "]]>").append("</tran_date>");							
								valueXmlString.append("<site_code>").append("<![CDATA[" + loginSite + "]]>").append("</site_code>");
								valueXmlString.append("<site_descr>").append("<![CDATA[" + siteDescr+ "]]>").append("</site_descr>");

							}
							if(currentColumn.trim().equalsIgnoreCase("tran_type"))
							{
								
								sql ="select loc_code__insp,loc_code__aprv  from siteitem where site_code ='"+siteCode+"' and "
								      +" item_code ='"+itemCode+"' "; 
									System.out.println("sql-------------"+sql);
									String loc="",ls_loc_code_aprv="";
									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										loc=  rs.getString(1);
										ls_loc_code_aprv=  rs.getString(2);
										
									}
									rs.close();
									pstmt.close();
									valueXmlString.append("<loc_code>").append("<![CDATA[" + loc+ "]]>").append("</loc_code>");
									valueXmlString.append("<loc_code__aprv>").append("<![CDATA[" + ls_loc_code_aprv+ "]]>").append("</loc_code__aprv>");
							}
							if(currentColumn.trim().equalsIgnoreCase("work_order"))
							{	tranDate = getCurrdateAppFormat();
								workOrder = genericUtility.getColumnValue("work_order", dom);
								tranType = genericUtility.getColumnValue("tran_type", dom);
								sql = "select site_code	,ord_date,rel_date,due_date	,item_code,quantity,unit, "
								       +" lot_sl		,	mfg_date__start	,	current_batch_qty	,	ref_no	,	unit__std	,	tran_id__mps,"
									   +" quantity__mps	,	exp_date	,	yield_perc	,	feedback_reqd from workorder where work_order ='"+workOrder +"' ";
								System.out.println("sql:::" + sql);
								pstmt =  conn.prepareStatement(sql);
								rs = pstmt.executeQuery();
								if(rs.next())
								{						
									siteCode =  (rs.getString("site_code") == null ? "":rs.getString("site_code"));
									//ordDate = rs.getTimestamp("ord_date");
									relDate = rs.getTimestamp("rel_date") ;
									//dueDate = rs.getTimestamp("due_date") ;
									itemCode =  rs.getString("item_code") ;
									System.out.println("  itemCode................"+itemCode);
									quantity =rs.getDouble("quantity");
									mfgDateStart = rs.getTimestamp("mfg_date__start") ;
									currentBatchQty =rs.getDouble("current_batch_qty");
									refNo = (rs.getString("ref_no")==null ? " ":rs.getString("ref_no"));
									unitStd = (rs.getString("unit__std") ==null ? " ":rs.getString("unit__std"));	
									tranIdMps = (rs.getString("tran_id__mps")==null ? "":rs.getString("tran_id__mps")) ;
									quantityMps = rs.getDouble("quantity__mps") ;
									expDate = rs.getTimestamp("exp_date") ;
								//	tranIdMps = rs.getString("tran_id__mps") ;
									unit = rs.getString("unit") ;
									//yieldPerc = rs.getDouble("yield_perc") ;
									feedbackReqd = (rs.getString("feedback_reqd") ==null ? "N" :rs.getString("feedback_reqd")) ;
								}
								SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
								if(relDate!=null)
								{
									rdate = simpledateformat.parse(relDate.toString());
									relDate = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
									startDate1 = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(relDate).toString();
								}
								valueXmlString.append("<date__start>").append("<![CDATA[" + startDate1 + "]]>").append("</date__start>");
								if(expDate!=null)
								{
									rdate = simpledateformat.parse(expDate.toString());
									expDate = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
									startDate = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(expDate).toString();
								}
								valueXmlString.append("<exp_date>").append("<![CDATA[" + startDate + "]]>").append("</exp_date>");
								if(mfgDateStart!=null)
								{
									rdate = simpledateformat.parse(mfgDateStart.toString());
									mfgDateStart = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
									startDate = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(mfgDateStart).toString();
								}
								valueXmlString.append("<mfg_date>").append("<![CDATA[" + startDate + "]]>").append("</mfg_date>");

								itemDescr = getFieldValue("descr", "item", "item_code", itemCode, conn);
								itemDescr = itemDescr == null ? "" : itemDescr ;
					            valueXmlString.append("<item_descr>").append("<![CDATA[" + itemDescr + "]]>").append("</item_descr>");
					            valueXmlString.append("<unit>").append("<![CDATA[" + unit + "]]>").append("</unit>");
								siteDescr = getFieldValue("descr", "site", "site_code",siteCode, conn);
								siteDescr = siteDescr == null ? "" : siteDescr ;
								valueXmlString.append("<site_descr>").append("<![CDATA[" + siteDescr+ "]]>").append("</site_descr>");
								System.out.println("  startDate................"+startDate);
								tranId = genericUtility.getColumnValue("tran_id", dom);				
								//valueXmlString.append("<date__start>").append("<![CDATA[" + startDate + "]]>").append("</date__start>");
								valueXmlString.append("<unit__std>").append("<![CDATA[" + unitStd + "]]>").append("</unit__std>");
								valueXmlString.append("<quantity__mps>").append("<![CDATA[" + quantityMps + "]]>").append("</quantity__mps>");
								valueXmlString.append("<tran_id__mps>").append("<![CDATA[" + tranIdMps + "]]>").append("</tran_id__mps>");
								valueXmlString.append("<yield_perc>").append("<![CDATA[" + yieldPerc + "]]>").append("</yield_perc>");
								valueXmlString.append("<ref_no>").append("<![CDATA[" + refNo + "]]>").append("</ref_no>");
								valueXmlString.append("<date__compl>").append("<![CDATA[" + tranDate + "]]>").append("</date__compl>");
								valueXmlString.append("<item_code>").append("<![CDATA[" + itemCode + "]]>").append("</item_code>");
								valueXmlString.append("<site_code>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>");
								valueXmlString.append("<workorder_quantity>").append("<![CDATA[" + currentBatchQty + "]]>").append("</workorder_quantity>");

								sql ="select max(operation) from worder_route where work_order ='"+workOrder+"' " ;
								      
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										opr=  rs.getInt(1);
										
									}
									rs.close();
									pstmt.close();
								valueXmlString.append("<operation>").append("<![CDATA[" + opr + "]]>").append("</operation>");
								sql ="select sum(quantity) from workorder_receipt where work_order ='"+workOrder+"' and "
								      +" tran_type ='F' "; 
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										sum_quantity=  rs.getDouble(1);
										
									}
									rs.close();
									pstmt.close();
						
								sql ="select loc_code,site_code__own,potency_perc,item_ser,shelf_life,   "
										+" descr,mfg_date_on,track_shelf_life from item where item_code ='"+itemCode+"'" ;
									System.out.println("sql-------------"+sql);
									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{	 	
										locCode=  rs.getString("loc_code");
										site_code__own=(rs.getString("site_code__own")==null ? "" :rs.getString("site_code__own"));
										potency_perc=rs.getDouble("potency_perc");
										item_ser=rs.getString("item_ser");
										shelf_life=rs.getInt("shelf_life");
										descr=rs.getString("descr");
										mfg_date_on = rs.getString("mfg_date_on") ;
										track_shelf_life=rs.getString("track_shelf_life");
									}
									rs.close();
									pstmt.close();
								valueXmlString.append("<potency_perc>").append("<![CDATA[" + potency_perc + "]]>").append("</potency_perc>");
								valueXmlString.append("<site_code__own>").append("<![CDATA[" + site_code__own + "]]>").append("</site_code__own>");
								valueXmlString.append("<loc_code>").append("<![CDATA[" + locCode + "]]>").append("</loc_code>");
								valueXmlString.append("<c_crevqty>").append("<![CDATA[" + sum_quantity+ "]]>").append("</c_crevqty>");	
								sql ="select mfg_date_on from itemser where item_ser ='"+item_ser+"'  "	 ; 
									System.out.println("sql-------------"+sql);
									String ls_on="";
									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										ls_on= ( rs.getString(1)==null ? "": rs.getString(1));
										
									}
									rs.close();
									pstmt.close();
								    if(ls_on.equalsIgnoreCase("C"))
									{
										
									   valueXmlString.append("<mfg_date>").append("<![CDATA[" + tranDate + "]]>").append("</mfg_date>");
									}
									else if(ls_on.equalsIgnoreCase("S"))
									{
									   valueXmlString.append("<mfg_date>").append("<![CDATA[" + startDate1 + "]]>").append("</mfg_date>");
									}	
							}
							if(currentColumn.trim().equalsIgnoreCase("site_code"))
							{	
								siteCode = genericUtility.getColumnValue("site_code", dom);
								siteDescr = getFieldValue("descr", "site", "site_code",siteCode, conn);
								siteDescr = siteDescr == null ? "" : siteDescr ;
								valueXmlString.append("<site_descr>").append("<![CDATA[" + siteDescr+ "]]>").append("</site_descr>");
							}
							if(currentColumn.trim().equalsIgnoreCase("date__compl"))
							{
								String ls_on="";
								tranType = genericUtility.getColumnValue("tran_type", dom);
								itemCode = genericUtility.getColumnValue("item_code", dom);
								workOrder = genericUtility.getColumnValue("work_order", dom);
							    sql ="select mfg_date__start,rel_date  ,due_date from workorder where  work_order ='"+workOrder+"' "; 
								System.out.println("sql-------------"+sql);
								pstmt =  conn.prepareStatement(sql);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									mfgDateStart=  rs.getTimestamp(1);
									relDate=  rs.getTimestamp(2);
									System.out.println("mfgDateStart-------------"+mfgDateStart);
									System.out.println("relDate-------------"+relDate);	
								}
								rs.close();
								pstmt.close();
								SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
								if(relDate!=null)
								{
									rdate = simpledateformat.parse(relDate.toString());
									relDate = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
									startDate1 = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(relDate).toString();
								}
								valueXmlString.append("<date__start>").append("<![CDATA[" + startDate1 + "]]>").append("</date__start>");
//								if(expDate!=null)
//								{
//									rdate = simpledateformat.parse(expDate.toString());
//									expDate = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
//									startDate2 = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(expDate).toString();
//									System.out.println("startDate2-------------"+startDate2);
//								}
//								valueXmlString.append("<exp_date>").append("<![CDATA[" + startDate2 + "]]>").append("</exp_date>");
								if(mfgDateStart!=null)
								{
									rdate = simpledateformat.parse(mfgDateStart.toString());
									mfgDateStart = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
									startDate3 = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(mfgDateStart).toString();
									valueXmlString.append("<mfg_date>").append("<![CDATA[" + startDate3 + "]]>").append("</mfg_date>");
								}
								sql ="select mfg_date_on,case when shelf_life is null then 0 else shelf_life end  ,item_ser from item where  item_code ='"+itemCode+"' "; 
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										ls_on=  (rs.getString(1)==null ? "" :rs.getString(1));
										shelf_life=  rs.getInt(2);
										item_ser=  rs.getString(3);
										System.out.println("shelf_life-------------"+shelf_life);

									}
									rs.close();
									pstmt.close();
								
								if(ls_on.trim().length()==0)
								{
									sql ="select mfg_date_on from itemser where item_ser ='"+item_ser+"'  "	 ;
								
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										ls_on=  (rs.getString(1)==null ? "" :rs.getString(1));
										
									}
									rs.close();
									pstmt.close();
								}
								if(mfgDateStart == null)
								{
									if(ls_on.equalsIgnoreCase("C"))
									{
									  String  date__compl = genericUtility.getColumnValue("date__compl", dom);
									  System.out.println("date__compl-------------"+date__compl);
									   mfgDateStart=new Timestamp(System.currentTimeMillis() );
									   valueXmlString.append("<mfg_date>").append("<![CDATA[" + date__compl + "]]>").append("</mfg_date>");
									}
									else if(ls_on.equalsIgnoreCase("S"))
									{
									   valueXmlString.append("<mfg_date>").append("<![CDATA[" + startDate1 + "]]>").append("</mfg_date>");
									   mfgDateStart=relDate;
									}
								}
								if(mfgDateStart!=null)
								{
									java.sql.Timestamp expdatelast =null;
									java.sql.Timestamp expdate1 =getRelativeDate(mfgDateStart,shelf_life);
									System.out.println("expdate1-------------"+expdate1);
									rdate = simpledateformat.parse(expdate1.toString());
									expdatelast = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");        
								    String expdateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(expdatelast).toString();
									expdateStr=expdateStr+"-00.00.00";
									System.out.println("expdateStr-------------"+expdateStr);
									//sql ="select last_day(?) from dual";		
									sql ="select FN_RLAST_DAY(timestamp('"+expdateStr+"')) from dual";
									System.out.println("sql-------------"+sql);
									pstmt =  conn.prepareStatement(sql);
									//pstmt.setTimestamp(1,expdate1);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										expdatelast=  rs.getTimestamp(1);
										System.out.println("expdatelast-------------"+expdatelast);
									}
									rs.close();
									pstmt.close();
									rdate = simpledateformat.parse(expdatelast.toString());
									expdatelast = Timestamp.valueOf(simpledateformat.format(rdate).toString() + " 00:00:00.0");
								    expdateStr = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(expdatelast).toString();
									valueXmlString.append("<exp_date>").append("<![CDATA[" + expdateStr + "]]>").append("</exp_date>");
								}									
							}
							if(currentColumn.trim().equalsIgnoreCase("qc_reqd"))
							{
								qcReqd = genericUtility.getColumnValue("qc_reqd", dom);
								siteCode = genericUtility.getColumnValue("site_code", dom);
								itemCode = genericUtility.getColumnValue("item_code", dom);
								if(qcReqd.equalsIgnoreCase("Y"))
								{
									sql ="select loc_code__insp from siteitem where site_code ='"+siteCode+"' and item_code ='"+itemCode+"' "; 
									System.out.println("sql-------------"+sql);

									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										ls_loc=  rs.getString(1);	
									}
									rs.close();
									pstmt.close();
								}
								else
								{
									sql ="select loc_code__aprv from siteitem where site_code ='"+siteCode+"' and item_code ='"+itemCode+"' "; 
									System.out.println("sql-------------"+sql);
									pstmt =  conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										ls_loc=  rs.getString(1);	
									}
									rs.close();
									pstmt.close();
								}
								valueXmlString.append("<loc_code>").append("<![CDATA[" + ls_loc+ "]]>").append("</loc_code>");
							}
						if(currentColumn.trim().equalsIgnoreCase("emp_code__aprv"))
						{
							if (columnValue != null)
							{
								sql = "select emp_fname,emp_mname,emp_lname from employee where emp_code='"+columnValue+"'";
								pstmt = conn.prepareStatement(sql);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									fname = rs.getString(1) == null ? "" :rs.getString(1);
									mname = rs.getString(2) == null ? "" :rs.getString(2);
									lname = rs.getString(3) == null ? "" :rs.getString(3);	valueXmlString.append("<emp_fname>").append("<![CDATA[").append(fname).append("]]>").append("</emp_fname>");
									valueXmlString.append("<emp_mname>").append("<![CDATA[").append(mname).append("]]>").append("</emp_mname>");
									valueXmlString.append("<emp_lname>").append("<![CDATA[").append(lname).append("]]>").append("</emp_lname>");
								}
								else
								{
									valueXmlString.append("<emp_fname>").append("<![CDATA[").append("").append("]]>").append("</emp_fname>");
									valueXmlString.append("<emp_mname>").append("<![CDATA[").append("").append("]]>").append("</emp_mname>");
									valueXmlString.append("<emp_lname>").append("<![CDATA[").append("").append("]]>").append("</emp_lname>");
								}
								pstmt.close();
								pstmt = null;
							 }
						}
						valueXmlString.append("</Detail1 >");
						System.out.println("itemchange string :::" +valueXmlString);
						break;
					case 2:			
							parentNodeList = dom.getElementsByTagName("Detail2");
							parentNode = parentNodeList.item(0);
							childNodeList = parentNode.getChildNodes();
							ctr = 0;
							
							valueXmlString.append("<Detail2>");
							int childListLength = childNodeList.getLength();
							do
							{
								childNode = childNodeList.item(ctr);
								childNodeName = childNode.getNodeName();
								if(childNodeName.equals(currentColumn.trim()))
								{
									if (childNode.getFirstChild() != null)
									{
										columnValue=childNode.getFirstChild().getNodeValue();
									}
								}
								ctr++;
							}
						   while(ctr < childListLength && !childNodeName.equals(currentColumn));
						   if(currentColumn.trim().equalsIgnoreCase("itm_default"))
							{   
								String hdrworder = null,hdLocCode="";
								hdrworder = genericUtility.getColumnValue("work_order",dom1);
								System.out.println("Inside case2 (value of workorder):::::::::"+hdrworder);
								String hdItemCode = null;
								hdItemCode = genericUtility.getColumnValue("item_code",dom1);
								System.out.println("Inside case2 (value of item_code):::::::::"+hdItemCode);
								itemDescr = getFieldValue("descr", "item", "item_code", hdItemCode, conn);
							    itemDescr = itemDescr == null ? "" : itemDescr ;
							    unit = getFieldValue("unit", "item", "item_code", hdItemCode, conn);

								hdLocCode = genericUtility.getColumnValue("loc_code",dom1);
								//locDesc = getFieldValue("unit", "item", "item_code", hdItemCode, conn);
								valueXmlString.append("<loc_code>").append("<![CDATA[" + hdLocCode + "]]>").append("</loc_code>");
							    valueXmlString.append("<item_descr>").append("<![CDATA[" + itemDescr + "]]>").append("</item_descr>");
							    valueXmlString.append("<unit>").append("<![CDATA[" + unit + "]]>").append("</unit>");
								valueXmlString.append("<work_order>").append("<![CDATA[").append(hdrworder).append("]]>").append("</work_order>");
								valueXmlString.append("<item_code>").append("<![CDATA[").append(hdItemCode).append("]]>").append("</item_code>");
								valueXmlString.append("<item_code>").append("<![CDATA[").append(hdItemCode).append("]]>").append("</item_code>");
							}
							if(currentColumn.trim().equalsIgnoreCase("pack_code"))
							{	
								packCode = genericUtility.getColumnValue("pack_code", dom);
								packDescr = getFieldValue("descr", "packing", "pack_code",packCode, conn);
								packDescr = packDescr == null ? "" : packDescr ;
								valueXmlString.append("<packing_descr>").append("<![CDATA[" + packDescr+ "]]>").append("</packing_descr>");
							}
							if(currentColumn.trim().equalsIgnoreCase("gross_weight")||currentColumn.trim().equalsIgnoreCase("tare_weight"))
							{
								grossWeight = genericUtility.getColumnValue("gross_weight", dom);
								tareWeight = genericUtility.getColumnValue("tare_weight", dom);
								grossWeightNbr =Double.parseDouble(grossWeight);
								tareWeightNbr =Double.parseDouble(tareWeight);
								netweight =	grossWeightNbr - tareWeightNbr;
								
								valueXmlString.append("<net_weight>").append("<![CDATA[" + netweight+ "]]>").append("</net_weight>");
							}

						   valueXmlString.append("</Detail2>");
						   break;
					
				}// switch end
						valueXmlString.append("</Root>");
			}// try end
      catch(Exception e)
      {	
         e.printStackTrace();
         System.out.println("Exception ::" + e.getMessage());
         throw new ITMException(e);
      }
      finally 
		{
			try
			{
				if(conn != null)
				   conn.close();
								conn = null;
			}
			catch(Exception e1)
			{
			  e1.printStackTrace();
			}
			
		}
        System.out.println("[MPSOrder] Connection is Closed");
        System.out.println("[MPSOrder] Connection is Closed");
        System.out.println("valueXmlString:::::" + valueXmlString.toString());
        return valueXmlString.toString();
    }

    private String getCurrdateAppFormat()
    {
        String s = "";				  
        GenericUtility genericUtility = GenericUtility.getInstance();
        try
        {
            java.util.Date date = null;
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            System.out.println(genericUtility.getDBDateFormat());
            
            SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
            date = simpledateformat.parse(timestamp.toString());
            timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
            s = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
        }
        catch(Exception exception)
        {
            System.out.println("Exception in [MPSOrder] getCurrdateAppFormat " + exception.getMessage());
        }
        return s;
    }
    private String getFieldValue(String column,String tableName, String columnName, String columnValue,Connection conn)
    {	
    	PreparedStatement pstmt = null;
        ResultSet rs = null;
        String value = null;
        String sql = null;
   
        sql = " select "+column+" from "+tableName+" where "+columnName+" = '" + columnValue + "' ";
        try
        {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            System.out.println("\n\n\n Query Executed " + sql+ "\n\n******************");
            if(rs.next())
            {
            	value = rs.getString(1) != null ? rs.getString(1) : " ";            	
            }
            else
            {
            	value = " ";
            }   
            rs.close();
            pstmt.close();
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
            System.out.println("Exception ::" + exception.getMessage());
        }
        return value;
    }
	
    private int isValueExist(String tableName, String columnName, String columnValue,Connection conn)
    {	
    	PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = null;
        int cnt = 0 ; 	
        sql = " select count(1) as count from "+tableName+" where "+columnName+" = '" + columnValue + "' ";
        try
        {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            System.out.println("\n\n\n Query Executed " + sql+ "\n\n******************");
            if(rs.next())
            {
            	cnt = rs.getInt("count");            	
            }
            rs.close();
            pstmt.close();
            System.out.println("cnt--------------"+cnt);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
            System.out.println("Exception ::" + exception.getMessage());
        }
        return cnt;
    }
    private java.sql.Timestamp getRelativeDate(java.sql.Timestamp date, int n )
    {	
        	Calendar  cal = Calendar.getInstance();
        	cal.setTime(date);
        	cal.add(cal.DATE, n);
        	java.util.Date date1 =  cal.getTime();
			SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
			return java.sql.Timestamp.valueOf(sdt.format(date1) + " 00:00:00.000");
    }
}
