/*
Modification:
1- lot lot generate problem [ 290052007]
*/





package ibase.webitm.ejb.mfg.adv;

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

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


import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.dis.StockUpdate;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.ejb.fin.FinCommonInvAcct;
import ibase.webitm.utility.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class RcpBackflushMultiConf extends ActionHandlerEJB implements  RcpBackflushMultiConfLocal , RcpBackflushMultiConfRemote //SessionBean 
{
   /* public void ejbCreate() throws RemoteException,CreateException{
        
    }
    public void ejbRemove(){
        
    }
    public void ejbActivate(){
        
    }
    public void ejbPassivate(){
        
    }*/
    public void setSessionContext(SessionContext se){
        
    }
    
    public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
    {
        Connection conn = null;
        Statement stmt = null,stmt1 = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null,rs1 = null;
        String sql = "";
        ConnDriver connDriver = null;
        
        String issLineNo = "",issItemCode = "",issUnit = "",issLocCode = "",issLotNo = "";
        String issLotSl ="";
        double issQuantity = 0,issRate =0;
        
        String rcpConfirm = "",rcpItemCode = "",rcpLocCode = "",rcpLotNo = "",rcpLotSl = "";
        String rcpUnit = "",rcpQcReqd = "",rcpSiteCodeMfg = "",rcpPackCOde = "",rcpGrade = "";
        String rcpDimension = "";
        double rcpQuantity = 0,rcpGrossWt = 0,rcpTareWt = 0,rcpNetWt = 0,rcpInvValue = 0,rcpCapacity = 0;
        long rcpNoArt = 0;
        java.sql.Date rcpMfgDate = null,rcpExpDate = null;
        
        String stkGrade= "",stkBatchNo = "",stkAcctCodeInv = "",stkCctrCodeInv = "",stkSuppCodeMfg = "";
        long stkNoArt = 0;
        double stkRate = 0,stkGrossRate = 0,stkPotencyPerc = 0;
        java.sql.Timestamp stkRetestDate = null;

        String acctCodeDr = "",cctrCodeDr = "",acctCodeCr = "",cctrCodeCr = "";
        String itemSer = "",itemStru = "";
        
        String errString = "",backFlushType = "",unitAlt = "",siteCodeHdr = "",projCodeHdr = "",prjIndNo = "";
        double amount = 0,grossAmount = 0,convQtyStdUom = 0;
        Timestamp tranDate = null;
        HashMap stkUpdMap = null;
        ITMDBAccessEJB itmDBAccessEJB = null;
        
        FinCommon finCommon = null;
        GenericUtility genericUtility = null;
        FinCommonInvAcct finCommonInvAcct = null;
        try{
            finCommon = new FinCommon();
            finCommonInvAcct = new FinCommonInvAcct();
            itmDBAccessEJB = new ITMDBAccessEJB();
            genericUtility = new GenericUtility();
            stkUpdMap = new HashMap();
           
            connDriver = new ConnDriver();
            conn = connDriver.getConnectDB("Driver");
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            stmt1 = conn.createStatement();
            
            sql = "select confirmed,site_code,backflush_type,tran_date,proj_code from rcp_backflush where tran_id = '"+tranID+"'";
            System.out.println("SQL : "+sql);
            rs1 = stmt1.executeQuery(sql);
            if(rs1.next()){
                rcpConfirm = rs1.getString("confirmed");
                siteCodeHdr = rs1.getString("site_code");
                backFlushType = rs1.getString("backflush_type");
                tranDate = rs1.getTimestamp("tran_date");
                projCodeHdr = rs1.getString("proj_code");
            }
            rs1.close();
            if(rcpConfirm != null && rcpConfirm.trim().equalsIgnoreCase("Y")){
                System.out.println("The Selected ransaction is already confirmed..........");
                errString = itmDBAccessEJB.getErrorString("","VTCONF8","","",conn);
                return errString;
            }
            String itemCodeHdr = "",lotNoHdr = "",lotSlHdr = "",locCodeHdr = "";
            String acctCodeHdr = "",cctrCodeHdr = "";
            sql = "select item_code,loc_code,lot_no,lot_sl from rcp_backflush_rcpt";
            System.out.println("SQL : "+sql);
            rs1 = stmt1.executeQuery(sql);
            if(rs1.next()){
                itemCodeHdr = rs1.getString("item_code");
                locCodeHdr = rs1.getString("loc_code");
                lotNoHdr = rs1.getString("lot_no");
                lotSlHdr = rs1.getString("lot_sl");
            }
            rs1.close();
            
            sql = "select item_ser from item where item_code = '"+itemCodeHdr+"'";
            System.out.println("SQL : "+sql);
            rs1 = stmt1.executeQuery(sql);
            if(rs1.next()){
                itemSer = rs1.getString("item_ser");
            }
            rs1.close();
            
            sql = "select acct_code__inv, cctr_code__inv from stock where " +
                    "item_code = '"+itemCodeHdr+"' " +
                    "and site_code = '"+siteCodeHdr+"' " +
                    "and loc_code = '"+locCodeHdr+"' " +
                    "and lot_no = '"+lotNoHdr+"' " +
                    "and lot_sl = '"+lotSlHdr+"'";
            System.out.println("SQL : "+sql);
            rs1 = stmt1.executeQuery(sql);
            if(rs1.next()){
                acctCodeHdr = rs1.getString("acct_code__inv");
                cctrCodeHdr = rs1.getString("cctr_code__inv");
            }
            rs1.close();
            
            sql = "select line_no,item_code,unit,rate,loc_code,lot_no,lot_sl,quantity from rcp_backflush_iss " +
                    "where tran_id = '"+tranID+"'";
            System.out.println("SQL : "+sql);
            rs = stmt.executeQuery(sql);
            //Issue Update
            while(rs.next()){
                issLineNo = rs.getString("line_no");
                issItemCode = rs.getString("item_code");
                issUnit = rs.getString("unit");
                issRate = rs.getDouble("rate");
                issLocCode = rs.getString("loc_code");
                issLotNo = rs.getString("lot_no");
                issLotSl = rs.getString("lot_sl");
                issQuantity = rs.getDouble("quantity"); 
                
                
                sql = "select rate,gross_rate,grade,batch_no,no_art,retest_date,acct_code__inv,cctr_code__inv," +
                        "potency_perc,supp_code__mfg from stock " +
                        "where item_code = '"+issItemCode+"' and " +
                        "site_code = '"+siteCodeHdr+"' and " +
                        "loc_code = '"+issLocCode+"' and " +
                        "lot_no = '"+issLotNo+"' and " +
                        "lot_sl = '"+issLotSl+"'";
                
                rs1 = stmt1.executeQuery(sql);
                System.out.println("SQL : "+sql);
                if(rs1.next()){
                    stkRate = rs1.getDouble("rate");
                    stkGrossRate = rs1.getDouble("gross_rate");
                    stkGrade = rs1.getString("grade");
                    stkBatchNo = rs1.getString("batch_no");
                    stkNoArt = rs1.getLong("no_art");
                    stkRetestDate = rs1.getTimestamp("retest_date");
                    stkAcctCodeInv = rs1.getString("acct_code__inv");
                    stkCctrCodeInv = rs1.getString("cctr_code__inv");
                    stkPotencyPerc = rs1.getDouble("potency_perc");
                    stkSuppCodeMfg = rs1.getString("supp_code__mfg");
                }else{
                    if(issQuantity > 0){
                        errString = itmDBAccessEJB.getErrorString("","VXSTK2","","",conn);
                        return errString;
                    }
                }
                rs1.close();
                
                sql = "select item_ser,item_stru " +
                        "from item " +
                        "where item_code = '"+issItemCode+"'";
                System.out.println("SQL : "+sql);
                rs1 = stmt1.executeQuery(sql);
                if(issQuantity < 0){
                    stkRate = issRate;
                    stkGrossRate = issRate;
                    if(rs1.next()){
                        itemSer = rs1.getString("item_ser");
                        itemStru = rs1.getString("item_stru");
                        
                        acctCodeDr = stkAcctCodeInv;
                        cctrCodeDr = stkCctrCodeInv;
                    }else{
                        String acctCodeDrTemp = "";
                        acctCodeDrTemp =  finCommon.getFromAcctDetr(issItemCode,itemSer,"IN",conn);
                        if(acctCodeDr != null && acctCodeDr.trim().length() > 0){
                            acctCodeDr = acctCodeDrTemp.substring(0,acctCodeDr.indexOf(","));
                            cctrCodeDr = acctCodeDrTemp.substring(acctCodeDr.indexOf(",")+1);
                        }
                        acctCodeDrTemp = null;
                    }
                    acctCodeCr = acctCodeHdr;
                    cctrCodeCr = cctrCodeHdr;
                    
                    if(cctrCodeCr == null || cctrCodeCr.trim().length() == 0){
                        cctrCodeCr = stkCctrCodeInv;
                    }
                }else{
                    acctCodeCr = stkAcctCodeInv;
                    cctrCodeCr = stkCctrCodeInv;
                }
                rs1.close();
                /*if (isnull(ls_cctrcodedr) or len(trim(ls_cctrcodedr)) = 0) and lc_quantity_hdr >= 0 then
                    ls_cctrcodedr = ls_cctrcodecr
                elseif (isnull(ls_cctrcodecr) or len(trim(ls_cctrcodecr)) = 0) and lc_quantity_hdr < 0 then
                    ls_cctrcodecr = ls_cctrcodedr
                end if*/
                
                if(issQuantity > 0){
                    amount = amount + (stkRate * issQuantity);
                    grossAmount = grossAmount + (grossAmount * issQuantity);
                }
                if(backFlushType.equalsIgnoreCase("S") || backFlushType.equalsIgnoreCase("C")){
                    if(backFlushType.equalsIgnoreCase("C")){
                        stkUpdMap.put("potency_perc",Double.toString(stkPotencyPerc));
                        stkUpdMap.put("supp_code__mfg",stkSuppCodeMfg);
                    }
                    if(unitAlt == null || unitAlt.trim().length() == 0){
                        sql = "select unit__alt from stock where item_code = '"+issItemCode+"' " +
                                "and lot_no = '"+issLotNo+"' " +
                                "and unit__alt is not null " +
                                "and length(trim(unit__alt)) > 0";
                        System.out.println("SQL : "+sql);
                        rs1 = stmt1.executeQuery(sql);
                        if(rs1.next()){
                            unitAlt = rs1.getString("unit__alt");
                        }
                        rs1.close();
                    }
                    if(convQtyStdUom == 0){
                        sql = "select conv__qty_stduom " +
                                "from stock " +
                                "where item_code = '"+issItemCode+"' " +
                                "and lot_no = '"+issLotNo+"' " +
                                "and conv__qty_stduom is not null " +
                                "and conv__qty_stduom <> 0 ";
                        System.out.println("SQL : "+sql);
                        rs1 = stmt1.executeQuery(sql);
                        if(rs1.next()){
                            convQtyStdUom = rs1.getDouble("conv__qty_stduom");
                        }
                    }                    
                }
                if(cctrCodeCr == null || cctrCodeCr.trim().length() == 0){
                    cctrCodeCr = " ";
                }
                if(cctrCodeDr == null || cctrCodeDr.trim().length() == 0){
                    cctrCodeDr = " ";
                }
                stkUpdMap.put("line_no",issLineNo);
                stkUpdMap.put("item_code",issItemCode);
                stkUpdMap.put("site_code",siteCodeHdr);
                stkUpdMap.put("loc_code",issLocCode);
                stkUpdMap.put("lot_no",issLotNo);
                stkUpdMap.put("lot_sl",issLotSl);
                stkUpdMap.put("unit",issUnit);
                stkUpdMap.put("quantity",Double.toString(issQuantity));
                stkUpdMap.put("qty_stduom",Double.toString(issQuantity));
                stkUpdMap.put("tran_id",tranID);
                stkUpdMap.put("tran_ser","R-BFS");
                stkUpdMap.put("tran_date",tranDate);
                stkUpdMap.put("acct_code__cr",acctCodeCr);
                stkUpdMap.put("cctr_code__cr",cctrCodeCr);
                stkUpdMap.put("acct_code__dr",acctCodeDr);
                stkUpdMap.put("cctr_code__dr",cctrCodeDr);
                if(issQuantity >= 0){
                    stkUpdMap.put("tran_type","ID");
                }else{
                    stkUpdMap.put("tran_type","R");
                    stkUpdMap.put("quantity",Double.toString(-1 * issQuantity));
                    stkUpdMap.put("qty_stduom",Double.toString(-1 * issQuantity));
                    stkUpdMap.put("acct_code_inv",acctCodeDr);
                    stkUpdMap.put("cctr_code_inv",cctrCodeDr);
                }
                stkUpdMap.put("grade",stkGrade);
                if(issQuantity < 0){
                    stkUpdMap.put("rate",Double.toString(stkRate));
                    stkUpdMap.put("gross_rate",Double.toString(stkGrossRate));
                }
                if(itemStru == null || !itemStru.equalsIgnoreCase("R")){
                	StockUpdate stkUpd =  new StockUpdate();
                    errString = stkUpd.updateStock(stkUpdMap,xtraParams,conn);
                	stkUpd =  null;
                    if(errString.indexOf("Error") != -1){
                        break;
                    }
                }
                stkUpdMap.clear();                   
            }//while end (Issue)
            rs.close();
            stmt.close();
            
            //Recipt stock update
            stkUpdMap.clear();
            
            if(errString.indexOf("Error") != -1){
                System.out.println("Returning Result "+errString);
                conn.rollback();
                return errString;
            }
            
            ////////Creating QC Order
            System.out.println("Creating QC Order....");
            errString = createQCOrder(tranID,siteCodeHdr,backFlushType,xtraParams,conn);
            if(errString.indexOf("Error") != -1){
                System.out.println("Create QC Order Failed........");
                errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
                conn.rollback();
                return errString;
            }
            /////////////
            sql = "select item_code,loc_code,lot_no,lot_sl," +
                    "quantity,unit,qc_reqd,mfg_date,exp_date,site_code__mfg,pack_code," +
                    "grade, dimension, gross_weight, tare_weight, net_weight, no_art, inv_value " +
                    "from rcp_backflush_rcpt where tran_id = '"+tranID+"'";
            System.out.println("SQL : "+sql);
            stmt = conn.createStatement();
            
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                rcpItemCode = rs.getString("item_code");
                rcpLocCode = rs.getString("loc_code");
                rcpLotNo = rs.getString("lot_no");
                rcpLotSl = rs.getString("lot_sl");
                rcpQuantity = rs.getDouble("quantity");
                rcpUnit = rs.getString("unit");
                rcpQcReqd = rs.getString("qc_reqd");
                rcpMfgDate = rs.getDate("mfg_date");
                rcpExpDate = rs.getDate("exp_date");
                rcpSiteCodeMfg = rs.getString("site_code__mfg");
                rcpPackCOde = rs.getString("pack_code");
                rcpGrade = rs.getString("grade");
                rcpDimension = rs.getString("dimension");
                rcpGrossWt = rs.getDouble("gross_weight");
                rcpTareWt = rs.getDouble("tare_weight");
                rcpNetWt = rs.getDouble("net_weight");
                rcpNoArt = rs.getLong("no_art");
                rcpInvValue = rs.getDouble("inv_value");
                
                sql = "select case when capacity is null then 0 else capacity end from location where " +
                        "loc_code = '"+rcpLocCode+"'";
                System.out.println("SQL : "+sql);
                stmt1 = conn.createStatement();
                rs1 = stmt1.executeQuery(sql);
                if(rs1.next()){
                    rcpCapacity = rs1.getDouble(1);
                }
                rs1.close();
                if(rcpQuantity > rcpCapacity){
                    errString = itmDBAccessEJB.getErrorString("","VTCAPACITY","","",conn);
                    return errString;
                }
                
                if(rcpQuantity > 0){
                    stkRate = rcpInvValue / rcpQuantity;
                    if(backFlushType.equalsIgnoreCase("S") || backFlushType.equalsIgnoreCase("C")){
                        stkGrossRate = grossAmount / rcpQuantity;
                    }else{
                        stkGrossRate = rcpInvValue / rcpQuantity;
                    }
                }
                
                stkUpdMap.put("item_code",rcpItemCode);
                stkUpdMap.put("site_code",siteCodeHdr);
                stkUpdMap.put("loc_code",rcpLocCode);
                stkUpdMap.put("lot_no",rcpLotNo);
                stkUpdMap.put("lot_sl",rcpLotSl);
                stkUpdMap.put("unit",rcpUnit);
                if(rcpQuantity >= 0){
                    stkUpdMap.put("quantity",Double.toString(rcpQuantity));
                    stkUpdMap.put("qty_stduom",Double.toString(rcpQuantity));
                }else{
                    stkUpdMap.put("quantity",Double.toString(-1 * rcpQuantity));
                    stkUpdMap.put("qty_stduom",Double.toString(-1 * rcpQuantity));
                }
                stkUpdMap.put("tran_id",tranID);
                stkUpdMap.put("tran_ser","R-BFS");
                stkUpdMap.put("tran_date",tranDate);
                 
                sql = "select acct_code__inv, cctr_code__inv from stock " +
                        "where item_code = '"+rcpItemCode+"' " +
                        "and site_code = '"+siteCodeHdr+"' " +
                        "and loc_code = '"+rcpLocCode+"' " +
                        "and lot_no = '"+rcpLotNo+"' " +
                        "and lot_sl = '"+rcpLotSl+"'";
                System.out.println("SQL : "+sql);
                rs1 = stmt1.executeQuery(sql);
                if(rs1.next())
                {
                    acctCodeDr = rs1.getString("acct_code__inv");
                    cctrCodeDr = rs1.getString("cctr_code__inv");
                    rs1.close();
                	stmt1.close();
                }
                else
                {
                	
                	//added by tarani else part
                	 sql = "select item_ser from item where item_code = '"+rcpItemCode+"'";
                	System.out.println("SQL : "+sql);
                	rs1 = stmt1.executeQuery(sql);
                	if(rs1.next())
                	{
                		itemSer	= rs1.getString(1);
                	}
                	rs1.close();
                	stmt1.close();
                	if(itemSer !=null)itemSer.trim();
                	System.out.println("Parameter goes to getFromAcctDetr.....");
                	System.out.println("rcpItemCode :::["+rcpItemCode+"]");
                	System.out.println("itemSer:::["+itemSer+"]");
                	System.out.println("Parameter goes to getFromAcctDetr.....");
                	String acctCctr = finCommon.getFromAcctDetr(rcpItemCode,itemSer, "IN",conn);
                	System.out.println("acct @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+acctCctr);
                	acctCodeDr = acctCctr.substring(0,acctCctr.indexOf(","));
                    cctrCodeDr = acctCctr.substring(acctCctr.indexOf(",")+1);
                    acctCctr = null;
                }
                
                if(rcpQuantity >= 0){
                    stkUpdMap.put("acct_code__dr",acctCodeDr);
                    stkUpdMap.put("cctr_code__dr",cctrCodeDr);
                    stkUpdMap.put("acct_code_inv",acctCodeDr);
                    stkUpdMap.put("cctr_code_inv",cctrCodeDr);
                }else{
                    stkUpdMap.put("acct_code__cr",acctCodeDr);
                    stkUpdMap.put("cctr_code__cr",cctrCodeDr);
                    stkUpdMap.put("acct_code_inv",acctCodeDr);
                    stkUpdMap.put("cctr_code_inv",cctrCodeDr);
                }
                stkUpdMap.put("acct_code__cr"," ");
                stkUpdMap.put("cctr_code__cr"," ");
                stkUpdMap.put("rate",Double.toString(stkRate));
                stkUpdMap.put("gross_rate",Double.toString(stkGrossRate));
                
                if(rcpQuantity >= 0){
                    stkUpdMap.put("tran_type","R");
                }else{
                    stkUpdMap.put("tran_type","I");
                }
                stkUpdMap.put("mfg_date",rcpMfgDate);
                stkUpdMap.put("exp_date",rcpExpDate);
                
                stkUpdMap.put("site_code__mfg",rcpSiteCodeMfg);
                stkUpdMap.put("pack_code",rcpPackCOde);
                stkUpdMap.put("retest_date",stkRetestDate);
                if(rcpGrade == null || rcpGrade.trim().length() == 0) rcpGrade = "   ";
                stkUpdMap.put("grade",rcpGrade);
                stkUpdMap.put("batch_no",stkBatchNo);
                stkUpdMap.put("no_art",Double.toString(rcpNoArt));
                stkUpdMap.put("dimension",rcpDimension);
                stkUpdMap.put("gross_weight",Double.toString(rcpGrossWt));
                stkUpdMap.put("tare_weight",Double.toString(rcpTareWt));
                stkUpdMap.put("net_weight",Double.toString(rcpNetWt));
                
                if(backFlushType.equalsIgnoreCase("S") || backFlushType.equalsIgnoreCase("C")){
                    stkUpdMap.put("unit__alt",unitAlt);
                    stkUpdMap.put("conv__qty_stduom",Double.toString(convQtyStdUom));
                }
                
                 StockUpdate stkUpd =  new StockUpdate();
	              errString = stkUpd.updateStock(stkUpdMap,xtraParams,conn);
                 stkUpd =null;
                if(errString != null && errString.indexOf("Error") != -1  )	//added by rajendra on 09/07/07   for checking null value
				{
                    break;
                }
                
                stkUpdMap.clear();
                
            }//while end
            System.out.println("errString : "+errString);
            if(errString == null || errString.indexOf("Error") == -1){					//comment by rajendra 0n 17/07/07
		   // if(errString ==null ){
                errString = finCommonInvAcct.rbfpost(tranID,"R-BFS",conn);
                System.out.println("ErrString from RbfPost :: "+errString);
                if(errString.indexOf("Error") == -1 && projCodeHdr != null && projCodeHdr.trim().length() > 0){
                    sql = "select ind_no from project where proj_code = '"+projCodeHdr+"'";
                     stmt1 = conn.createStatement();
                    rs1 = stmt1.executeQuery(sql);
                    if(rs1.next()){
                        prjIndNo = rs1.getString("ind_no");
                    }
                    if(prjIndNo != null && prjIndNo.trim().length() > 0){
                        sql = "update indent set status = 'C',status_date = ? ," +
                                "chg_date = ? ,chg_user = ? ,chg_term = ? " +
                                "where ind_no = ? ";
                        System.out.println("SQL : "+sql);
                        pstmt = conn.prepareStatement(sql);
                        pstmt.setTimestamp(1,new Timestamp(System.currentTimeMillis()));
                        pstmt.setTimestamp(2,new Timestamp(System.currentTimeMillis()));
                        pstmt.setString(3,"SYSTEM");
                        pstmt.setString(4,"SYSTEM");
                        pstmt.setString(5,prjIndNo);
                        
                        int updCnt = pstmt.executeUpdate();
                        System.out.println("Update in Indent : "+updCnt);
                    }
                    sql = "update project set quantity = (select sum(quantity) from rcp_backflush_rcpt " +
                            "where tran_id = '"+tranID+"') where proj_code = '"+projCodeHdr+"'";
                    System.out.println("SQL :"+sql);
                    stmt1.executeUpdate(sql);
                }else{
                    conn.rollback();
                    //errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
                    return errString;
                }
                String empCodeAprv = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
                sql = "update rcp_backflush set confirmed = 'Y',conf_date = ? ,emp_code__aprv = ? where tran_id = '"+tranID+"' ";
                System.out.println("SQL : "+sql);
                pstmt = conn.prepareStatement(sql);
                pstmt.setTimestamp(1,new Timestamp(System.currentTimeMillis()));
                pstmt.setString(2,empCodeAprv);
                int upd = pstmt.executeUpdate();
                System.out.println("Receipt Backflush Multi Confirm :: "+upd);
                if(upd > 0){
                    conn.commit();
                    errString = itmDBAccessEJB.getErrorString("","VTDIST30","");
                    System.out.println("ReceiptBackflush Multi Confirmed .."+errString);
                }
                
            }else{                
                conn.rollback();
                //errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
                return errString;
            }
            
        }catch(ITMException ie){
            System.out.println("ITMException : "+ie);
            try{conn.rollback();}catch(Exception t){}
            ie.printStackTrace();
            errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
            System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
            return errString;
        }catch(Exception e){
            System.out.println("Exception in Confirm [RcpBackflushConfEJB]"+e);
            try{conn.rollback();}catch(Exception t){}
            e.printStackTrace();
            errString = itmDBAccessEJB.getErrorString("","VTDESNCONF","","",conn);
            System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
            return errString;
        }finally{
            try{
                stkUpdMap = null;
                if(rs != null){rs.close();rs = null;}
                if(rs1 != null){rs1.close();rs1 = null;}
                if(stmt != null){stmt.close();stmt = null;}
                if(stmt1 != null){stmt1.close();stmt1 = null;}
                if(conn != null){//conn.close();//To be uncommented - checked for error
                    conn = null;}
               
            }catch(Exception e){System.out.println("Exception : "+e);e.printStackTrace();}
        }
        System.out.println("Returnng String From RcpBackflushMultiConf :"+errString);
        return errString;
    }
    
    private String createQCOrder(String tranId,String rcpSiteCode,String rcpBackflushType,String xtraParm,Connection conn) throws ITMException
    {
        String winName = "w_qcorder_new",sql = "";
        Statement stmt = null,stmt1 = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null,rs1 = null;
        String rcpLineNo = "",rcpItemCode = "",rcpUnit = "";
        String rcpLocCode = "",rcpLotNo = "",rcpLotSl = "";
        double rcpQuantity = 0;
        int qcLeadTime = 0;
        String itemSer = "",siteItemSer = "",qOrderType = "";
        String keyString = "";
        String qcNo = "",userId = "",porcpLineNo = "";
        int porcpline = 1;
        String sqlInsert = "";
        String currDate = "",errString = "",loginEmpCode = "";
        GenericUtility genericUtility = null;
        SimpleDateFormat sdf = null;
        java.util.Date qcDueDate = null;
        java.sql.Date expDate = null;
        try{
            genericUtility = new GenericUtility();
            sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
            stmt = conn.createStatement();
            stmt1 = conn.createStatement();
            
            currDate = sdf.format(new java.sql.Date(System.currentTimeMillis()));
            loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParm,"loginEmpCode");
            
            sqlInsert ="insert into qc_order (qorder_no,qorder_type,qorder_date,site_code,item_code, " +
                        "route_code,quantity,qty_passed,qty_rejected," +
                        "start_date,due_date,rel_date,porcp_no,porcp_line_no, " +
                        "lot_no,lot_sl,chg_date,chg_user,chg_term,loc_code," +
                        "qty_sample,status, unit,qc_create_type, batch_no,expiry_date," +
                        "loc_code__aprv,loc_code__rej,unit__sample,lot_no__new,retest_date,emp_code,item_code__new ) " +
                        "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    
            sql = "select line_no,item_code, quantity, unit, loc_code, lot_no, lot_sl, exp_date " +
                    "from rcp_backflush_rcpt where tran_id = '"+tranId+"' and upper(qc_reqd) = 'Y'" ;
            System.out.println("SQL : "+sql);
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                rcpLineNo = rs.getString("line_no");
                rcpItemCode = rs.getString("item_code");
                rcpQuantity = rs.getDouble("quantity");
                rcpUnit = rs.getString("unit");
                rcpLocCode = rs.getString("loc_code");
                rcpLotNo = rs.getString("lot_no");
                rcpLotSl = rs.getString("lot_sl");
                expDate = rs.getDate("exp_date");
                
                sql = "select case when qc_lead_time is null then 0 else qc_lead_time end , item_ser " +
                        "from item where item_code = '"+rcpItemCode+"'";
                System.out.println("SQL : "+sql);
                rs1 = stmt1.executeQuery(sql);
                if(rs1.next()){
                    qcLeadTime = rs1.getInt(1);
                    itemSer = rs1.getString(2);
                }
                rs1.close();
                
                qcDueDate = getRelativeDate(new java.util.Date(System.currentTimeMillis()),qcLeadTime);
                
                sql = "select item_ser from siteitem where site_code = '"+rcpSiteCode+"' and item_code = '"+rcpItemCode+"'";
                System.out.println("SQL : "+sql);
                rs1 = stmt1.executeQuery(sql);
                if(rs1.next()){
                    siteItemSer = rs1.getString("item_ser");
                }
                if(siteItemSer != null && siteItemSer.trim().length() > 0){
                    itemSer = siteItemSer;
                }
                 rs1.close();
                
                sql = "select key_string from transetup where tran_window = '"+winName+"'";
                System.out.println("SQL : "+sql);
                rs1 = stmt1.executeQuery(sql);
                if(rs1.next()){
                    keyString = rs1.getString("key_string");
                }
                rs1.close();
                
                if(keyString == null || keyString.trim().length() == 0){
                    sql = "select key_string from transetup where tran_window = 'GENERAL'";
                    System.out.println("SQL : "+sql);
                    rs1 = stmt1.executeQuery(sql);
                    if(rs1.next()){
                        keyString = rs1.getString("key_string");
                    }
                    rs1.close();
                }
                
                //comment by tarani lot no generated for the qc item
               /* if(rcpBackflushType != null && rcpBackflushType.trim().equalsIgnoreCase("S")){
                    qOrderType = "I";
                    rcpLotNo = qcNo;
                }else{
                    qOrderType = "S";
                }*/
                //290052007
                 qOrderType = "I";
                
                    
                
                String xmlValues = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
                xmlValues = xmlValues + "<Header></Header>";
                xmlValues = xmlValues + "<Detail1>";
                xmlValues = xmlValues + "<tran_id></tran_id>";
                xmlValues = xmlValues + "<site_code>"+rcpSiteCode+"</site_code>";
                xmlValues = xmlValues + "<qorder_type>"+ qOrderType + "</qorder_type>";
                xmlValues = xmlValues + "<qorder_date>"+currDate+"</qorder_date>";
                xmlValues = xmlValues + "<lot_no>"+rcpLotNo+"</lot_no>";
                xmlValues = xmlValues + "<item_ser>"+itemSer+"</item_ser>";
                xmlValues = xmlValues + "</Detail1></Root>";
                
                userId = genericUtility.getValueFromXTRA_PARAMS("loginCode",xtraParm);
                TransIDGenerator tg1 = new TransIDGenerator(xmlValues, userId, CommonConstants.DB_NAME);
                qcNo = tg1.generateTranSeqID("QC-ORD", "qorder_no", keyString, conn);
                
                System.out.println("Generated QC No : "+qcNo);
                if(qcNo.indexOf("Error") != -1){
                    errString = "Error";
                    return errString; 
                }
                //290052007
                if(rcpLotNo==null || rcpLotNo.trim().length()==0)
               	{
                    	rcpLotNo = qcNo;
                }
                
                sql = "update rcp_backflush_rcpt set lot_no = '"+rcpLotNo+"' where tran_id = '"+tranId+"' and line_no = "+rcpLineNo+"";
                System.out.println("SQL :"+sql);
                int upd = stmt1.executeUpdate(sql);
                System.out.println("Update in rcp_backflush_rcpt : "+upd);
                
                System.out.println("Inserting QC Order ::");
                pstmt = conn.prepareStatement(sqlInsert);
                pstmt.setString(1,qcNo);
                pstmt.setString(2,qOrderType);
                pstmt.setTimestamp(3,new Timestamp(System.currentTimeMillis()));
                pstmt.setString(4,rcpSiteCode);
                pstmt.setString(5,rcpItemCode);
                pstmt.setString(6," ");
                pstmt.setDouble(7,rcpQuantity);
                pstmt.setDouble(8,0);
                pstmt.setDouble(9,0);
                pstmt.setTimestamp(10,new Timestamp(System.currentTimeMillis()));
                pstmt.setTimestamp(11,new Timestamp(qcDueDate.getTime()));
                pstmt.setTimestamp(12,new Timestamp(System.currentTimeMillis()));
                pstmt.setString(13,tranId);
                
                porcpLineNo = "   " + porcpline;
                porcpLineNo = porcpLineNo.substring(porcpLineNo.length() - 3);
                
                pstmt.setString(14,porcpLineNo);
                pstmt.setString(15,rcpLotNo);
                pstmt.setString(16,rcpLotSl);
                pstmt.setTimestamp(17,new Timestamp(System.currentTimeMillis()));
                pstmt.setString(18,"SYSTEM");
                pstmt.setString(19,"SYSTEM");
                pstmt.setString(20,rcpLocCode);
                pstmt.setDouble(21,0);
                pstmt.setString(22,"U");
                pstmt.setString(23,rcpUnit);
                pstmt.setString(24,"T");
                pstmt.setString(25,"");
                if(expDate == null){
                    pstmt.setNull(26,Types.TIMESTAMP);
                }else{
                    pstmt.setTimestamp(26,new Timestamp(expDate.getTime()));
                }
                pstmt.setNull(27,Types.VARCHAR);
                pstmt.setNull(28,Types.VARCHAR);
                pstmt.setString(29,rcpUnit);
                pstmt.setString(30,rcpLotNo);
                pstmt.setNull(31,Types.TIMESTAMP);
                pstmt.setString(32,loginEmpCode);
                pstmt.setString(33,rcpItemCode);
                
                int intCount = pstmt.executeUpdate();
                System.out.println("Inserting Qc_order :"+intCount);
                pstmt.clearParameters();
            }
        }catch(Exception e){
            errString = "Error";
            System.out.println("Exception in RcpBackflushMultiConf [createQCOrder]"+e);
            e.printStackTrace();
            throw new ITMException(e);
        }
        return errString;
    }
    
    private java.util.Date getRelativeDate(java.util.Date currDate,int leadTime )throws ITMException
    {
        java.util.Date relativeDate = null;
        try{
            Calendar cal = Calendar.getInstance();
            cal.setTime(currDate);
            cal.add(Calendar.DATE,leadTime);
            relativeDate = cal.getTime();            
        }catch(Exception e){
            System.out.println("Exception "+e);
            e.printStackTrace();
            throw new ITMException(e);
        }
        return relativeDate;
    }
}
