package ibase.webitm.ejb.fin;

import java.sql.*;
import java.text.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.text.SimpleDateFormat;
import java.util.*;
import ibase.webitm.utility.*;
import java.util.HashMap;
import ibase.webitm.ejb.*;
import org.w3c.dom.*;

import ibase.webitm.ejb.fin.FinCommon;

public class InvAcct
{
	ValidatorEJB validator = new ValidatorEJB();
	public String acctPoRcpt(String tranId, Connection conn)throws ITMException
	{
		FinCommon finCommon = null;
        GenericUtility genericUtility = null;
		ITMDBAccessEJB itmDBAccessEJB = null;

		String sql = "",errString = "", errCode = "";
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmtUpd = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		java.sql.Timestamp tranDate = null, effDate = null;

		String siteCode = "", suppCode = "", itemSer = "", currCode = "";
		String purcOrder = "", postType = "", postProv = "", analCode = "";

		double excRate = 0, addAmtHdr = 0, frtAmt = 0, insurAmt = 0, clearAmt = 0, adjTotAmount = 0, amountNP = 0;
		double othChgAmt = 0, excRateFrt = 0, excRateIns = 0, excRateClr = 0, excRateOthCh = 0,tempValue = 0, actualAmount = 0;

		String remarks = "", pordType = "", projCode = "", acctType = "", currCodeBase = "";
		String invOnline = "",vouchOnLine = "", invAcct = "", acctCodeChrg = "", cctrCodeChrg = "";
		boolean bExit = false, qcReqd = false;
		int qcCount  = 0;
		String finEntity = "", acctAP = "", cctrAP = "", acctAdCost = "", cctrAdCost = "";
		String acctFreCost = "", cctrFreCost = "", acctCleCost = "", cctrCleCost = "", acctInsCost = "", cctrInsCost = "";
		double amountCR = 0, netAmount = 0, addAmount = 0, quantity = 0, stdRate = 0, grAmount = 0, recoAmount = 0, stdAmount = 0;

		String itemCode = "", lineNo = "", acctCodeCR = "", acctCodeDR = "", cctrCodeCR = "", cctrCodeDR = "", tranSer = "";
		String deptCode = "", acctCodeProvDR = "", acctCodeProvCR = "", cctrCodeProvDR = "", cctrCodeProvCR = "", mapKey = "";
		//double insurAmt = 0, clearAmt = 0, othChgAmt = 0, excRateFrt = 0, excRateIns = 0, excRateClr = 0, excRateOthCh = 0, amountNP = 0;
		HashMap poRcpMap = null, tempMap = null, glTraceMap = null;
		String acctCodePpv = "", cctrCodePpv = "", acctCodeReco = "", ccrtCodeReco = "", acctCodeNP = "", cctrCodeNP = "";
		
		try
		{
		
			finCommon = new FinCommon();
			genericUtility = GenericUtility.getInstance();
			itmDBAccessEJB = new ITMDBAccessEJB();

			sql = " SELECT TRAN_DATE, EFF_DATE, SITE_CODE, SUPP_CODE, " 
				+ " ITEM_SER, CURR_CODE, EXCH_RATE, TOTAL_ADDITIONAL_COST, PURC_ORDER, " 
				+ " POST_type,FRT_AMT,INSURANCE_AMT,CLEARING_CHARGES,OTHER_CHARGES, EXCH_RATE__FRT, " 
				+ " EXCH_RATE__INS, EXCH_RATE__CLR,EXCH_RATE__OTHCH, POST_PROV,ANAL_CODE, TRAN_SER "
				+ " FROM PORCP WHERE TRAN_ID = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				tranDate = rs.getTimestamp("TRAN_DATE");
				effDate = rs.getTimestamp("EFF_DATE");
				siteCode = rs.getString("SITE_CODE");
				suppCode = rs.getString("SUPP_CODE");
				itemSer = rs.getString("ITEM_SER");
				currCode = rs.getString("CURR_CODE");
				excRate = rs.getDouble("EXCH_RATE");
				addAmtHdr = rs.getDouble("TOTAL_ADDITIONAL_COST");
				purcOrder = rs.getString("PURC_ORDER");
				postType = rs.getString("POST_type");
				frtAmt = rs.getDouble("FRT_AMT");
				insurAmt = rs.getDouble("INSURANCE_AMT");
				clearAmt = rs.getDouble("CLEARING_CHARGES");
				othChgAmt = rs.getDouble("OTHER_CHARGES");
				excRateFrt = rs.getDouble("EXCH_RATE__FRT");
				excRateIns = rs.getDouble("EXCH_RATE__INS");
				excRateClr = rs.getDouble("EXCH_RATE__CLR");
				excRateOthCh = rs.getDouble("EXCH_RATE__OTHCH");
				postProv = rs.getString("POST_PROV");
				analCode = rs.getString("ANAL_CODE");
				tranSer = rs.getString("TRAN_SER");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if (postType == null)
			{
				postType = "A";
			}
			remarks = "Against purchase order no. " + purcOrder.trim();
			
			sql = "SELECT PORD_type,PROJ_CODE FROM PORDER WHERE PURC_ORDER = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,purcOrder);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				pordType = rs.getString("PORD_TYPE");
				projCode = rs.getString("PROJ_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,siteCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				currCodeBase = rs.getString("PORD_TYPE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			invOnline = finCommon.getFinparams("999999", "INV_ACCT_PORCP", conn);
			if ("NULLFOUND".equals(invOnline))
			{
				errCode = "VTFINPARM";
				errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
				return errString;
			}

			if (!"Y".equals(invOnline) || !"N".equals(invOnline) || !"S".equals(invOnline) )
			{
				errCode = "VTFINPARM";
				errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
				return errString;
			}
			
			vouchOnLine = finCommon.getFinparams("999999", "VOUCHER_CREATION", conn);
			if ("NULLFOUND".equals(vouchOnLine))
			{
				errCode = "VTFINPARM";
				errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
				return errString;
			}
			if (invOnline == null || invOnline.trim().length() ==  0)
			{
				invOnline = "N";
			}	
			if (vouchOnLine == null || vouchOnLine.trim().length() == 0)
			{
				vouchOnLine = "N";
			}	
			bExit = false;

			if ("S".equals(invOnline))
			{
				sql = "SELECT CASE WHEN S.INV_ACCT IS NULL THEN 'N' ELSE S.INV_ACCT END) AS INV_ACCT "
						+" FROM PORCPDET D, ITEM I, ITEMSER S "
						+ " WHERE D.ITEM_CODE = I.ITEM_CODE "
						+ " AND S.ITEM_SER = I.ITEM_SER "
						+ " AND D.TRAN_ID = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCode);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					invAcct = rs.getString("INV_ACCT");
					if (!"Y".equals(invAcct))
					{
						bExit = true;
						//break;
					}
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if (bExit == true)
				{
					errCode = "VTFINPARM";
					errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
					return errString;
				}
			}
			
			sql = "SELECT COUNT(QC_REQD) FROM ITEM "
				+ " WHERE ITEM_CODE IN (SELECT ITEM_CODE FROM PORCPDET "
				+ " WHERE TRAN_ID = ?) AND QC_REQD = 'Y'";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				qcCount = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			if (qcCount > 0)
			{
				qcReqd = true;
			}
			else	
			{
				qcReqd = false;
			}
			if ("Y".equals(invOnline) ||("S".equals(invOnline) && bExit != true))
			{
				sql = "SELECT FIN_ENTITY FROM SITE WHERE SITE_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCode);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					finEntity = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if (postProv == null || postProv.trim().length() == 0 || "N".equals(postProv))
				{
					cctrAP = finCommon.getAcctDetrTtype(" ", itemSer, "PORCP", pordType, conn);
					if (cctrAP != null && cctrAP.trim().length() > 0)
					{
						acctAP = cctrAP.substring(0,cctrAP.indexOf(","));
						cctrAP = cctrAP.substring(cctrAP.indexOf(",")+1);
					}
					
					if (acctAP == null || acctAP.trim().length() == 0)
					{
						errCode = "VTACCTAP";
						errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
						return errString;
					}
					if (cctrAP == null)
					{
						cctrAP = " ";
					}
				}
				
				cctrAdCost = finCommon.getAcctDetrTtype(" ", itemSer, "ADDCOST", pordType, conn);
				if (cctrAdCost != null && cctrAdCost.trim().length() > 0)
				{
					acctAdCost = cctrAdCost.substring(0,cctrAdCost.indexOf(","));
					cctrAdCost = cctrAdCost.substring(cctrAdCost.indexOf(",")+1);
				}

				cctrFreCost = finCommon.getAcctDetrTtype(" ", itemSer, "FRECOST", pordType, conn);
				if (cctrFreCost != null && cctrFreCost.trim().length() > 0)
				{
					acctFreCost = cctrFreCost.substring(0,cctrFreCost.indexOf(","));
					cctrFreCost = cctrFreCost.substring(cctrFreCost.indexOf(",")+1);
				}
				if (acctFreCost == null || acctFreCost.trim().length() == 0)
				{
					acctFreCost = acctAdCost;
					cctrFreCost = cctrAdCost;
				}
				
				cctrCleCost = finCommon.getAcctDetrTtype(" ", itemSer, "CLECOST", pordType, conn);
				if (cctrCleCost != null && cctrCleCost.trim().length() > 0)
				{
					acctCleCost = cctrCleCost.substring(0,cctrCleCost.indexOf(","));
					cctrCleCost = cctrCleCost.substring(cctrCleCost.indexOf(",")+1);
				}
				if (acctCleCost == null || acctCleCost.trim().length() == 0)
				{
					acctCleCost = acctAdCost;
					cctrCleCost = cctrAdCost;
				}
			
				cctrInsCost = finCommon.getAcctDetrTtype(" ", itemSer, "INSCOST", pordType, conn);
				if (cctrInsCost != null && cctrInsCost.trim().length() > 0)
				{
					acctInsCost = cctrInsCost.substring(0,cctrInsCost.indexOf(","));
					cctrInsCost = cctrInsCost.substring(cctrInsCost.indexOf(",")+1);
				}
				if (acctInsCost == null || acctInsCost.trim().length() == 0)
				{
					acctInsCost = acctAdCost;
					cctrInsCost = cctrAdCost;
				}
				amountCR = 0;
				if ( "Y".equals(invOnline) || ("S".equals(invOnline) && bExit == false))
				{
					poRcpMap = new HashMap();
					// Cursor to get PO Detail Data
					// In below select acct_code__prov_dr,acct_code__prov_cr,cctr_code__prov_dr,cctr_code__prov_cr-Added by fatema - 03/04/2007-DI7SUN0018
					sql = "select item_code, line_no, "
						+ " acct_code__cr, acct_code__dr,   "
						+ " cctr_code__cr, cctr_code__dr, (case when net_amt is null then 0 else net_amt end) as net_amt, " 
						+ "	(case when additional_cost is null then 0 else additional_cost end) as additional_cost, "
						+ "	quantity, std_rate, dept_code, "
						+ " acct_code__prov_dr, acct_code__prov_cr, cctr_code__prov_dr, cctr_code__prov_cr "
						+ " from porcpdet where tran_id = ? " ;
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,tranId);
					rs = pstmt.executeQuery();
					while (rs.next())
					{
						// In below fetch ls_adr_prov,ls_acr_prov,ls_cdr_prov,ls_ccr_prov-Added by fatema - 03/04/2007-DI7SUN0018
						itemCode = rs.getString("item_code");
						lineNo = rs.getString("line_no");
						acctCodeCR = rs.getString("acct_code__cr");
						acctCodeDR = rs.getString("acct_code__dr");
						cctrCodeCR = rs.getString("cctr_code__cr");
						cctrCodeDR = rs.getString("cctr_code__dr");
						netAmount = rs.getDouble("net_amt");
						addAmount = rs.getDouble("additional_cost");
						quantity = rs.getDouble("quantity");
						stdRate = rs.getDouble("std_rate");
						deptCode = rs.getString("dept_code");
						acctCodeProvDR = rs.getString("acct_code__prov_dr");
						acctCodeProvCR = rs.getString("acct_code__prov_cr");
						cctrCodeProvDR = rs.getString("cctr_code__prov_dr");
						cctrCodeProvCR = rs.getString("cctr_code__prov_cr");
						if (cctrCodeDR == null || cctrCodeDR.trim().length() == 0 )
						{
							if (cctrCodeCR != null && cctrCodeCR.trim().length() > 0)
							{
								cctrCodeDR = cctrCodeCR;
							}
						}
						if (cctrCodeCR == null || cctrCodeCR.trim().length() == 0 )
						{
							if (cctrCodeDR == null && cctrCodeDR.trim().length() > 0)
							{
								cctrCodeCR = cctrCodeDR;
							}
						}
						// 28/10/02 end
						if (cctrAP == null || cctrAP.trim().length() == 0 )
						{
							cctrAP = cctrCodeCR;
						}
						//added by prince --13-10-06
						if (cctrFreCost == null || cctrFreCost.trim().length() == 0)
						{
							cctrFreCost = cctrCodeCR;
						}
						if (cctrCleCost == null || cctrCleCost.trim().length() == 0)
						{
							cctrCleCost = cctrCodeCR;
						}
						if (cctrInsCost == null || cctrInsCost.trim().length() == 0)
						{
							cctrInsCost = cctrCodeCR;
						}
						//ended by prince
						
						//dept code added by sandip 27/05/05
						if (deptCode == null || deptCode.trim().length() == 0)
						{
							deptCode = " ";
						}
						
						
						///////////////////////////////////////////////////////////////
						// ********************** IMPORTANT *************************//
						///////////////////////////////////////////////////////////////
						// 23/03/02 manoharan new column 'type' added in d_porcp
						// for additional cost it will be 'A' and all other amount
						// it will be 'X'
						// in all the dw find function it should be considered
						// because the acct/cctr will be same 
						// Purpose :- additional cost will be in base currency
						// posting should be done separately
													
						// Loop to process the Accounting Effect
						// 28/03/02 mamoharan based on old object
						amountCR = amountCR + netAmount;
						
						// Added by fatema - 03/04/2007 - DI7SUN0018
						if (postProv != null && "Y".equals(postProv))
						{
							acctAP = acctCodeProvCR;
							cctrAP = cctrCodeProvCR;
							
							if (acctAP  == null || acctAP.trim().length() == 0)
							{
								errCode = "VTPROVACCT";
								errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
								break;
							}
							if (cctrAP == null)
							{
								cctrAP = " ";
							}
							
							acctCodeDR = acctCodeProvDR;
							cctrCodeDR = cctrCodeProvDR;
							
							if (acctCodeDR == null || acctCodeDR.trim().length() == 0)
							{
								errCode = "VTPROVACCT";
								errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
								break;
							}
						}
						// Ended by fatema - 03/04/2007 - DI7SUN0018
						
						// If ACCT Code is NULL/SPACE Then Exit
						if (acctCodeDR == null || acctCodeDR.trim().length() == 0)
						{
							  errCode = "VTACCTPO";
							  errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
							  break;
						}
						// If CCTR Code is NULL Then Space
						if (cctrCodeDR == null)
						{
							cctrCodeDR = " ";
						}
						
						if ("S".equals(postType))
						{
							/// amish 05-10-04 // if post type is s then transaction to be post in base currency					
							currCode = currCodeBase;
							excRate = 1; 
							///////////////////end by amish 05-10-04

							/// amish pick up the ppv a/c and cctr				
							cctrCodePpv = finCommon.getAcctDetrTtype(" ", itemSer, "PPV", pordType, conn);
							if (cctrCodePpv != null && cctrCodePpv.trim().length() > 0)
							{
								acctCodePpv = cctrCodePpv.substring(0,cctrCodePpv.indexOf(","));
								cctrCodePpv = cctrCodePpv.substring(cctrCodePpv.indexOf(",")+1);
							}
							if (acctCodePpv == null || acctCodePpv.trim().length() == 0)
							{
							  errCode = "VTACCTPP";
							  errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
							  break;
							}
						}
						
						
						if (addAmount != 0)
						{
							if (poRcpMap.containsKey("A" + acctCodeDR + cctrCodeDR ))
							{
								tempMap = (HashMap) poRcpMap.get("A" + acctCodeDR + cctrCodeDR);
								grAmount = Double.parseDouble(tempMap.get("amount").toString());
								tempMap.put("amount", grAmount + addAmount);
							}
							else
							{
								tempMap = new HashMap();
								tempMap.put("type", "A");
								tempMap.put("acct_code", acctCodeDR);
								tempMap.put("cctr_code", cctrCodeDR);
								tempMap.put("amount", addAmount);
							}
							poRcpMap.put("A" + acctCodeDR + cctrCodeDR, tempMap);
						}
							
						if ("S".equals(postType))
						{
							// post inventory at standards						
							/// and diff to PPV a/c				
							stdAmount = quantity * stdRate;	
							
							if (stdAmount != 0)
							{
								if (poRcpMap.containsKey("X" + acctCodeDR + cctrCodeDR ))
								{
									tempMap = (HashMap) poRcpMap.get("X" + acctCodeDR + cctrCodeDR);
									grAmount = Double.parseDouble(tempMap.get("amount").toString());
									tempMap.put("amount", grAmount + stdAmount);
								}
								else
								{
									tempMap = new HashMap();
									tempMap.put("type", "X");
									tempMap.put("acct_code", acctCodeDR);
									tempMap.put("cctr_code", cctrCodeDR);
									tempMap.put("amount", stdAmount);
								}
								poRcpMap.put("A" + acctCodeDR + cctrCodeDR, tempMap);
							}
						}		
						else						
						{
								
							if (netAmount != 0)
							{
								if (poRcpMap.containsKey("X" + acctCodeDR + cctrCodeDR ))
								{
									tempMap = (HashMap) poRcpMap.get("X" + acctCodeDR + cctrCodeDR);
									grAmount = Double.parseDouble(tempMap.get("amount").toString());
									tempMap.put("amount", grAmount + netAmount);
								}
								else
								{
									tempMap = new HashMap();
									tempMap.put("type", "X");
									tempMap.put("acct_code", acctCodeDR);
									tempMap.put("cctr_code", cctrCodeDR);
									tempMap.put("amount", netAmount);
								}
								poRcpMap.put("A" + acctCodeDR + cctrCodeDR, tempMap);
							}
						}
						
						if ("A".equals(postType))
						{
						
							// Cursor for Tax recovery for the item, if any
							sql = "SELECT ACCT_CODE__RECO,	CCTR_CODE__RECO, SUM(RECO_AMOUNT) AS RECO_AMOUNT "
								+ " FROM TAXTRAN "
								+ " WHERE TRAN_CODE= ?  "
								+ " AND TRAN_ID	= ? "
								+ " AND LINE_NO	= ? "
								+ " AND RECO_AMOUNT <> 0 "
								+ " GROUP BY ACCT_CODE__RECO, CCTR_CODE__RECO " ;
											
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1,tranSer);
							pstmt1.setString(1,tranId);
							pstmt1.setString(1,lineNo);
							rs1 = pstmt1.executeQuery();
							while (rs1.next())
							{
								acctCodeReco = rs1.getString("ACCT_CODE__RECO");
								ccrtCodeReco = rs1.getString("CCTR_CODE__RECO");
								recoAmount  = rs1.getDouble("RECO_AMOUNT");
								if (acctCodeReco == null || acctCodeReco.trim().length() == 0)
								{
									// Selecting ACCT/CCTR Code from ITEM_ACCT_DETR Table
									// shiri 22/04/02 changed func call from gbf_acct_detr to gbf_acct_detr_type for a/cing on tran type
									ccrtCodeReco = finCommon.getAcctDetrTtype(itemCode, itemSer, "TAXRECO", pordType, conn);
									if (ccrtCodeReco != null && ccrtCodeReco.trim().length() > 0)
									{
										acctCodeReco = ccrtCodeReco.substring(0,ccrtCodeReco.indexOf(","));
										ccrtCodeReco = ccrtCodeReco.substring(ccrtCodeReco.indexOf(",")+1);
									}
								}
								
								// If ACCT Code is NULL/SPACE Then Exit
								if (acctCodeReco  == null || acctCodeReco.trim().length() == 0)
								{
									errCode = "VTACCTRECO";
									errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
									break;
								}
								
								// If CCTR Code is NULL/SPACE Then set to inventory cost centre
								// 28/10/02 manoharan
								//if isnull(ccrtCodeReco) then
								if (ccrtCodeReco == null || ccrtCodeReco.trim().length() == 0)
								{
									// 28/10/02 end
									ccrtCodeReco = cctrCodeDR;
								}
							
								// If CCTR Code is still NULL/SPACE Then set to blank
								if (ccrtCodeReco ==  null)
								{
									ccrtCodeReco =  " ";
								}
								// the tax recovery amount is subtracted from the effect going to the inventory
								///amish for std acct
								tempMap.put("amount", grAmount - recoAmount);
								poRcpMap.put("A" + acctCodeDR + cctrCodeDR, tempMap);
							
								////////////////////////////////////////////////////////////
								// 23/03/02 consider type additional cost should be posted 
								// separately
								if (poRcpMap.containsKey("X" + acctCodeReco + ccrtCodeReco ))
								{
									tempMap = (HashMap) poRcpMap.get("X" + acctCodeReco + ccrtCodeReco);
									grAmount = Double.parseDouble(tempMap.get("amount").toString());
									tempMap.put("amount", grAmount + recoAmount);
								}
								else
								{
									tempMap = new HashMap();
									tempMap.put("type", "X");
									tempMap.put("acct_code", acctCodeDR);
									tempMap.put("cctr_code", cctrCodeDR);
									tempMap.put("amount", recoAmount);
								}
								poRcpMap.put("X" + acctCodeReco + ccrtCodeReco, tempMap);
							}
							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;
							
							// If error then exit
							if (errString != null && errString.trim().length() > 0)
							{
								break;
							}
						
							// Cursor for non payable taxes to be removed from the effect to unbooked purchases
							sql = "SELECT A.ACCT_CODE, A.CCTR_CODE, SUM(A.TAX_AMT) AS TAX_AMT "
								+ " FROM TAXTRAN A, TAX B "
								+ " WHERE A.TAX_CODE = B.TAX_CODE "
								+ " AND A.TRAN_CODE = ? "
								+ " AND A.TRAN_ID = ? " 
								+ " AND A.LINE_NO = ? "
								+ " A.TAX_AMT <> 0 "
								+ " B.NON_PAYABLE = 'Y' "
								+ " GROUP BY A.ACCT_CODE, A.CCTR_CODE" ;
											
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1,tranSer);
							pstmt1.setString(2,tranId);
							pstmt1.setString(3,lineNo);
							rs1 = pstmt1.executeQuery();
							while (rs1.next())
							{
							
								acctCodeNP = rs1.getString("ACCT_CODE");
								cctrCodeNP = rs1.getString("CCTR_CODE");
								amountNP = rs1.getDouble("TAX_AMT");
								
								// If ACCT Code is NULL/SPACE Then Exit
								if (acctCodeNP  == null || acctCodeNP.trim().length() == 0)
								{
									errCode = "VMACCT1";
									errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
									break;
								}
								
								// If CCTR Code is NULL/SPACE Then set to inventory cost centre
								if (cctrCodeNP == null)
								{
									cctrCodeNP = cctrCodeDR;
								}
							
								// If CCTR Code is still NULL/SPACE Then set to blank
								if (cctrCodeNP == null)
								{
									cctrCodeNP = " ";
								}
							
								// before changing sign subtract from credit amount to go to unbooked purchases
								//amountCR = amountCR + netAmount - amountNP
								amountCR = amountCR - amountNP;
							
								// chnage sign so that it goes as credit
								amountNP = 0 - amountNP;
								////////////////////////////////////////////////////
								// 23/03/02 consider type - additional cost posting
								// separate
								//
								//// cr effect being generated for the non payable tax
								//ll_taxrow = poRcpMap.Find( &
								//		"acct_code = '"+ acctCodeNP + "' and cctr_code = '" + cctrCodeNP + "'", 1, ll_nbr);
								//if ll_taxrow = 0 then
								//	ll_taxrow = poRcpMap.insertrow(0)
								//	poRcpMap.setitem(ll_taxrow,"acct_code",acctCodeNP)
								//	poRcpMap.setitem(ll_taxrow,"cctr_code",cctrCodeNP)
								//	poRcpMap.setitem(ll_taxrow,"amount",amountNP)
								//elseif ll_taxrow > 0 then
								//	grAmount = poRcpMap.getitemnumber(ll_taxrow,"amount")
								//	poRcpMap.setitem(ll_taxrow,"amount",grAmount + amountNP)
								//end if
								// cr effect being generated for the non payable tax
								//ll_taxrow = poRcpMap.Find( &
								//		" type = 'X' and acct_code = '"+ acctCodeNP + "' and cctr_code = '" + cctrCodeNP + "'", 1, ll_nbr);
								// gf_nulltostr() called  to convert null to blank string by Amit on 19/09/03 for DB2.		

								if (poRcpMap.containsKey("X" + acctCodeNP + cctrCodeNP ))
								{
									tempMap = (HashMap) poRcpMap.get("X" + acctCodeReco + ccrtCodeReco);
									grAmount = Double.parseDouble(tempMap.get("amount").toString());
									tempMap.put("amount", grAmount + amountNP);
								}
								else
								{
									tempMap = new HashMap();
									tempMap.put("type", "X");
									tempMap.put("acct_code", acctCodeNP);
									tempMap.put("cctr_code", cctrCodeNP);
									tempMap.put("amount", amountNP);
								}
								poRcpMap.put("X" + acctCodeNP + cctrCodeNP, tempMap);
							}
							rs1.close();
							rs1 = null;
							pstmt1.close();
							pstmt1 = null;
						} // post actual
										
						///// this code if for posting ppv at grn
						//// amish for standard accounting
						/// post diff to PPV account.
						//if postType = 'S' then 					
						//	
						//	ll_nbr = poRcpMap.RowCount()
						//	
						//	netAmount = poRcpMap.getitemnumber(ll_foundrow,"net_amt")										
						//	lc_actual = addAmount + (netAmount * excRate) 
						//	stdAmount = quantity * stdRate	
						//	/// diff amt should be calculat in base curr
						//	lc_diffamt = lc_actual - ( stdAmount * excRate) 
						//	
						//	if lc_diffamt <> 0 then							
						//		
						//		ll_foundrow = poRcpMap.Find( &
						//				" type = 'A' and acct_code = '" + gf_nulltostr(acctCodeDR) +"' and cctr_code = '" + gf_nulltostr(cctrCodeDR) + "'", 1, ll_nbr);
						//		if ll_foundrow = 0 then
						//			ll_foundrow = poRcpMap.insertrow(0)
						//			poRcpMap.setitem(ll_foundrow,"type",'A')
						//			poRcpMap.setitem(ll_foundrow,"acct_code",acctCodePpv)
						//			poRcpMap.setitem(ll_foundrow,"cctr_code",cctrCodePpv)
						//			poRcpMap.setitem(ll_foundrow,"amount",lc_diffamt)
						//		elseif ll_foundrow > 0 then
						//			grAmount = poRcpMap.getitemnumber(ll_foundrow,"amount")
						//			poRcpMap.setitem(ll_foundrow,"amount",grAmount + lc_diffamt)
						//		end if						
						//	end if
						//	
						//end if
						// 19/01/2009 manoharan commented while sqlca.sqlcode  = 0 creating problem as
						// there were many other select statements inside the loop
						//
						// In below fetch acctCodeProvDR,acctCodeProvCR,cctrCodeProvDR,cctrCodeProvCR-Added by fatema - 03/04/2007-DI7SUN0018
						//fetch cur_rcpdet into :itemCode, :lineNo,
						//							:acctCodeCR, :acctCodeDR, 
						//							:cctrCodeCR, :cctrCodeDR, :netAmount, :addAmount, 
						//							:quantity, :stdRate, :deptCode, //dept code added by sandip 27/05/05
						//							:acctCodeProvDR, :acctCodeProvCR, :cctrCodeProvDR, :cctrCodeProvCR ;
						// end 19/01/2009 manoharan
					} // end porcpdet
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					// If error then exit
					if (errString != null && errString.trim().length() > 0)
					{
						return errString;
					}
					
					// Initialising the variable to ZERO
					netAmount = 0;
					grAmount = 0;
					actualAmount = 0;
					Map.Entry poRcpMapEntry =  null;
					Set poRcpSet = poRcpMap.entrySet();
					Iterator itrPoRcp = poRcpSet.iterator();
					while(itrPoRcp.hasNext())
					{
						poRcpMapEntry = (Map.Entry)itrPoRcp.next();
						mapKey = (String)poRcpMapEntry.getKey();
						tempMap = (HashMap)poRcpMap.get(mapKey);
						
						// Debit Entry for Inventory / credit entry for non payable taxes
						acctCodeDR	= (String) tempMap.get("acct_code");
						cctrCodeDR	= (String) tempMap.get("cctr_code");
						grAmount = Double.parseDouble(tempMap.get("amount").toString());
						//actualAmount = poRcpMap.getitemnumber(i,"net_amt") //amish 
							
						// shiri 22/12/01
						if ("P-RET".equals(tranSer))
						{
							grAmount = 0 - grAmount;
							//actualAmount = 0 - actualAmount //amish 
						}
						glTraceMap = new HashMap();
						glTraceMap.put("tran_date",tranDate);
						glTraceMap.put("eff_date",effDate);
						glTraceMap.put("fin_entity",finEntity);
						glTraceMap.put("site_code",siteCode);
						glTraceMap.put("sundry_type","O");
						//glTraceMap.put("sundry_code",);
						glTraceMap.put("acct_code",acctCodeDR);
						glTraceMap.put("cctr_code",cctrCodeDR);
						//glTraceMap.put("emp_code",);
						glTraceMap.put("dept_code",deptCode);
						glTraceMap.put("proj_code",projCode);
						glTraceMap.put("anal_code ",analCode);

						if ("A".equals( (String) tempMap.get("type")) )
						{
							glTraceMap.put("curr_code",currCodeBase);
							glTraceMap.put("exch_rate", 1);
						}
						else
						{
							glTraceMap.put("curr_code",currCode);
							glTraceMap.put("exch_rate", excRate);
						}

						if (grAmount > 0 )
						{
							glTraceMap.put("dr_amt",grAmount);
							glTraceMap.put("cr_amt","0");
						}
						else
						{
							glTraceMap.put("dr_amt","0");
							glTraceMap.put("cr_amt",-1 * grAmount);
						}
						glTraceMap.put("ref_type","D");
						glTraceMap.put("ref_ser",tranSer);
						glTraceMap.put("ref_id",tranId);
						glTraceMap.put("remarks",remarks);
						
						errString = finCommon.glTraceUpdate(glTraceMap,conn);
						glTraceMap = null;
						if(errString != null && errString.trim().length() > 0 )
						{
							break;
						}
						///////////////////////////////////////////////////////////
						// 07/04/02 manoharan additional cost not to be added to net
						// because additonal cost of header will posted separately 
						if (!"A".equals( (String) tempMap.get("type")) )
						{
							netAmount = netAmount + grAmount;
							//if postType = 'S' then // amish 
							//	netAmount = netAmount + actualAmount
							//else							
							//	netAmount = netAmount + grAmount
							//end if

						}
							//////////// 07/04/02 //////////////////////////////////////
					}
					if(errString != null && errString.trim().length() > 0 )
					{
						return errString;
					}
					///////////////////////////////////////////////////////////
					
					// Assigning the PO Receipt A/c & CC Code to the variable
					acctCodeCR = acctAP;
					cctrCodeCR = cctrAP;
					
					//shiri modified this posting instead of using netAmount, lc_amount_hdr is used so that the credit for
					//the additional cost can be taken separately in the posting - 29/11/01
					//on 20/12/01 used separate credit amount as it is net off non payable taxes
					// Crediting Entry for PO Receipt
					if (netAmount != 0 )
					{
						// the sign of netAmount is already reverted while recalculating
						//// shiri 22/12/01
						//if as_transer = 'P-RET' then
						//	netAmount = 0 - netAmount
						//end if	
						glTraceMap = new HashMap();

						glTraceMap.put("tran_date",tranDate);
						glTraceMap.put("eff_date",effDate);
						glTraceMap.put("fin_entity",finEntity);
						glTraceMap.put("site_code",siteCode);
						glTraceMap.put("sundry_type","O");
						glTraceMap.put("acct_code",acctCodeCR);
						glTraceMap.put("cctr_code",cctrCodeCR);
						glTraceMap.put("dept_code",deptCode);
						glTraceMap.put("anal_code ",analCode);
						glTraceMap.put("curr_code",currCode);
						glTraceMap.put("exch_rate", excRate);
						if (grAmount > 0 )
						{
							glTraceMap.put("dr_amt","0");
							glTraceMap.put("cr_amt",netAmount);
						}
						else
						{
							glTraceMap.put("dr_amt",-1 * netAmount);
							glTraceMap.put("cr_amt","0");
						}
						glTraceMap.put("ref_type","D");
						glTraceMap.put("ref_ser",tranSer);
						glTraceMap.put("ref_id",tranId);
						glTraceMap.put("remarks",remarks);
						
						errString = finCommon.glTraceUpdate(glTraceMap,conn);
						glTraceMap = null;
						if(errString != null && errString.trim().length() > 0 )
						{
							return errString;
						}
					}
					
					//credit entry for the additional cost
					//added by prince --31-05-06
					// if the total addnl cost entered does not match the break up, then the posting is to be done only for the total
					adjTotAmount = (frtAmt * excRateFrt) + (insurAmt * excRateIns) + (clearAmt * excRateClr) + (othChgAmt * excRateOthCh);
					
											
					if	(adjTotAmount != addAmtHdr)
					{
						//ended by prince	
						//if addAmtHdr <> 0 and postType = 'A' then 								
						if (addAmtHdr != 0 )  /// amish 30-12-04 post additional cost for standard and actual both
						{
							
							// if ACCT Code is NULL/SPACE Then Exit
							if (acctAdCost == null || acctAdCost.trim().length() == 0)
							{
								errCode = "VMACCT1";
								errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
								return errString;
							}
									
							// if additional cost centre is null then set to ap cost centre
							if (cctrAdCost == null || cctrAdCost.trim().length() == 0)
							{
								cctrAdCost = cctrCodeCR;
							}
							// if additional cost centre is still null then set to space
							if (cctrAdCost == null )
							{
								cctrAdCost = " ";
							}
							
							// Ashok 14/02/03
							if ("P-RET".equals(tranSer))
							{
								addAmtHdr = -1 * addAmtHdr;
							}
							// End of changes on 14/02/03					
							glTraceMap = new HashMap();

							glTraceMap.put("tran_date",tranDate);
							glTraceMap.put("eff_date",effDate);
							glTraceMap.put("fin_entity",finEntity);
							glTraceMap.put("site_code",siteCode);
							glTraceMap.put("sundry_type","O");
							glTraceMap.put("acct_code",acctAdCost);
							glTraceMap.put("cctr_code",cctrAdCost);
							glTraceMap.put("dept_code",deptCode);

							glTraceMap.put("curr_code",currCodeBase);
							glTraceMap.put("exch_rate", 1);
							if (grAmount > 0 )
							{
								glTraceMap.put("dr_amt","0");
								glTraceMap.put("cr_amt",addAmtHdr);
							}
							else
							{
								glTraceMap.put("dr_amt",-1 * addAmtHdr);
								glTraceMap.put("cr_amt","0");
							}
							glTraceMap.put("ref_type","D");
							glTraceMap.put("ref_ser",tranSer);
							glTraceMap.put("ref_id",tranId);
							glTraceMap.put("remarks",remarks);
							
							errString = finCommon.glTraceUpdate(glTraceMap,conn);
							glTraceMap = null;
							if(errString != null && errString.trim().length() > 0 )
							{
								return errString;
							}
						}
						//ended by prince 25-01-06
					}
					else
					{
						// if the total matches the break up, then individual posting is to be done
						//added by prince 27-01-06
						// reset this dw so that there is no previous data, as the posting will be done from the data now generated
						// all previous data has been already posted and has no use here
						poRcpMap = null;
						if (addAmtHdr != 0)
						{
							for ( int i = 1; i < 4; i++)
							{
								tempValue = 0;
								if (i == 1 && frtAmt != 0)
								{
									//tempValue = frtAmt //prince --28-10-06
									tempValue = frtAmt * excRateFrt; //prince --28-10-06
									acctCodeChrg = acctFreCost;
									cctrCodeChrg = cctrFreCost;
								}
								else if (i == 2 && insurAmt != 0)
								{
									//tempValue = insurAmt //prince --28-10-06
									tempValue = insurAmt * excRateIns;
									acctCodeChrg = acctInsCost;
									cctrCodeChrg = cctrInsCost;
								}
								else if (i == 3 && clearAmt != 0)
								{
									//tempValue = clearAmt //prince --28-10-06
									tempValue = clearAmt * excRateClr;
									acctCodeChrg = acctCleCost;
									cctrCodeChrg = cctrCleCost;
								}
								else if (i == 4 && othChgAmt != 0)
								{
									//tempValue = othChgAmt //prince --28-10-06
									tempValue = othChgAmt * excRateOthCh;
									acctCodeChrg = acctAdCost;
									cctrCodeChrg = cctrAdCost;
								}
								
								// if additional cost centre is null then set to ap cost centre
								if (cctrAdCost  == null || cctrAdCost.trim().length() == 0)
								{
									cctrAdCost = cctrCodeCR;
								}
								// if additional cost centre is still null then set to space
								if (cctrAdCost ==  null )
								{
									cctrAdCost = " ";
								}
								
								if (acctAdCost == null || acctAdCost.trim().length() == 0)
								{
									errCode = "VMACCT1";
									errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
									break;
								}
																
								if (tempValue != 0)
								{
									if (poRcpMap.containsKey("A" + acctCodeChrg + cctrCodeChrg ))
									{
										tempMap = (HashMap) poRcpMap.get("X" + acctCodeChrg + ccrtCodeReco);
										grAmount = Double.parseDouble(tempMap.get("amount").toString());
										tempMap.put("amount", grAmount + tempValue);
									}
									else
									{
										tempMap = new HashMap();
										tempMap.put("type", "A");
										tempMap.put("acct_code", acctCodeChrg);
										tempMap.put("cctr_code", cctrCodeChrg);
										tempMap.put("amount", tempValue);
									}
									poRcpMap.put("A" + acctCodeChrg + cctrCodeChrg, tempMap);
								}
							}
						}
						if(errString != null && errString.trim().length() > 0 )
						{
							return errString;
						}

						poRcpMapEntry =  null;
						poRcpSet = poRcpMap.entrySet();
						itrPoRcp = poRcpSet.iterator();
						while(itrPoRcp.hasNext())
						{
							poRcpMapEntry = (Map.Entry)itrPoRcp.next();
							mapKey = (String)poRcpMapEntry.getKey();
							tempMap = (HashMap)poRcpMap.get(mapKey);
							
							// Debit Entry for Inventory / credit entry for non payable taxes
							acctCodeChrg	= (String) tempMap.get("acct_code");
							cctrCodeChrg	= (String) tempMap.get("cctr_code");
							tempValue = Double.parseDouble(tempMap.get("amount").toString());
							acctType =  (String) tempMap.get("type");
						
												
							if ("A".equals(acctType) && "P-RET".equals(tranSer))
							{
								tempValue = -1 * tempValue;
							}
							// End of changes on 14/02/03					
							glTraceMap = new HashMap();

							glTraceMap.put("tran_date",tranDate);
							glTraceMap.put("eff_date",effDate);
							glTraceMap.put("fin_entity",finEntity);
							glTraceMap.put("site_code",siteCode);
							glTraceMap.put("sundry_type","O");
							glTraceMap.put("acct_code",acctCodeChrg);
							glTraceMap.put("cctr_code",cctrCodeChrg);
							glTraceMap.put("dept_code",deptCode);

							glTraceMap.put("curr_code",currCodeBase);
							glTraceMap.put("exch_rate", 1);
							if (grAmount > 0 )
							{
								glTraceMap.put("dr_amt","0");
								glTraceMap.put("cr_amt",tempValue);
							}
							else
							{
								glTraceMap.put("dr_amt",-1 * tempValue);
								glTraceMap.put("cr_amt","0");
							}
							glTraceMap.put("ref_type","D");
							glTraceMap.put("ref_ser",tranSer);
							glTraceMap.put("ref_id",tranId);
							glTraceMap.put("remarks",remarks);
							
							errString = finCommon.glTraceUpdate(glTraceMap,conn);
							glTraceMap = null;
							if(errString != null && errString.trim().length() > 0 )
							{
								return errString;
							}
						}
					}
					//ended by prince

					//--------------------
					// 28/09/00 manoharan check coin diff.

					if(errString != null && errString.trim().length() > 0 )
					{
						return errString;
					}
					errString = finCommon.checkGlTranDrCr(tranSer,tranId,conn);
					if(errString != null && errString.trim().length() > 0)
					{
						return errString;
					}
					//--------------------------
				} // inventory accounting on
			} // inventory accounting on
			
			// If QC is required OR Create Voucher Online is No Then
			// Debit the Inventory & Credit PO Receipt
			
			// amit-26-04-02
			if (qcReqd == false && "Y".equals(vouchOnLine))
			{
				errString = "CREATE-VOUCHER";
			}
			sql = "update porcp set acct_inv_online = ?, acct_porcp_online = ? "
				+ " where tran_id = ? ";
			pstmtUpd = conn.prepareStatement(sql);
			pstmtUpd.setString(1,invOnline);
			pstmtUpd.setString(2,vouchOnLine);
			pstmtUpd.setString(3,tranId);
			pstmtUpd.executeUpdate();
			// end - amit-26-04-02
		}//try
		catch(Exception exception)
		{   
			exception.printStackTrace();
			throw new ITMException(exception);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close(); rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close(); pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	    return (errString);
	}


}