/*
* $RCSfile: OrderEJB.java,v $ $Revision: 1.2 $ $Date: 2005/07/14 16:38:12 $ - $Author: mcallist $
*
* 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.order;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;
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 OrderEJB implements EntityBean {
private static Logger logger = Logger.getLogger(OrderEJB.class);
protected javax.ejb.EntityContext ctx;
protected Context environment;
private OrderForm orderForm;
private boolean isDirty = false; // update data if isDirty is true (ejbStore)
private String dataSource = "MySqlDS";
/*
* Create Order record in Database
*/
public OrderPK ejbCreate(OrderForm orderForm, int userID, String ds)
{
int orderID = 0;
this.dataSource = ds;
CVDal dl = new CVDal(ds);
try {
ItemLines itemLines = orderForm.getItemLines();
itemLines.calculate();
dl.setSql("order.addorder");
// insert into cvorder
// (entityid,billaddress,shipaddress,status,terms,accountmgr,project,ponumber,creator,orderdate,created,subtotal,tax,total,description,invoiceIsGenerated)
// values (?,?,?,?,?,?,?,?,?,?,concat(CURRENT_DATE,
// CURRENT_TIME),?,?,?,?,?)
dl.setInt(1, orderForm.getCustomerIdValue()); // entityid
dl.setInt(2, orderForm.getBillToAddIdValue());// billaddress
dl.setInt(3, orderForm.getShipToAddIdValue());// shipaddress
dl.setInt(4, orderForm.getStatusIdValue()); // statusid
dl.setInt(5, orderForm.getTermsIdValue());// termid
dl.setInt(6, orderForm.getAcctMgrIdValue()); // accmanager
dl.setInt(7, orderForm.getProjectIdValue()); // project id
dl.setString(8, orderForm.getPo());// ponumber
dl.setInt(9, userID);
dl.setRealDate(10, orderForm.getOrderDate()); // orderDate DateObject
dl.setFloat(11, itemLines.getSubtotal()); // sub total
dl.setFloat(12, itemLines.getTax()); // tax
dl.setFloat(13, itemLines.getTotal()); // total
dl.setString(14, orderForm.getNotes()); // notes
if (orderForm.getInvoiceIsGenerated())
dl.setString(15, "YES");
else
dl.setString(15, "NO");
dl.setInt(16, userID);
dl.executeUpdate();
orderID = dl.getAutoGeneratedKey();
dl.clearParameters();
this.orderForm = orderForm;
this.orderForm.setOrderIdValue(orderID);
Set listkey = itemLines.keySet();
Iterator it = listkey.iterator();
while (it.hasNext()) {
Object str = it.next();
ItemElement ele = (ItemElement) itemLines.get(str);
this.addOrderItem(ele, orderID);
}// end of while
InitialContext ic = CVUtility.getInitialContext();
AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome) ic.lookup("local/Authorization");
AuthorizationLocal authorizationLocal = authorizationHome.create();
authorizationLocal.setDataSource(ds);
authorizationLocal.saveCurrentDefaultPermission("OrderHistory", orderID, userID);
} catch (Exception e) {
logger.error("[ejbCreate]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
return new OrderPK(orderID, ds);
}// end of ejbCreate
/*
* Add OrderItem record in Database
*/
private void addOrderItem(ItemElement ele, int orderID)
{
CVDal dl = new CVDal(this.dataSource);
try {
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");
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();
remote.setDataSource(this.dataSource);
int taxClassID = remote.getTaxClassID(itemID);
Integer jurisdictionID = this.orderForm.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("order.addorderitem");
dl.setInt(1, orderID);
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) {
logger.error("[addOrderItem]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
}// end of addOrderItem
/*
* Update OrderItem record in Database
*/
private void updateOrderItem(ItemElement ele, int orderID)
{
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");
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();
remote.setDataSource(this.dataSource);
int taxClassID = remote.getTaxClassID(itemID);
int taxJurisdictionId = (this.orderForm.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("order.updateorderitem");
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, orderID);
dl.executeUpdate();
dl.clearParameters();
} catch (Exception e) {
logger.error("[updateOrderItem]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
}// end of updateOrderItem
/*
* Update OrderItem record in Database Mark as delete
*/
private void markDeleatedOrderItem(ItemElement ele, int orderID)
{
CVDal dl = new CVDal(this.dataSource);
try {
IntMember lineid = (IntMember) ele.get("LineId");
String status = ele.getLineStatus();
dl.setSql("order.markdeletedorderitem");
dl.setString(1, status);
dl.setInt(2, ((Integer) lineid.getMemberValue()).intValue());
dl.setInt(3, orderID);
dl.executeUpdate();
dl.clearParameters();
} catch (Exception e) {
logger.error("[markDeleatedOrderItem]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
}// end of markDeleatedOrderItem
/**
* EJB Container callback method
*/
public void ejbPostCreate(OrderForm orderForm, int userID, String ds)
{}
/**
* Finds if a given Order exits in the database
* @returns OrderPK class (EJB clients get Remote)
* @param int OrderID
*/
public OrderPK ejbFindByPrimaryKey(OrderPK primaryKey) throws FinderException
{
HashMap hm = getBasic(primaryKey);
if (hm == null) {
throw new FinderException("Could not find Order: " + primaryKey);
}
return primaryKey;
}// end of ejbFindByPrimaryKey
/*
* get Basic Order
*/
private HashMap getBasic(OrderPK primaryKey)
{
CVDal dl = new CVDal(primaryKey.getDataSource());
dl.setSql("order.getorder");
// SELECT cvorder.orderid,cvorder.entityid,entity.name as
// entityname,cvorder.billaddress ,concat(add1.street1,' ',add1.street2) as
// billaddressdesc ,cvorder.shipaddress,concat(add2.street1,'
// ',add2.street2) as shipaddressdesc ,cvorder.status
// ,accountingstatus.title as
// statusdesc,cvorder.orderdate,cvorder.ponumber,cvorder.terms,accountingterms.title
// as termsdesc ,cvorder.accountmgr,concat(individual.firstname,'
// ',individual.lastname) as accountmgrdesc FROM cvorder left outer join
// entity on cvorder.entityid = entity.entityid left outer join address add1
// on cvorder.billaddress = add1.addressid left outer join address add2 on
// cvorder.shipaddress = add2.addressid left outer join accountingstatus on
// cvorder.status = accountingstatus.statusid left outer join
// accountingterms on cvorder.terms = accountingterms.termsid left outer
// join individual on cvorder.accountmgr= individual.individualid where
// cvorder.orderid = 1
dl.setInt(1, primaryKey.getId());
Collection col = dl.executeQuery();
dl.destroy();
dl = null;
Iterator it = col.iterator();
if (!it.hasNext()) {
return null;
}
return (HashMap) it.next();
}// end of getBasic
/*
* This method set the basicform for
*/
private void setBasicForm(HashMap hm)
{
this.orderForm = new OrderForm();
Long tmp;
tmp = (Long) (hm.get("orderid"));
if (tmp != null)
this.orderForm.setOrderIdValue(tmp.intValue());
tmp = (Long) (hm.get("entityid"));
if (tmp != null)
this.orderForm.setCustomerIdValue(tmp.intValue());
this.orderForm.setCustomerName((String) (hm.get("entityname")));
tmp = (Long) (hm.get("billaddress"));
if (tmp != null)
this.orderForm.setBillToAddIdValue(tmp.intValue());
this.orderForm.setBillToAdd((String) (hm.get("billaddressdesc")));
tmp = (Long) (hm.get("shipaddress"));
if (tmp != null)
this.orderForm.setShipToAddIdValue(tmp.intValue());
this.orderForm.setShipToAdd((String) (hm.get("shipaddressdesc")));
tmp = (Long) (hm.get("status"));
if (tmp != null)
this.orderForm.setStatusIdValue(tmp.intValue());
this.orderForm.setStatus((String) (hm.get("statusdesc")));
this.orderForm.setOrderDate((java.sql.Date) (hm.get("orderdate")));
this.orderForm.setPo((String) (hm.get("ponumber")));
tmp = (Long) (hm.get("terms"));
if (tmp != null)
this.orderForm.setTermsIdValue(tmp.intValue());
this.orderForm.setTerms((String) (hm.get("termsdesc")));
if (hm.get("jurisdictionID") != null) {
int jurisdictionID = ((Number) hm.get("jurisdictionID")).intValue();
this.orderForm.setJurisdictionID(new Integer(jurisdictionID));
}
tmp = (Long) (hm.get("accountmgr"));
if (tmp != null)
this.orderForm.setAcctMgrIdValue(tmp.intValue());
this.orderForm.setAcctMgr((String) (hm.get("accountmgrdesc")));
this.orderForm.setProject((String) (hm.get("ProjectTitle")));
tmp = (Long) (hm.get("project"));
if (tmp != null)
this.orderForm.setProjectIdValue(tmp.intValue());
this.orderForm.setProjectId(tmp + "");
this.orderForm.setNotes((String) (hm.get("description")));
if (((String) hm.get("invoiceisgenerated")).equals("NO") || hm.get("invoiceisgenerated") == null)
this.orderForm.setInvoiceIsGenerated(false);
else
this.orderForm.setInvoiceIsGenerated(true);
}// end of setBasicForm
/*
* Set the OrderItem Data in OrderForm Object
*/
private void setOrderItemData()
{
CVDal dl = new CVDal(this.dataSource);
try {
dl.setSqlQuery("select * from `orderitem` where status != 'Deleted' and orderid = "
+ this.orderForm.getOrderIdValue() + ";");
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("lineid")).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.orderForm.setItemLines(itemLines);
}// end of if
} catch (Exception e) {
logger.error("[setOrderItemData]: Exception", e);
} 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("order.deleteorderitem");
dl.setInt(1, this.orderForm.getOrderIdValue());
// update orderitem set status = 'Deleted' where orderid = ?
dl.executeUpdate();
dl.clearParameters();
dl.setSql("order.deleteorder");
// update cvorder set orderstatus = 'Deleted' where orderid = 34
dl.setInt(1, this.orderForm.getOrderIdValue());
dl.executeUpdate();
dl.clearParameters();
} catch (Exception e) {
logger.error("[ejbRemove]: Exception", e);
} 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()
{
OrderPK orderPK = (OrderPK) (ctx.getPrimaryKey());
this.setDataSource(orderPK.getDataSource());
HashMap hm = getBasic(orderPK);
if (hm != null) {
setBasicForm(hm);
}
}
public void ejbStore()
{
if (isDirty) {
CVDal dl = new CVDal(this.dataSource);
try {
ItemLines itemLines = orderForm.getItemLines();
itemLines.calculate();
dl.setSql("order.updateorder");
dl.setInt(1, this.orderForm.getCustomerIdValue()); // entityid
dl.setInt(2, this.orderForm.getBillToAddIdValue());// bill address
dl.setInt(3, this.orderForm.getShipToAddIdValue()); // ship address
dl.setInt(4, this.orderForm.getStatusIdValue());// status
dl.setString(5, this.orderForm.getPo()); // ponumber
dl.setInt(6, this.orderForm.getTermsIdValue()); // terms
dl.setInt(7, this.orderForm.getAcctMgrIdValue()); // accountmgr
dl.setInt(8, this.orderForm.getProjectIdValue()); // projectid
dl.setFloat(9, itemLines.getSubtotal()); // sub total
dl.setFloat(10, itemLines.getTax()); // tax
dl.setFloat(11, itemLines.getTotal()); // total
dl.setString(12, this.orderForm.getNotes());
if (orderForm.getInvoiceIsGenerated())
dl.setString(13, "YES");
else
dl.setString(13, "NO");
dl.setInt(14, this.orderForm.getModifiedBy()); // modified By
dl.setInt(15, this.orderForm.getOrderIdValue()); // order 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 = it.next();
ItemElement ele = (ItemElement) itemLines.get(str);
String status = ele.getLineStatus();
if (status == null)
status = "";
status = status.trim();
if (status.equals("Active")) {
updateOrderItem(ele, this.orderForm.getOrderIdValue());
} else if (status.equals("Deleted")) {
markDeleatedOrderItem(ele, this.orderForm.getOrderIdValue());
} else if (status.equals("New") || status.equals("")) {
addOrderItem(ele, this.orderForm.getOrderIdValue());
}
}// end of while
} catch (Exception e) {
logger.error("[ejbStore]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
}// end of if
}// end of ejbStore
public OrderForm getOrderForm()
{
setOrderItemData();
return this.orderForm;
}// end of getOrderForm
/*
* set the Order Form
*/
public void setOrderForm(OrderForm orderForm, int userID)
{
OrderForm orderDBVO = getOrderForm();
orderForm = (OrderForm) CVUtility.replaceVO(orderDBVO, orderForm, "OrderHistory", userID, this.dataSource);
this.orderForm = orderForm;
this.isDirty = true;
}// end of setOrderForm
public void setInvoiceIsGenerated(boolean flag, int orderId)
{
CVDal dl = new CVDal(this.dataSource);
String value = null;
try {
if (flag)
value = "YES";
else
value = "NO";
dl.setSqlQuery("update cvorder set invoiceIsGenerated = '" + value + "' where orderid = " + orderId);
dl.executeUpdate();
HashMap hm = getBasic((OrderPK) (ctx.getPrimaryKey()));
// calling EXPLICITLY because data needs to be set in this.orderForm
// and ejbLoad doesnot get called for next requests as data is set once
// already.
// This happens because we are calling this method which changes DB
// EXPLICITLY
// If we would have done this setting of 'YES'/'NO' through updateOrder
// then ejbLoad would have got called by server to refresh the data
// NOTE: This method uses CVDal to access DB directly because using Whole
// OrderForm
// and using update method is Lot cumbersome for just ONE field.
if (hm != null) {
setBasicForm(hm);
}
} catch (Exception e) {
logger.error("[setInvoiceIsGenerated]: Exception", e);
} finally {
dl.destroy();
dl = null;
}
}
/**
* @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;
}
}