BillBean.java 12.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/*
 * 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.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.EJBAccessException;
import javax.ejb.EJBException;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

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

import fi.codecrew.moya.beanutil.PdfPrinter;
import fi.codecrew.moya.bortal.views.BillSummary;
import fi.codecrew.moya.enums.apps.BillPermission;
import fi.codecrew.moya.enums.apps.ShopPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.exceptions.BillException;
import fi.codecrew.moya.exceptions.BillExceptionAlreadyPaid;
import fi.codecrew.moya.exceptions.BillExceptionNotEnoughtCredits;
import fi.codecrew.moya.facade.BillFacade;
import fi.codecrew.moya.facade.BillLineFacade;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.BillLine;
import fi.codecrew.moya.model.Discount;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.FoodWave;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag;

/**
 * Session Bean implementation class BillBean
 */
@Stateless
@LocalBean
@DeclareRoles({ BillPermission.S_CREATE_BILL, BillPermission.S_READ_ALL, BillPermission.S_VIEW_OWN, BillPermission.S_WRITE_ALL, SpecialPermission.S_USER, SpecialPermission.S_VERKKOMAKSU_CHECK, })
public class BillBean implements BillBeanLocal {

	private static final Logger logger = LoggerFactory.getLogger(BillBean.class);
	@EJB
	private BillFacade billFacade;

	@EJB
	private EventBeanLocal eventbean;
	@EJB
	private BillLineFacade billLineFacade;

	@EJB
	private PermissionBeanLocal permbean;
	@EJB
	private ProductBean productBean;

	@EJB
	private PlaceBean placebean;

	@EJB
	private UtilBean utilbean;

	@EJB
	private LoggingBeanLocal loggingBean;
	@EJB
	private EventUserFacade eventUserFacade;
	@EJB
	private ProductPBean productPBean;

	@EJB
	private DiscountBean discountBean;
	
	@EJB
	private LoggingBeanLocal logbean;

	/**
	 * Default constructor.
	 */
	public BillBean() {

	}

	@Override
	@RolesAllowed(BillPermission.S_VIEW_OWN)
	public Bill findById(int id) {
		if (id <= 0) {
			return null;
		}
		Bill bill = billFacade.find(id);
		EventUser currentuser = permbean.getCurrentUser();
		logger.debug("bill {} user {}", bill, currentuser);

		if (bill != null && !currentuser.equals(bill.getUser())
				&& !permbean.hasPermission(BillPermission.READ_ALL)) {
			bill = null;
		}
		return bill;

	}

	@Override
	public void getPdfBillStream(Bill bill, OutputStream ostream) {
		if (bill == null) {
			return;
		}
		if (bill.getBillNumber() == null || bill.getBillNumber() <= 0) {
			generateBillNumber(bill);
		}
		new PdfPrinter(bill).output(ostream);
	}

	private void generateBillNumber(Bill bill) {
		if (bill.getBillNumber() == null || bill.getBillNumber() == 0) {
			LanEvent currEvent = eventbean.getCurrentEvent();

			Integer billnr = billFacade.getBiggestBillNumber();

			if (billnr == null || billnr < currEvent.getNextBillNumber()) {
				billnr = currEvent.getNextBillNumber();
			} else {
				++billnr;
			}
			bill.setBillNumber(billnr);
			billFacade.merge(bill);
		}

	}

	// @Override
	// public Bill createEmptyBill(User shoppingUser) throws
	// PermissionDeniedException {
	// if (permbean.isCurrentUser(shoppingUser)) {
	// permbean.fatalPermission(BillPermission.CREATE_BILL,
	// "No permission to create empty bill for self");
	// } else {
	// permbean.fatalPermission(BillPermission.WRITE_ALL,
	// "Trying to create bill to someone else without sufficient permission");
	// }
	//
	// LanEvent event = eventbean.getCurrentEvent();
	// Bill ret = new Bill(event, shoppingUser);
	// billFacade.create(ret);
	// ret.setUser(shoppingUser);
	// em.flush();
	// logger.debug("Created bill with id {} and user {}", ret.getId(),
	// ret.getUser());
	// return ret;
	// }

