ProductPBean.java 5.7 KB
/*
 * Copyright Codecrew Ry
 * 
 * All rights reserved.
 * 
 * This license applies to any software containing a notice placed by the 
 * copyright holder. Such software is herein referred to as the Software. 
 * This license covers modification, distribution and use of the Software. 
 * 
 * Any distribution and use in source and binary forms, with or without 
 * modification is not permitted without explicit written permission from the 
 * copyright owner. 
 * 
 * A non-exclusive royalty-free right is granted to the copyright owner of the 
 * Software to use, modify and distribute all modifications to the Software in 
 * future versions of the Software. 
 * 
 */
package fi.codecrew.moya.beans;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.facade.AccountEventFacade;
import fi.codecrew.moya.facade.ProductFacade;
import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.Discount;
import fi.codecrew.moya.model.DiscountInstance;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.FoodWave;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;

/**
 * Session Bean implementation class ProductPBean
 */
@Stateless
@LocalBean
public class ProductPBean {

	@EJB
	private PermissionBean permbean;

	@EJB
	private DiscountBean discountBean;
	@EJB
	private AccountEventFacade accounteventfacade;

	@EJB
	private PlaceBean placebean;

	@EJB
	private ProductFacade productFacade;

	@EJB
	private LoggingBeanLocal lbean;

	private static final Logger logger = LoggerFactory
			.getLogger(ProductPBean.class);

	/**
	 * Default constructor.
	 */
	public ProductPBean() {
		// TODO Auto-generated constructor stub
	}

	public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user, Date date) {
		return this.createAccountEvent(product, null, quantity, user, date, null, null);
	}

	public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user, Date date, String description) {
		return this.createAccountEvent(product, null, quantity, user, date, description, null);
	}

	/**
	 * Creates new AccountEvent from provided product to provided user <br>
	 * <strong>Notice</strong>, that this function expects the user parameter to
	 * be attached entity!
	 * 
	 * @param product
	 *            Product to create the account event from
	 * @param quantity
	 *            How many products have been bought
	 * @param user
	 *            user to whom the product should be created. MUST BE ATTACHED
	 *            ENTITY!
	 * @param date
	 *            AccountEvent creation time
	 * @return The created AccountEvent entity
	 */
	public AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user, Date date, String description, FoodWave foodwave) {

		if (!accounteventfacade.isAttached(product)) {
			product = productFacade.reload(product);
		}

		if (!product.getEvent().equals(user.getEvent())) {
			throw new EJBException("Trying to create accountevent for different event in user and product");
		}

		BigDecimal unitPrice = product.getPrice().negate();

		List<Discount> discounts = new ArrayList<>();

		if (overriddenUnitPrice != null && BigDecimal.ZERO.compareTo(overriddenUnitPrice) <= 0) {

			unitPrice = overriddenUnitPrice.negate();
			lbean.sendMessage(MoyaEventType.ACCOUNTEVENT_INFO, permbean.getCurrentUser(), "User creating accountevent with discount");
			// lbean.logMessage(SecurityLogType.accountEvent, permbean.getCurrentUser(), "User creating accountevent with discount");
		} else {

			// no discounts if custom price
			discounts = discountBean.getActiveDiscountsByProduct(product, quantity, date, user);
			for (Discount d : discounts) {
				unitPrice = unitPrice.multiply(d.getPercentage());
			}
		}

		AccountEvent ret = new AccountEvent(user, product, unitPrice, quantity, Calendar.getInstance());


		// If product name is edited, move it into the description
		if(description != null && !description.isEmpty() && !product.getName().equals(description)) {
			String aeDescription = description;

			// Remove product name from option descriptions
			aeDescription = aeDescription.replaceFirst("^" + product.getName() + ",?", "").trim();

			ret.setDescription(aeDescription);
		}


		// ret.setDelivered(Calendar.getInstance());
		ret.setSeller(permbean.getCurrentUser());

		if (foodwave != null) {
			ret.setFoodWave(foodwave);
			if (foodwave.getAccountEvents() == null) {
				foodwave.setAccountEvents(new ArrayList<AccountEvent>());
			}
			foodwave.getAccountEvents().add(ret);
		}

		if (product.getProductFlags().contains(ProductFlag.RESERVE_PLACE_WHEN_BOUGHT) || product.getProductFlags().contains(ProductFlag.CREATE_NEW_PLACE_WHEN_BOUGHT)) {
			placebean.lockPlaceProduct(user, product, quantity);
		}

		List<DiscountInstance> accEventdiscounts = ret.getDiscountInstances();

		for (Discount d : discounts) {
			// discountsArray.add(discInst);
			// discountinstancefacade.create(discInst);
			accEventdiscounts.add(new DiscountInstance(ret, d));
		}

		if (product.getAccountEvents() == null) {
			product.setAccountEvents(new ArrayList<AccountEvent>());
		}
		product.getAccountEvents().add(ret);

		user.addAccountevent(ret);
		accounteventfacade.create(ret);
		logger.debug("create ac {} for user {}", ret, user.getUser());
		// flush changes to db.
		// userFacade.flush();

		lbean.sendMessage(MoyaEventType.ACCOUNTEVENT_INFO, user, "User created accountevent: for product ", ret.getProduct().getName(), " count: ", ret.getQuantity());
		return ret;
	}
}