DiscountBean.java 2.38 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.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import fi.codecrew.moya.facade.DiscountFacade;
import fi.codecrew.moya.model.Discount;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.Role;

/**
 * Session Bean implementation class DiscountBean
 */
@Stateless
@LocalBean
public class DiscountBean implements DiscountBeanLocal {

	@EJB
	private DiscountFacade discountfacade;

	@EJB
	private UserBean userBean;

	public DiscountBean() {
	}

	@Override
	public Discount save(Discount discount) {
		Discount ret = discountfacade.merge(discount);
		// productfacade.evictClass();
		// discountfacade.evictClass();
		return ret;
	}

	@Override
	public List<Discount> getActiveDiscountsByProduct(Product product, BigDecimal quantity, Date time, EventUser user) {

		ArrayList<Discount> ret = new ArrayList<Discount>();
		for (Discount d : product.getDiscounts()) {
			if (d.isActive() &&
					(d.getValidTo() == null || d.getValidTo().after(time)) &&
					(d.getValidFrom() == null || d.getValidFrom().before(time)) &&
					(d.getAmountMax().compareTo(BigDecimal.ZERO) == 0 || quantity.compareTo(d.getAmountMax()) <= 0) &&
					(d.getAmountMin().compareTo(BigDecimal.ZERO) == 0 || quantity.compareTo(d.getAmountMin()) >= 0)) {

				// plaah, there is role, must do stuff
				if (d.getRole() != null) {
					for (Role role : userBean.localFindUsersRoles(user)) {
						if (d.getRole().equals(role)) {
							ret.add(d);
						}
					}
				} else {
					ret.add(d);
				}
			}
		}
		ret.sort(Discount.SORT_COMPARATOR);
		return ret;

	}

}