	// @Override
	// @RolesAllowed("SHOP/EXECUTE")
	// public BillLine addProductToBill(Bill bill, Product product, BigDecimal
	// count) throws PermissionDeniedException {
	//
	// // If bill number > 0 bill has been sent and extra privileges are needed
	// // to modify.
	// boolean iscurrent = permissionbean.isCurrentUser(bill.getUser());
	// Integer billnr = bill.getBillNumber();
	// if (!iscurrent || billnr != null) {
	// permbean.fatalPermission(BillPermission.WRITE_ALL,
	// "User tried to modify bill ", bill, "without sufficient permissions");
	// }
	// BillLine line = new BillLine(bill, product.getName(),
	// product.getUnitName(), count, product.getPrice(), product.getVat());
	// line.setLineProduct(product);
	// billLineFacade.create(line);
	//
	// List<Discount> discounts = productBean.getActiveDiscounts(product,
	// count);
	//
	// for (Discount disc : discounts) {
	// BigDecimal unitPrice =
	// product.getPrice().subtract(product.getPrice().multiply(disc.getPercentage())).negate().setScale(2,
	// RoundingMode.HALF_UP);
	// BigDecimal vatPrice =
	// product.getVat().subtract(product.getVat().multiply(disc.getPercentage())).negate().setScale(2,
	// RoundingMode.HALF_UP);
	//
	// BillLine discountLine = new BillLine(bill, disc.getShortdesc(),
	// product.getUnitName(), count, unitPrice, vatPrice);
	// billLineFacade.create(discountLine);
	//
	// }
	//
	// em.flush();
	// return line;
	// }

	@Override
	@RolesAllowed(BillPermission.S_READ_ALL)
	public List<Bill> findAll() {

		return billFacade.findAll();
	}

	@Override
	@RolesAllowed(BillPermission.S_READ_ALL)
	public Collection<BillSummary> getBillLineSummary() {
		Collection<BillSummary> ret = billLineFacade.getLineSummary(eventbean
				.getCurrentEvent());

		return ret;
	}

	
	
	/**
	 * We will mark bill paid in different transaction. That's because we don't wont it to fail if something other fails.
	 * 
	 * @param bill
	 * @param when
	 * @param useCredits
	 * @return
	 * @throws BillException
	 */
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	private Bill markPaidSafeTransaction(Bill bill, Calendar when, boolean useCredits) throws BillException {
		bill = billFacade.reload(bill);
		
		if (bill.getAccountEvent() != null || bill.getPaidDate() != null) {
			logbean.logMessage(SecurityLogType.bill, permbean.getCurrentUser(), "Trying to doublemark bill paid", bill.getId());
			throw new BillExceptionAlreadyPaid("Trying to mark bill paid, already paid, BillID: "+bill.getId());
		}
		

		Product creditproduct = productBean.findCreditProduct();

		EventUser user = bill.getUser();
		
		
		if(useCredits) {
			
			// check if there is enought credits
			if(bill.getUser().getAccountBalance().compareTo(bill.getTotalPrice()) < 1) {
				logbean.logMessage(SecurityLogType.bill, permbean.getCurrentUser(), "Trying to pay bill with accountevents, and there is no saldo, billid: ", bill.getId());
				throw new BillExceptionNotEnoughtCredits("There is not enought credits to pay. , BillID: "+bill.getId());
			}
		} else {
		
			AccountEvent ac = productBean.createAccountEvent(creditproduct, bill.totalPrice(), user);
	
			logger.info("Created creditentry. {}, userproducts {}", ac, user.getAccountEvents().size());
			ac.setEventTime(when);
			ac.setBill(bill);
			ac.setSeller(permbean.getCurrentUser());
		
			bill.setAccountEvent(ac);
		}
		
		bill.setPaidDate(when.getTime());
		
		return bill;
	}
	
	
	@Override
	@RolesAllowed({ BillPermission.S_WRITE_ALL,
			SpecialPermission.S_VERKKOMAKSU_CHECK })
	public Bill markPaid(Bill bill, Calendar when, boolean useCredits)  throws BillException {

		
		bill = markPaidSafeTransaction(bill, when,useCredits);
		
		EventUser user = bill.getUser();
		
		
		
		if (bill.isFoowavePaymentOver() && !permbean.hasPermission(ShopPermission.MANAGE_FOODWAVES))
		{
			logbean.logMessage(SecurityLogType.bill, permbean.getCurrentUser(), "FoodwaveClosed and marking bill for it paid");
			throw new EJBException("Trying to mark paid a closed or left foodwave");
		}
		

		// bill = billFacade.merge(bill);

		for (BillLine bl : bill.getBillLines()) {

			Product prod = bl.getLineProduct();
			if (prod != null && !prod.getProductFlags().contains(ProductFlag.PREPAID_CREDIT)) {

				logger.debug("Creating Bill prepaidInstant product {}, {}", prod.getName(), bl.getQuantity());

				AccountEvent ac2 = productPBean.createAccountEvent(prod, bl.getQuantity(), user, bill.getSentDate(), bl.getFoodwave());
				logger.info("Created ac from product. {}, userproducts {}", ac2, user.getAccountEvents().size());

				ac2.setSeller(permbean.getCurrentUser());

			}
		}
		
		billFacade.flush();
		
		/*
		MailMessage msg = new MailMessage();

		String subject = MessageFormat.format(eventbean.getPropertyString(LanEventPropertyKey.BILL_PAID_MAIL_SUBJECT), user.getEvent().getName());
		String content = MessageFormat.format(eventbean.getPropertyString(LanEventPropertyKey.BILL_PAID_MAIL_CONTENT), (bill.getBillNumber() == null) ? "----" : bill.getBillNumber().toString());
		logger.info("Bill mail subject: {}, content {}", subject, content);
		msg.setSubject(subject);
		msg.setMessage(content);
		msg.setTo(bill.getUser().getUser());
		utilbean.sendMail(msg);
		*/
		
		eventUserFacade.flush();
		logbean.logMessage(SecurityLogType.bill, permbean.getCurrentUser(), "Marking bill paid, for user: ", bill.getUser().getId(),"BillId: ",bill.getId());
		eventUserFacade.evict(bill.getUser());
		
		return bill;
	}

