/*
* $RCSfile: InvoiceEJB.java,v $ $Revision: 1.1.1.1 $ $Date: 2005/04/28 20:21:27 $ - $Author: mking_cv $
*
* The contents of this file are subject to the Open Software License
* Version 2.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.centraview.com/opensource/license.html
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is: CentraView Open Source.
*
* The developer of the Original Code is CentraView. Portions of the
* Original Code created by CentraView are Copyright (c) 2004 CentraView,
* LLC; All Rights Reserved. The terms "CentraView" and the CentraView
* logos are trademarks and service marks of CentraView, LLC.
*/
package com.centraview.account.invoice;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.centraview.account.common.ItemElement;
import com.centraview.account.common.ItemLines;
import com.centraview.account.helper.AccountHelperLocal;
import com.centraview.account.helper.AccountHelperLocalHome;
import com.centraview.administration.authorization.AuthorizationLocal;
import com.centraview.administration.authorization.AuthorizationLocalHome;
import com.centraview.common.CVDal;
import com.centraview.common.CVUtility;
import com.centraview.common.FloatMember;
import com.centraview.common.IntMember;
import com.centraview.common.StringMember;
public class InvoiceEJB implements EntityBean
{
protected javax.ejb.EntityContext ctx;
protected Context environment;
private InvoiceVO invoiceVO;
private boolean isDirty = false; //update data if isDirty is true (ejbStore)
private String dataSource = "MySqlDS";
/*
* Create Invoice record in Database
*/
public InvoicePK ejbCreate(InvoiceVO invoiceVO,int userID, String ds)
{
int invoiceID = 0;
this.dataSource = ds;
CVDal dl = new CVDal(ds);
try
{
ItemLines itemLines = invoiceVO.getItemLines();
itemLines.calculate();
dl.setSql("invoice.addinvoice");
dl.setInt(1,invoiceVO.getOrderId()); //orderID
dl.setInt(2,invoiceVO.getBillToId());//billaddress
dl.setInt(3,invoiceVO.getShipToId());//shipaddress
dl.setInt(4,invoiceVO.getStatusId()); // statusid
dl.setInt(5,invoiceVO.getTermId());// termid
dl.setInt(6,invoiceVO.getAccountManagerId()); //accmanager
dl.setInt(7,invoiceVO.getProjectId()); //project id
dl.setString(8,invoiceVO.getPo());// ponumber
dl.setInt(9,userID);
dl.setDate(10,invoiceVO.getInvoiceDate()); // invoiceDate DateObject
dl.setFloat(11,itemLines.getSubtotal()); // sub total
dl.setFloat(12,itemLines.getTax()); //tax
dl.setFloat(13,itemLines.getTotal()); // total
dl.setFloat(14,invoiceVO.getCustomerId()); // customer id
dl.setString(15,invoiceVO.getDescription()); // Notes
dl.setString(16,invoiceVO.getExternalId()); // externalID
dl.setInt(17,userID); // Owner
dl.executeUpdate();
invoiceID = dl.getAutoGeneratedKey();
this.invoiceVO =invoiceVO;
invoiceVO.setInvoiceId(invoiceID);
dl.clearParameters();
Set listkey = itemLines.keySet();
Iterator it = listkey.iterator();
while (it.hasNext())
{
Object str = ( Object )it.next();
ItemElement ele = ( ItemElement)itemLines.get( str );
this.addInvoiceItem(ele,invoiceID);
}// end of while
InitialContext ic = CVUtility.getInitialContext();
AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome)ic.lookup("local/Authorization");
AuthorizationLocal authorizationLocal = authorizationHome.create();
authorizationLocal.setDataSource(ds);
authorizationLocal.saveCurrentDefaultPermission("InvoiceHistory", invoiceID, userID);
}
catch(Exception e)
{
System.out.println("[Exception][InvoiceEJB.ejbCreate] Exception Thrown: "+e);
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
return new InvoicePK(invoiceID, ds);
}// end of ejbCreate
/*
* Add InvoiceItem record in Database
*/
private void addInvoiceItem(ItemElement ele ,int invoiceID)
{
CVDal dl = new CVDal(this.dataSource);
try
{
IntMember lineid = ( IntMember )ele.get("LineId");
IntMember itemid = ( IntMember )ele.get("ItemId");
StringMember sku = ( StringMember )ele.get("SKU");
IntMember qty = ( IntMember )ele.get("Quantity");
FloatMember priceEach = ( FloatMember )ele.get("Price");
StringMember desc = ( StringMember )ele.get("Description");
String status = ele.getLineStatus();
int quantity = ((Number) qty.getMemberValue()).intValue();
float price = ((Number) priceEach.getMemberValue()).floatValue();
int itemID = ((Number)itemid.getMemberValue()).intValue();
InitialContext ic = CVUtility.getInitialContext();
AccountHelperLocalHome home = (AccountHelperLocalHome)ic.lookup("local/AccountHelper");
AccountHelperLocal remote = home.create();
int taxClassID = remote.getTaxClassID(itemID);
Integer jurisdictionID = this.invoiceVO.getJurisdictionID();
int taxJurisdictionId = 0;
if(jurisdictionID != null){
taxJurisdictionId = jurisdictionID.intValue();
}
float taxRate = 0;
if (taxClassID != -1 && taxJurisdictionId !=0)
{
taxRate = remote.getTax(taxClassID, taxJurisdictionId);
}//if (taxJurisdictionId !=0)
float taxTotal = ((quantity * price) * (taxRate/100));
dl.setSql("invoice.addinvoiceitem");
dl.setInt(1,invoiceID);
dl.setInt(2,itemID );
dl.setInt(3,quantity);
dl.setFloat(4,((Float)priceEach.getMemberValue()).floatValue());
dl.setString(5,(String)sku.getMemberValue());
dl.setString(6,(String)desc.getMemberValue());
dl.setFloat(7,taxTotal);
dl.executeUpdate();
dl.clearParameters();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}// end of addInvoiceItem
/*
* Update InvoiceItem record in Database
*/
private void updateInvoiceItem(ItemElement ele ,int invoiceID)
{
CVDal dl = new CVDal(this.dataSource);
try
{
IntMember lineid = ( IntMember )ele.get("LineId");
IntMember itemid = ( IntMember )ele.get("ItemId");
StringMember sku = ( StringMember )ele.get("SKU");
IntMember qty = ( IntMember )ele.get("Quantity");
FloatMember priceEach = ( FloatMember )ele.get("Price");
StringMember desc = ( StringMember )ele.get("Description");
String status = ele.getLineStatus();
int quantity = ((Number) qty.getMemberValue()).intValue();
float price = ((Number) priceEach.getMemberValue()).floatValue();
int itemID = ((Number)itemid.getMemberValue()).intValue();
InitialContext ic = CVUtility.getInitialContext();
AccountHelperLocalHome home = (AccountHelperLocalHome)ic.lookup("local/AccountHelper");
AccountHelperLocal remote = home.create();
int taxClassID = remote.getTaxClassID(itemID);
int taxJurisdictionId = (this.invoiceVO.getJurisdictionID()).intValue();
float taxRate = 0;
if (taxClassID != -1 && taxJurisdictionId !=0)
{
taxRate = remote.getTax(taxClassID, taxJurisdictionId);
}//if (taxJurisdictionId !=0)
float taxTotal = ((quantity * price) * (taxRate/100));
dl.setSql("invoice.updateinvoiceitem");
dl.setInt(1, itemID);
dl.setInt(2,quantity);
dl.setFloat(3,price);
dl.setString(4,(String)sku.getMemberValue());
dl.setString(5,(String)desc.getMemberValue());
dl.setFloat(6,taxTotal);
dl.setInt(7,((Integer)lineid.getMemberValue()).intValue() );
dl.setInt(8,invoiceID);
dl.executeUpdate();
dl.clearParameters();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}// end of updateInvoiceItem
/*
* Update InvoiceItem record in Database
* Mark as delete
*/
private void markDeleatedInvoiceItem(ItemElement ele ,int invoiceID)
{
CVDal dl = new CVDal(this.dataSource);
try
{
IntMember lineid = ( IntMember )ele.get("LineId");
String status = ele.getLineStatus();
/* update invoiceitems set
status = ?
where invoicelineid = ? and invoiceid = ?
*/
dl.setSql("invoice.markdeletedinvoiceitem");
dl.setString(1,status);
dl.setInt(2,((Integer)lineid.getMemberValue()).intValue() );
dl.setInt(3,invoiceID);
dl.executeUpdate();
dl.clearParameters();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}// end of markDeleatedInvoiceItem
/**
* EJB Container callback method
*/
public void ejbPostCreate (InvoiceVO invoiceVO,int userID, String ds) throws CreateException
{
}
/**
* Finds if a given Invoice exits in the database
* @returns InvoicePK class (EJB clients get Remote)
* @param int InvoiceID
*/
public InvoicePK ejbFindByPrimaryKey(InvoicePK primaryKey) throws FinderException
{
HashMap hm = getBasic(primaryKey);
if (hm == null)
{
throw new FinderException("Could not find Invoice: " + primaryKey);
}
else
{
return primaryKey;
}
}// end of ejbFindByPrimaryKey
/*
* get Basic Invoice
*/
private HashMap getBasic(InvoicePK primaryKey)
{
CVDal dl = new CVDal(primaryKey.getDataSource());
dl.setSql("invoice.getinvoice");
dl.setInt(1,primaryKey.getId());
Collection col = dl.executeQuery();
dl.destroy();
dl = null;
Iterator it = col.iterator();
if (!it.hasNext())
return null;
else
return (HashMap)it.next();
}// end of getBasic
/*
* This method set the basicform for
*
*/
private void setBasicForm(HashMap hm)
{
this.invoiceVO = new InvoiceVO();
Long tmp;
tmp = (Long)(hm.get("invoiceid"));
if(tmp!=null)
this.invoiceVO.setInvoiceId(tmp.intValue());
tmp = (Long)(hm.get("order"));
if(tmp!=null)
this.invoiceVO.setOrderId(tmp.intValue());
tmp = (Long)(hm.get("customerid"));
if(tmp!=null)
this.invoiceVO.setCustomerId(tmp.intValue());
this.invoiceVO.setCustomerName((String)(hm.get("entityname")));
tmp = (Long)(hm.get("billaddress"));
if(tmp!=null)
this.invoiceVO.setBillToId(tmp.intValue());
this.invoiceVO.setBillToAddress((String)(hm.get("billaddressdesc")));
tmp = (Long)(hm.get("shipaddress"));
if(tmp!=null)
this.invoiceVO.setShipToId(tmp.intValue());
this.invoiceVO.setShipToAddress((String)(hm.get("shipaddressdesc")));
tmp = (Long)(hm.get("shipaddress"));
if(tmp!=null)
this.invoiceVO.setShipToId(tmp.intValue());
this.invoiceVO.setShipToAddress((String)(hm.get("shipaddressdesc")));
if( hm.get("jurisdictionID") != null){
int jurisdictionID = ((Number) hm.get("jurisdictionID")).intValue();
this.invoiceVO.setJurisdictionID(new Integer(jurisdictionID));
}
tmp = (Long)(hm.get("status"));
if(tmp!=null)
this.invoiceVO.setStatusId(tmp.intValue());
this.invoiceVO.setStatusName((String)(hm.get("statusdesc")));
this.invoiceVO.setInvoiceDate((java.sql.Date)(hm.get("invoicedate")));
this.invoiceVO.setPo((String)(hm.get("ponumber")));
tmp = (Long)(hm.get("terms"));
if(tmp!=null)
this.invoiceVO.setTermId(tmp.intValue());
this.invoiceVO.setTerm((String)(hm.get("termsdesc")));
tmp = (Long)(hm.get("accountmgr"));
if(tmp!=null)
this.invoiceVO.setAccountManagerId(tmp.intValue());
this.invoiceVO.setAccountManagerName((String)(hm.get("accountmgrdesc")));
this.invoiceVO.setDescription((String)(hm.get("description")));
tmp = (Long)(hm.get("project"));
if(tmp!=null)
this.invoiceVO.setProjectId(tmp.intValue());
tmp = (Long)(hm.get("orderid"));
if(tmp!=null)
this.invoiceVO.setOrderId(tmp.intValue());
this.invoiceVO.setProjectName((String)(hm.get("projecttitle")));
if(hm.get("externalid") != null)
this.invoiceVO.setExternalId((String)hm.get("externalid"));
if(hm.get("Created") != null)
this.invoiceVO.setCreatedOn((java.sql.Timestamp)hm.get("Created"));
if(hm.get("Modified") != null)
this.invoiceVO.setModifiedOn((java.sql.Timestamp)hm.get("Modified"));
}//end of setBasicForm
/*
* Set the InvoiceItem Data in InvoiceVO Object
*/
private void setInvoiceItemData()
{
CVDal dl = new CVDal(this.dataSource);
try
{
dl.setSqlQuery("select * from `invoiceitems` where status != 'Deleted' and InvoiceID = "+this.invoiceVO.getInvoiceId()+";");
Collection col = dl.executeQuery();
if (col != null)
{
ItemLines itemLines= new ItemLines();
Iterator it = col.iterator();
int count = 1;
while (it.hasNext())
{
HashMap hm =(HashMap)it.next();
int lineID = ((Number)hm.get("InvoiceLineID")).intValue();
int itemID = ((Number)hm.get("ItemID")).intValue();
int quantity = ((Number)hm.get("Quantity")).intValue();
float price = ((Number)hm.get("Price")).floatValue();
String sku = (String) hm.get("SKU");
String description = (String) hm.get("Description");
float taxTotal = ((Number)hm.get("taxAmount")).floatValue();
String status = (String) hm.get("status");
float priceExtended = quantity * price;
IntMember LineId = new IntMember("LineId",lineID,'D',"",'T',false,20);
IntMember ItemId = new IntMember("ItemId",itemID,'D',"",'T',false,20);
IntMember Quantity = new IntMember("Quantity",quantity,'D',"",'T',false,20);
FloatMember PriceEach = new FloatMember("Price",new Float(price),'D',"",'T',false,20);
StringMember SKU = new StringMember("SKU",sku,'D',"",'T',false);
StringMember Description = new StringMember("Description",description,'D',"",'T',false);
FloatMember PriceExtended = new FloatMember("PriceExtended",new Float(priceExtended),'D',"",'T',false,20);
FloatMember TaxAmount = new FloatMember("TaxAmount",new Float(taxTotal),'D',"",'T',false,20);
ItemElement ie = new ItemElement(11);
ie.put ("LineId",LineId);
ie.put ("ItemId",ItemId);
ie.put ("Quantity",Quantity);
ie.put ("Price",PriceEach);
ie.put ("SKU",SKU);
ie.put ("Description",Description);
ie.put ("PriceExtended",PriceExtended);
ie.put ("TaxAmount",TaxAmount);
ie.setLineStatus(status);
itemLines.put(""+count,ie);
count ++;
}
this.invoiceVO.setItemLines(itemLines);
}// end of if
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}// end of setOrderItemData
/**
* A container invokes this method before it ends the life of the entity object. This
* happens as a result of a client's invoking a remove operation, or when a container
* decides to terminate the entity object after a timeout. This method is called with
* no transaction context.
*/
public void ejbRemove ()
{
CVDal dl = new CVDal(this.dataSource);
try
{
dl.setSql("invoice.deleteinvoiceitem");
dl.setInt(1,this.invoiceVO.getInvoiceId());
//update invoiceitems set status = 'Deleted' where invoiceid = ?
dl.executeUpdate();
dl.clearParameters();
dl.setSql("invoice.deleteinvoice");
//update invoice set invoicestatus = 'Deleted' where invoiceid = ?
dl.setInt(1,this.invoiceVO.getInvoiceId());
dl.executeUpdate();
dl.clearParameters();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}
/**
* The activate method is called when the instance is activated from its 'passive' state.
* The instance should acquire any resource that it has released earlier in the ejbPassivate()
* method. This method is called with no transaction context.
*/
public void ejbActivate ()
{
}
/**
* The passivate method is called before the instance enters the 'passive' state. The
* instance should release any resources that it can re-acquire later in the ejbActivate()
* method. After the passivate method completes, the instance must be in a state that
* allows the container to use the Java Serialization protocol to externalize and store
* away the instance's state. This method is called with no transaction context.
*/
public void ejbPassivate ()
{
}
/*
* Set the associated entity context. The container calls this method after the instance
* creation. The enterprise Bean instance should store the reference to the context
* object in an instance variable. This method is called with no transaction context.
*/
public void setEntityContext(EntityContext ctx)
{
this.ctx = ctx;
}
public void unsetEntityContext()
{
this.ctx = null;
}
public void ejbLoad()
{
InvoicePK invoicePK = (InvoicePK)(ctx.getPrimaryKey());
this.setDataSource(invoicePK.getDataSource());
HashMap hm = getBasic(invoicePK);
if (hm == null)
return;
else
setBasicForm(hm);
}
public void ejbStore()
{
if (isDirty)
{
CVDal dl = new CVDal(this.dataSource);
try
{
ItemLines itemLines = invoiceVO.getItemLines();
itemLines.calculate();
dl.setSql("invoice.updateinvoice");
dl.setInt(1,this.invoiceVO.getBillToId());//bill address
dl.setInt(2,this.invoiceVO.getShipToId()); //ship address
dl.setInt(3,this.invoiceVO.getStatusId());// status
dl.setString(4,this.invoiceVO.getPo()); // ponumber
dl.setInt(5,this.invoiceVO.getTermId()); //terms
dl.setInt(6,this.invoiceVO.getAccountManagerId()); //accountmgr
dl.setInt(7,this.invoiceVO.getProjectId()); //projectid
dl.setFloat(8,itemLines.getSubtotal()); // sub total
dl.setFloat(9,itemLines.getTax()); //tax
dl.setFloat(10,itemLines.getTotal()); // total
dl.setString(11,this.invoiceVO.getDescription()); //notes
dl.setString(12,this.invoiceVO.getExternalId()); // externalId
dl.setInt(13,this.invoiceVO.getModifiedBy()); //modified By
dl.setInt(14,this.invoiceVO.getInvoiceId()); //Invoice id
dl.executeUpdate();
dl.clearParameters();
//Insert,Update Order Lines. as per status.
Set listkey = itemLines.keySet();
Iterator it = listkey.iterator();
while (it.hasNext())
{
Object str = ( Object)it.next();
ItemElement ele = ( ItemElement)itemLines.get( str );
String status = ele.getLineStatus();
if(status == null)
status = "";
status = status.trim();
if (status.equals("Active"))
{
updateInvoiceItem(ele,this.invoiceVO.getInvoiceId());
}
else if (status.equals("Deleted"))
{
markDeleatedInvoiceItem(ele,this.invoiceVO.getInvoiceId());
}
else if (status.equals("New") || status.equals(""))
{
addInvoiceItem(ele,this.invoiceVO.getInvoiceId());
}
}// end of while
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dl.destroy();
dl = null;
}
}// end of if
}// end of ejbStore
public InvoiceVO getInvoiceVO()
{
ejbLoad();
setInvoiceItemData();
return this.invoiceVO;
}// end of getInvoiceForm
/*
* set the Invoice Form
*/
public void setInvoiceVO(InvoiceVO invoiceVO,int userID)
{
// begin :: adding for fieldlevel rights...
InvoiceVO invDBVO = getInvoiceVO();
invoiceVO = (InvoiceVO)CVUtility.replaceVO(invDBVO, invoiceVO, "InvoiceHistory", userID, this.dataSource);
// end :: adding for fieldlevel rights...
this.invoiceVO = invoiceVO ;
this.isDirty = true;
}// end of setInvoiceForm
/**
* @author Kevin McAllister <kevin@centraview.com>
* This simply sets the target datasource to be used for DB interaction
* @param ds A string that contains the cannonical JNDI name of the datasource
*/
public void setDataSource(String ds) {
this.dataSource = ds;
}
}