	@Override
	@RolesAllowed({ BillPermission.S_CREATE_BILL, BillPermission.S_WRITE_ALL })
	public Bill createBill(Bill bill) {
		if (!permbean.isCurrentUser(bill.getUser()) && !permbean.hasPermission(BillPermission.WRITE_ALL)) {
			loggingBean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "Not enought rights to create bill for user ");
			throw new EJBAccessException("Could not create bill for another user");
		}
		billFacade.create(bill);
		generateBillNumber(bill);
		return bill;
	}

	@RolesAllowed({ BillPermission.S_WRITE_ALL })
	public Bill save(Bill bill) {
		return billFacade.merge(bill);
	}

	@Override
	@RolesAllowed({ BillPermission.S_VIEW_OWN, BillPermission.S_READ_ALL })
	public List<Bill> find(EventUser user) {
		if (!permbean.isCurrentUser(user) && !permbean.hasPermission(BillPermission.READ_ALL)) {
			loggingBean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "Not enought rights to get bill list for user ");
			throw new EJBAccessException("Could not list bills for another user");
		}
		return billFacade.find(user);
	}

	@Override
	@RolesAllowed({ BillPermission.S_VIEW_OWN, BillPermission.S_WRITE_ALL })
	public Bill expireBill(Bill bill) {
		if (!permbean.isCurrentUser(bill.getUser()) && !permbean.hasPermission(BillPermission.WRITE_ALL)) {
			loggingBean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "Not enought rights to expire a bill for user ");
			throw new EJBAccessException("Could not list bills for another user");
		}

		bill = billFacade.reload(bill);
		bill.markExpired();
		return bill;
	}

	@Override
	public Bill addProductToBill(Bill bill, Product product, BigDecimal count) {
		return this.addProductToBill(bill, product, count, null);
	}

	@Override
	public Bill addProductToBill(Bill bill, Product product, BigDecimal count, FoodWave foodwave) {

		// If bill number > 0 bill has been sent and extra privileges are needed
		// to modify.
		// if (!iscurrent || billnr != null) {
		// permbean.fatalPermission(BillPermission.WRITE_ALL,
		// "User tried to modify bill ", bill,
		// "without sufficient permissions");
		// }
		if (bill.getBillLines() == null) {
			bill.setBillLines(new ArrayList<BillLine>());
		}

		bill.getBillLines().add(new BillLine(bill, product, count, foodwave));

		for (Discount disc : discountBean.getActiveDiscountsByProduct(product, count, bill.getSentDate(), bill.getUser())) {
			bill.getBillLines().add(new BillLine(bill, product, disc, count));
		}

		return bill;
	}

}