Commit a63d4213 by Tuukka Kivilahti

Merge branch 'master' of codecrew.fi:codecrew/moya

2 parents d397569f dffe4d34
Showing with 1468 additions and 672 deletions
...@@ -15,3 +15,4 @@ ...@@ -15,3 +15,4 @@
moya-git.properties moya-git.properties
*/*/bin */*/bin
pom.xml.versionsBackup pom.xml.versionsBackup
.idea/
\ No newline at end of file
...@@ -27,11 +27,13 @@ import java.util.List; ...@@ -27,11 +27,13 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import fi.codecrew.moya.bortal.views.BillSummary; import fi.codecrew.moya.bortal.views.BillSummary;
import fi.codecrew.moya.entitysearch.BillSearchQuery;
import fi.codecrew.moya.exceptions.BillException; import fi.codecrew.moya.exceptions.BillException;
import fi.codecrew.moya.model.Bill; import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.FoodWave; import fi.codecrew.moya.model.FoodWave;
import fi.codecrew.moya.model.Product; import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.utilities.SearchResult;
@Local @Local
public interface BillBeanLocal { public interface BillBeanLocal {
...@@ -59,9 +61,13 @@ public interface BillBeanLocal { ...@@ -59,9 +61,13 @@ public interface BillBeanLocal {
List<Bill> find(EventUser user); List<Bill> find(EventUser user);
Bill expireBill(Bill bill); Bill expireBill(Bill bill);
Bill addProductToBill(Bill bill, Product product, BigDecimal count, FoodWave foodwave); Bill addProductToBill(Bill bill, Product product, BigDecimal count, FoodWave foodwave);
Bill addProductToBill(Bill bill, Product product, BigDecimal count); Bill addProductToBill(Bill bill, Product product, BigDecimal count);
SearchResult<Bill> findAll(BillSearchQuery q);
SearchResult<Bill> findUsers(BillSearchQuery q);
} }
...@@ -20,6 +20,7 @@ package fi.codecrew.moya.beans; ...@@ -20,6 +20,7 @@ package fi.codecrew.moya.beans;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
...@@ -33,6 +34,6 @@ public interface DiscountBeanLocal { ...@@ -33,6 +34,6 @@ public interface DiscountBeanLocal {
Discount save(Discount discount); Discount save(Discount discount);
public List<Discount> getActiveDiscountsByProduct(Product product, BigDecimal quantity, Calendar time, EventUser user); public List<Discount> getActiveDiscountsByProduct(Product product, BigDecimal quantity, Date time, EventUser user);
} }
...@@ -20,6 +20,7 @@ package fi.codecrew.moya.beans; ...@@ -20,6 +20,7 @@ package fi.codecrew.moya.beans;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -53,7 +54,7 @@ public interface ProductBeanLocal { ...@@ -53,7 +54,7 @@ public interface ProductBeanLocal {
AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user); AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user);
AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user); AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user);
// List<Discount> getActiveDiscounts(Product product, BigDecimal quantity); // List<Discount> getActiveDiscounts(Product product, BigDecimal quantity);
...@@ -67,7 +68,7 @@ public interface ProductBeanLocal { ...@@ -67,7 +68,7 @@ public interface ProductBeanLocal {
Discount save(Discount discount); Discount save(Discount discount);
BigDecimal calculateTotal(Product product, BigDecimal quantity, Calendar date, EventUser user); BigDecimal calculateTotal(Product product, BigDecimal quantity, Date date, EventUser user);
HashMap<Integer, BigDecimal> getProductLimit(Map<Integer, BigDecimal> prodCounts, EventUser user); HashMap<Integer, BigDecimal> getProductLimit(Map<Integer, BigDecimal> prodCounts, EventUser user);
......
...@@ -25,6 +25,7 @@ import java.util.List; ...@@ -25,6 +25,7 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Feedback; import fi.codecrew.moya.model.Feedback;
import fi.codecrew.moya.model.GameID; import fi.codecrew.moya.model.GameID;
...@@ -37,7 +38,6 @@ import fi.codecrew.moya.model.User; ...@@ -37,7 +38,6 @@ import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserApproval; import fi.codecrew.moya.model.UserApproval;
import fi.codecrew.moya.model.UserImage; import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.util.MailMessage; import fi.codecrew.moya.util.MailMessage;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery; import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
......
...@@ -41,4 +41,6 @@ public interface VerkkomaksutFiBeanLocal { ...@@ -41,4 +41,6 @@ public interface VerkkomaksutFiBeanLocal {
Map<Integer, String> getAuthcodeForBills(List<Bill> bills); Map<Integer, String> getAuthcodeForBills(List<Bill> bills);
String getAuthcodeForBill(Bill selectedBill);
} }
...@@ -20,6 +20,8 @@ public interface VipBeanLocal { ...@@ -20,6 +20,8 @@ public interface VipBeanLocal {
void create(Vip vip); void create(Vip vip);
void delete(Vip vip);
Vip find(Integer id); Vip find(Integer id);
Vip createProduct(VipProduct l); Vip createProduct(VipProduct l);
......
/*
* 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.entitysearch;
import java.util.Map;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.SearchQuery;
public class BillSearchQuery extends SearchQuery {
private static final long serialVersionUID = -522847840222858146L;
private final Map<String, Object> filters;
private EventUser user;
public BillSearchQuery(int first, int pageSize, String sortField, QuerySortOrder sort, Map<String, Object> filters) {
super((int) first / pageSize, pageSize, sortField, null, sort);
this.filters = filters;
}
public Map<String, Object> getFilters() {
return filters;
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser user) {
this.user = user;
}
}
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.util; package fi.codecrew.moya.entitysearch;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
......
...@@ -30,39 +30,31 @@ import javax.annotation.security.DeclareRoles; ...@@ -30,39 +30,31 @@ import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed; import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.EJBAccessException; import javax.ejb.EJBAccessException;
import javax.ejb.EJBException;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beanutil.PdfPrinter; import fi.codecrew.moya.beanutil.PdfPrinter;
import fi.codecrew.moya.bortal.views.BillSummary; import fi.codecrew.moya.bortal.views.BillSummary;
import fi.codecrew.moya.entitysearch.BillSearchQuery;
import fi.codecrew.moya.enums.apps.BillPermission; 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.enums.apps.SpecialPermission;
import fi.codecrew.moya.exceptions.BillException; 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.BillFacade;
import fi.codecrew.moya.facade.BillLineFacade; import fi.codecrew.moya.facade.BillLineFacade;
import fi.codecrew.moya.facade.EventUserFacade; import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.PlaceSlotFacade; import fi.codecrew.moya.facade.PlaceSlotFacade;
import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.Bill; import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.BillLine; import fi.codecrew.moya.model.BillLine;
import fi.codecrew.moya.model.Discount; import fi.codecrew.moya.model.Discount;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.FoodWave; import fi.codecrew.moya.model.FoodWave;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.PlaceSlot; import fi.codecrew.moya.model.PlaceSlot;
import fi.codecrew.moya.model.Product; import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.GenericFacade;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType; import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
/** /**
...@@ -385,4 +377,21 @@ public class BillBean implements BillBeanLocal { ...@@ -385,4 +377,21 @@ public class BillBean implements BillBeanLocal {
return bill; return bill;
} }
@Override
@RolesAllowed(BillPermission.S_READ_ALL)
public SearchResult<Bill> findAll(BillSearchQuery q) {
return billFacade.find(q);
}
@RolesAllowed(BillPermission.S_VIEW_OWN)
public SearchResult<Bill> findUsers(BillSearchQuery q) {
if (q.getUser() == null) {
q.setUser(permbean.getCurrentUser());
} else if (!permbean.hasPermission(BillPermission.VIEW_OWN) && !permbean.isCurrentUser(q.getUser())) {
throw new EJBAccessException("Tried to fetch bills for wrong user");
}
return billFacade.find(q);
}
} }
...@@ -264,7 +264,7 @@ public class CheckoutFiBean implements CheckoutFiBeanLocal { ...@@ -264,7 +264,7 @@ public class CheckoutFiBean implements CheckoutFiBeanLocal {
final StringBuilder stamp = new StringBuilder(); final StringBuilder stamp = new StringBuilder();
stamp.append(bill.getId()); stamp.append(bill.getId());
stamp.append(STAMP_SPLITCHAR); stamp.append(STAMP_SPLITCHAR);
stamp.append(bill.getSentDate().getTimeInMillis() / 1000); stamp.append(bill.getSentDate().getTime() / 1000);
return stamp.toString(); return stamp.toString();
} }
......
...@@ -21,6 +21,7 @@ package fi.codecrew.moya.beans; ...@@ -21,6 +21,7 @@ package fi.codecrew.moya.beans;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -42,7 +43,7 @@ public class DiscountBean implements DiscountBeanLocal { ...@@ -42,7 +43,7 @@ public class DiscountBean implements DiscountBeanLocal {
@EJB @EJB
private DiscountFacade discountfacade; private DiscountFacade discountfacade;
@EJB @EJB
private UserBean userBean; private UserBean userBean;
...@@ -58,47 +59,30 @@ public class DiscountBean implements DiscountBeanLocal { ...@@ -58,47 +59,30 @@ public class DiscountBean implements DiscountBeanLocal {
} }
@Override @Override
public List<Discount> getActiveDiscountsByProduct(Product product, BigDecimal quantity, Calendar time, EventUser user) { 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 ArrayList<Discount> ret = new ArrayList<Discount>();
if (d.getRole() != null) { for (Discount d : product.getDiscounts()) {
for (Role role : userBean.localFindUsersRoles(user)) { if (d.isActive() &&
if (d.getRole().equals(role)) { (d.getValidTo() == null || d.getValidTo().after(time)) &&
ret.add(d); (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)) {
} else {
ret.add(d);
}
}
}
return ret;
}
// @Override // plaah, there is role, must do stuff
// public Discount create(String discountdesc) { if (d.getRole() != null) {
// LanEvent ev = eventbean.getCurrentEvent(); for (Role role : userBean.localFindUsersRoles(user)) {
// Discount ret = new Discount(ev); if (d.getRole().equals(role)) {
// ret.setShortdesc(discountdesc); ret.add(d);
// ev.getDiscounts().add(ret); }
// discountfacade.flush(); }
// } else {
// // discountfacade.create(ret); ret.add(d);
// // eventfacade.evict(eventbean.getCurrentEvent()); }
// }
// return ret; }
// return ret;
// }
}
} }
...@@ -176,7 +176,7 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -176,7 +176,7 @@ public class PlaceBean implements PlaceBeanLocal {
BigDecimal total = Bill.BILL_SCALED_ZERO_PRICE; BigDecimal total = Bill.BILL_SCALED_ZERO_PRICE;
Calendar now = Calendar.getInstance(); Date now = new Date();
for (Entry<Product, Integer> entry : mockmap.entrySet()) { for (Entry<Product, Integer> entry : mockmap.entrySet()) {
logger.debug("Adding to price {} of {}", entry.getValue(), entry.getKey().getName()); logger.debug("Adding to price {} of {}", entry.getValue(), entry.getKey().getName());
if (entry.getKey() != null) { if (entry.getKey() != null) {
...@@ -350,7 +350,7 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -350,7 +350,7 @@ public class PlaceBean implements PlaceBeanLocal {
} }
for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) { for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) {
productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, Calendar.getInstance()); productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, new Date());
} }
} }
PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true); PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true);
......
...@@ -22,6 +22,7 @@ import java.math.BigDecimal; ...@@ -22,6 +22,7 @@ import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
...@@ -417,7 +418,7 @@ public class ProductBean implements ProductBeanLocal { ...@@ -417,7 +418,7 @@ public class ProductBean implements ProductBeanLocal {
} }
@Override @Override
public BigDecimal calculateTotal(Product product, BigDecimal quantity, Calendar date, EventUser user) { public BigDecimal calculateTotal(Product product, BigDecimal quantity, Date date, EventUser user) {
if (product == null || quantity == null) { if (product == null || quantity == null) {
throw new RuntimeException("Some parameter is null!"); throw new RuntimeException("Some parameter is null!");
} }
...@@ -478,7 +479,7 @@ public class ProductBean implements ProductBeanLocal { ...@@ -478,7 +479,7 @@ public class ProductBean implements ProductBeanLocal {
@Override @Override
public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) { public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) {
user = eventUserFacade.reload(user); user = eventUserFacade.reload(user);
AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, Calendar.getInstance()); AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, new Date());
cardTemplateBean.checkPrintedCard(user); cardTemplateBean.checkPrintedCard(user);
return ret; return ret;
} }
...@@ -487,7 +488,7 @@ public class ProductBean implements ProductBeanLocal { ...@@ -487,7 +488,7 @@ public class ProductBean implements ProductBeanLocal {
public AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user) { public AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user) {
user = eventUserFacade.reload(user); user = eventUserFacade.reload(user);
AccountEvent ret = productPBean.createAccountEvent(product, overriddenUnitPrice, quantity, user, Calendar.getInstance(), null); AccountEvent ret = productPBean.createAccountEvent(product, overriddenUnitPrice, quantity, user, new Date(), null);
cardTemplateBean.checkPrintedCard(user); cardTemplateBean.checkPrintedCard(user);
return ret; return ret;
} }
......
...@@ -21,6 +21,7 @@ package fi.codecrew.moya.beans; ...@@ -21,6 +21,7 @@ package fi.codecrew.moya.beans;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.ejb.*; import javax.ejb.*;
...@@ -73,7 +74,7 @@ public class ProductPBean { ...@@ -73,7 +74,7 @@ public class ProductPBean {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user, Calendar date) { public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user, Date date) {
return this.createAccountEvent(product, null, quantity, user, date, null); return this.createAccountEvent(product, null, quantity, user, date, null);
} }
...@@ -94,7 +95,7 @@ public class ProductPBean { ...@@ -94,7 +95,7 @@ public class ProductPBean {
* AccountEvent creation time * AccountEvent creation time
* @return The created AccountEvent entity * @return The created AccountEvent entity
*/ */
public AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user, Calendar date, FoodWave foodwave) { public AccountEvent createAccountEvent(Product product, BigDecimal overriddenUnitPrice, BigDecimal quantity, EventUser user, Date date, FoodWave foodwave) {
if (!accounteventfacade.isAttached(product)) { if (!accounteventfacade.isAttached(product)) {
product = productFacade.reload(product); product = productFacade.reload(product);
......
...@@ -80,10 +80,9 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -80,10 +80,9 @@ public class ReaderBean implements ReaderBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(ReaderBean.class); private static final Logger logger = LoggerFactory.getLogger(ReaderBean.class);
@Override @Override
public ReaderEvent checkCode(String code) { public ReaderEvent checkCode(String code) {
return checkCode(ReaderType.BARCODE.toString()+":handheld_reader_via_browser", code); return checkCode(ReaderType.BARCODE.toString() + ":handheld_reader_via_browser", code);
} }
@Override @Override
...@@ -101,7 +100,7 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -101,7 +100,7 @@ public class ReaderBean implements ReaderBeanLocal {
if (reader == null || code == null || code.isEmpty()) { if (reader == null || code == null || code.isEmpty()) {
return null; return null;
} }
logger.info("got code from reader {}", code); logger.info("got code from reader {}", code);
code = code.replace("\"\b", ""); code = code.replace("\"\b", "");
...@@ -109,8 +108,8 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -109,8 +108,8 @@ public class ReaderBean implements ReaderBeanLocal {
/** /**
* Some of rfid-readers adds zeros to start, some to end * Some of rfid-readers adds zeros to start, some to end
* *
* Also, under 16 char -rdid (the smaller one) should be 16 character long, * Also, under 16 char -rdid (the smaller one) should be 16 character
* with zeros on beginning. * long, with zeros on beginning.
*/ */
if (ReaderType.RFID.equals(reader.getType())) { if (ReaderType.RFID.equals(reader.getType())) {
...@@ -126,7 +125,6 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -126,7 +125,6 @@ public class ReaderBean implements ReaderBeanLocal {
code = sb.toString(); code = sb.toString();
} }
ReaderEvent event = new ReaderEvent(new Date(), reader, code); ReaderEvent event = new ReaderEvent(new Date(), reader, code);
// first, check if dublicate, there is 30s timeout for dublicates, // first, check if dublicate, there is 30s timeout for dublicates,
...@@ -189,7 +187,7 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -189,7 +187,7 @@ public class ReaderBean implements ReaderBeanLocal {
if (reader.isAutoproduct()) { if (reader.isAutoproduct()) {
EventUser eu = userbean.getEventUser(card.getUser().getUser(), false); EventUser eu = userbean.getEventUser(card.getUser().getUser(), false);
if (eu != null) { if (eu != null) {
AccountEvent createAc = productPBean.createAccountEvent(reader.getAutomaticProduct(), reader.getAutomaticProductCount(), eu, Calendar.getInstance()); AccountEvent createAc = productPBean.createAccountEvent(reader.getAutomaticProduct(), reader.getAutomaticProductCount(), eu, new Date());
readerfacade.flush(); readerfacade.flush();
logger.info("Creating new accountevent from autoproduct {}", createAc); logger.info("Creating new accountevent from autoproduct {}", createAc);
event.setNotes("Created automatic account event from reader. " + createAc); event.setNotes("Created automatic account event from reader. " + createAc);
...@@ -204,16 +202,13 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -204,16 +202,13 @@ public class ReaderBean implements ReaderBeanLocal {
@Override @Override
public ReaderEvent assocCodeToCard(ReaderEvent readerEvent, PrintedCard card) { public ReaderEvent assocCodeToCard(ReaderEvent readerEvent, PrintedCard card) {
// you can select between this and flushCache. // you can select between this and flushCache.
card = cardfacade.reload(card); card = cardfacade.reload(card);
CardCode code = new CardCode(card, readerEvent.getReader().getType(), readerEvent.getValue(), eventbean.getCurrentEvent()); CardCode code = new CardCode(card, readerEvent.getReader().getType(), readerEvent.getValue(), eventbean.getCurrentEvent());
cardCodeFacade.create(code); cardCodeFacade.create(code);
card.getCardCodes().add(code); card.getCardCodes().add(code);
......
...@@ -48,6 +48,7 @@ import javax.imageio.ImageIO; ...@@ -48,6 +48,7 @@ import javax.imageio.ImageIO;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.MapPermission; import fi.codecrew.moya.enums.apps.MapPermission;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
...@@ -90,13 +91,11 @@ import fi.codecrew.moya.model.User; ...@@ -90,13 +91,11 @@ import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserApproval; import fi.codecrew.moya.model.UserApproval;
import fi.codecrew.moya.model.UserImage; import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.util.MailMessage; import fi.codecrew.moya.util.MailMessage;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.I18n; import fi.codecrew.moya.utilities.I18n;
import fi.codecrew.moya.utilities.PasswordFunctions; import fi.codecrew.moya.utilities.PasswordFunctions;
import fi.codecrew.moya.utilities.SearchQuery; import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType; import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
import scala.tools.cmd.Spec;
@LocalBean @LocalBean
@Stateless @Stateless
...@@ -268,13 +267,13 @@ public class UserBean implements UserBeanLocal { ...@@ -268,13 +267,13 @@ public class UserBean implements UserBeanLocal {
return checkedRoles; return checkedRoles;
} }
private static void addRecursive(Set<Role> checkedRoles, Collection<Role> roles) { private void addRecursive(Set<Role> checkedRoles, Collection<Role> roles) {
for (Role r : roles) { for (Role r : roles) {
addRecursive(checkedRoles, r); addRecursive(checkedRoles, r);
} }
} }
private static void addRecursive(Set<Role> checkedRoles, Role role) { private void addRecursive(Set<Role> checkedRoles, Role role) {
if (role == null || checkedRoles.contains(role)) { if (role == null || checkedRoles.contains(role)) {
return; return;
} }
......
...@@ -363,15 +363,32 @@ public class VerkkomaksutFiBean implements VerkkomaksutFiBeanLocal { ...@@ -363,15 +363,32 @@ public class VerkkomaksutFiBean implements VerkkomaksutFiBeanLocal {
} }
@Override @Override
@RolesAllowed(BillPermission.S_WRITE_ALL)
public Map<Integer, String> getAuthcodeForBills(List<Bill> bills) { public Map<Integer, String> getAuthcodeForBills(List<Bill> bills) {
Map<Integer, String> ret = new HashMap<>(); Map<Integer, String> ret = new HashMap<>();
if (isSvmEnabled() && permbean.hasPermission(BillPermission.WRITE_ALL)) { if (isSvmEnabled() && permbean.hasPermission(BillPermission.WRITE_ALL)) {
String merchantId = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_ID).getTextvalue(); String merchantId = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_ID).getTextvalue();
String merchantPassword = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_PASSWORD).getTextvalue(); String merchantPassword = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_PASSWORD).getTextvalue();
for (Bill b : bills) { for (Bill b : bills) {
ret.put(b.getId(),PasswordFunctions.calculateMd5("&", merchantPassword, merchantId, b.getId().toString()).toUpperCase()); ret.put(b.getId(), PasswordFunctions.calculateMd5("&", merchantPassword, merchantId, b.getId().toString()).toUpperCase());
} }
} }
return ret; return ret;
} }
@Override
@RolesAllowed(BillPermission.S_WRITE_ALL)
public String getAuthcodeForBill(Bill selectedBill) {
if (selectedBill == null) {
return null;
}
final Bill b = billFacade.reload(selectedBill);
if (b == null) {
return null;
}
String merchantId = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_ID).getTextvalue();
String merchantPassword = eventPrivatePropertyFacade.getPropertyForEvent(LanEventPrivatePropertyKey.VERKKOMAKSU_MERCHANT_PASSWORD).getTextvalue();
return PasswordFunctions.calculateMd5("&", merchantPassword, merchantId, b.getId().toString()).toUpperCase();
}
} }
...@@ -57,6 +57,7 @@ public class VipBean implements VipBeanLocal { ...@@ -57,6 +57,7 @@ public class VipBean implements VipBeanLocal {
} }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public void create(Vip vip) { public void create(Vip vip) {
vip.setCreated(new Date()); vip.setCreated(new Date());
vip.setCreator(permbean.getCurrentUser()); vip.setCreator(permbean.getCurrentUser());
...@@ -69,6 +70,14 @@ public class VipBean implements VipBeanLocal { ...@@ -69,6 +70,14 @@ public class VipBean implements VipBeanLocal {
} }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public void delete(Vip vip) {
vip = vipFacade.merge(vip);
vipFacade.remove(vip);
}
@Override
@RolesAllowed({ VipPermission.S_VIEW })
public Vip find(Integer id) { public Vip find(Integer id) {
return vipFacade.find(id); return vipFacade.find(id);
} }
...@@ -80,6 +89,7 @@ public class VipBean implements VipBeanLocal { ...@@ -80,6 +89,7 @@ public class VipBean implements VipBeanLocal {
// } // }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public Vip createProduct(VipProduct l) { public Vip createProduct(VipProduct l) {
Vip vip = vipFacade.reload(l.getVip()); Vip vip = vipFacade.reload(l.getVip());
l.setVip(vip); l.setVip(vip);
...@@ -92,23 +102,27 @@ public class VipBean implements VipBeanLocal { ...@@ -92,23 +102,27 @@ public class VipBean implements VipBeanLocal {
} }
@Override @Override
@RolesAllowed({ VipPermission.S_VIEW })
public SearchResult<Vip> search(SearchQuery sq) { public SearchResult<Vip> search(SearchQuery sq) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public Vip save(Vip vip) { public Vip save(Vip vip) {
return vipFacade.merge(vip); return vipFacade.merge(vip);
} }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public Vip saveProduct(VipProduct prod) { public Vip saveProduct(VipProduct prod) {
VipProduct ret = vipProductFacade.merge(prod); VipProduct ret = vipProductFacade.merge(prod);
return ret.getVip(); return ret.getVip();
} }
@Override @Override
@RolesAllowed({ VipPermission.S_EDIT })
public Vip deleteProduct(VipProduct l) { public Vip deleteProduct(VipProduct l) {
l = vipProductFacade.reload(l); l = vipProductFacade.reload(l);
Vip vip = l.getVip(); Vip vip = l.getVip();
...@@ -118,6 +132,7 @@ public class VipBean implements VipBeanLocal { ...@@ -118,6 +132,7 @@ public class VipBean implements VipBeanLocal {
} }
@Override @Override
@RolesAllowed({ VipPermission.S_USAGE })
public VipProductDelivery createDelivery(VipProduct prod, BigDecimal quantity, String notes) { public VipProductDelivery createDelivery(VipProduct prod, BigDecimal quantity, String notes) {
prod = vipProductFacade.reload(prod); prod = vipProductFacade.reload(prod);
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
*/ */
package fi.codecrew.moya.facade; package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -27,10 +28,18 @@ import javax.persistence.criteria.CriteriaBuilder; ...@@ -27,10 +28,18 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.entitysearch.BillSearchQuery;
import fi.codecrew.moya.facade.callbacks.bill.BillEventPredicate;
import fi.codecrew.moya.facade.callbacks.bill.BillFilterPredicate;
import fi.codecrew.moya.facade.callbacks.bill.BillOrderPredicate;
import fi.codecrew.moya.facade.callbacks.bill.BillUserPredicate;
import fi.codecrew.moya.model.Bill; import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
@Stateless @Stateless
@LocalBean @LocalBean
...@@ -44,13 +53,6 @@ public class BillFacade extends IntegerPkGenericFacade<Bill> { ...@@ -44,13 +53,6 @@ public class BillFacade extends IntegerPkGenericFacade<Bill> {
} }
// @Override
// public void create(Bill entity) {
// super.create(entity);
// userfacade.evict(entity.getUser());
//
// }
public Integer getBiggestBillNumber() { public Integer getBiggestBillNumber() {
// SELECT max(b.billNumber) from Bill b where b.event = :event // SELECT max(b.billNumber) from Bill b where b.event = :event
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
...@@ -83,4 +85,17 @@ public class BillFacade extends IntegerPkGenericFacade<Bill> { ...@@ -83,4 +85,17 @@ public class BillFacade extends IntegerPkGenericFacade<Bill> {
} }
public SearchResult<Bill> find(BillSearchQuery queryParams) {
LanEvent event = eventbean.getCurrentEvent();
List<FacadeCallback<Bill>> callbacks = new ArrayList<>();
callbacks.add(new BillEventPredicate(event));
callbacks.add(new BillFilterPredicate(event, queryParams.getFilters()));
callbacks.add(new BillOrderPredicate(queryParams));
callbacks.add(new BillUserPredicate(queryParams.getUser()));
return super.searcher(queryParams, callbacks);
}
} }
...@@ -37,6 +37,7 @@ import org.slf4j.Logger; ...@@ -37,6 +37,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.DatabaseHasCompare; import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare; import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.facade.callbacks.EventLimiter; import fi.codecrew.moya.facade.callbacks.EventLimiter;
...@@ -52,7 +53,6 @@ import fi.codecrew.moya.model.EventUser_; ...@@ -52,7 +53,6 @@ import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_; import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder; import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
...@@ -182,8 +182,8 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -182,8 +182,8 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
} }
From<?, EventUser> listRoot = searchCallbacks(listCQuery, callbacks, EventUser.class); From<?, EventUser> listRoot = searchCallbacks(listCQuery, callbacks, EventUser.class, true);
From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class); From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class,false);
listCQuery.select(listRoot); listCQuery.select(listRoot);
countCQuery.select(cb.count(countRoot)); countCQuery.select(cb.count(countRoot));
......
...@@ -20,6 +20,7 @@ package fi.codecrew.moya.facade; ...@@ -20,6 +20,7 @@ package fi.codecrew.moya.facade;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -142,10 +143,10 @@ public class PlaceSlotFacade extends IntegerPkGenericFacade<PlaceSlot> { ...@@ -142,10 +143,10 @@ public class PlaceSlotFacade extends IntegerPkGenericFacade<PlaceSlot> {
preds.add(cb.isNotNull(bill.get(Bill_.paidDate))); preds.add(cb.isNotNull(bill.get(Bill_.paidDate)));
} else { } else {
// If expire is null or has not passed, count it // If expire is null or has not passed, count it
Path<Calendar> billexp = bill.get(Bill_.expires); Path<Date> billexp = bill.get(Bill_.expires);
preds.add(cb.or( preds.add(cb.or(
cb.isNull(billexp), cb.isNull(billexp),
cb.greaterThan(billexp, Calendar.getInstance()) cb.greaterThan(billexp, new Date())
)); ));
} }
...@@ -181,10 +182,10 @@ public class PlaceSlotFacade extends IntegerPkGenericFacade<PlaceSlot> { ...@@ -181,10 +182,10 @@ public class PlaceSlotFacade extends IntegerPkGenericFacade<PlaceSlot> {
if (paidOnly) { if (paidOnly) {
preds.add(cb.isNotNull(bill.get(Bill_.paidDate))); preds.add(cb.isNotNull(bill.get(Bill_.paidDate)));
} else { } else {
Path<Calendar> billexp = bill.get(Bill_.expires); Path<Date> billexp = bill.get(Bill_.expires);
preds.add(cb.or( preds.add(cb.or(
cb.isNull(billexp), cb.isNull(billexp),
cb.greaterThan(billexp, Calendar.getInstance()) cb.greaterThan(billexp, new Date())
)); ));
} }
......
...@@ -52,7 +52,7 @@ public class UserFacade extends IntegerPkGenericFacade<User> { ...@@ -52,7 +52,7 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
private static List<SingularAttribute<User, String>> SEARCHATTRS; private static List<SingularAttribute<User, String>> SEARCHATTRS;
static List<SingularAttribute<User, String>> getAttrlist() { public static List<SingularAttribute<User, String>> getAttrlist() {
if (SEARCHATTRS == null) if (SEARCHATTRS == null)
{ {
ArrayList<SingularAttribute<User, String>> buildAttrs = new ArrayList<SingularAttribute<User, String>>(); ArrayList<SingularAttribute<User, String>> buildAttrs = new ArrayList<SingularAttribute<User, String>>();
......
...@@ -45,7 +45,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC ...@@ -45,7 +45,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates, boolean isFullQuery) {
if (searchval == null || attributes == null || attributes.isEmpty()) { if (searchval == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
...@@ -39,7 +39,7 @@ public class EventLimiter implements FacadeCallback<EventUser> { ...@@ -39,7 +39,7 @@ public class EventLimiter implements FacadeCallback<EventUser> {
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
predicates.add(cb.equal(root.get(EventUser_.event), ev)); predicates.add(cb.equal(root.get(EventUser_.event), ev));
} }
......
...@@ -45,7 +45,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser> ...@@ -45,7 +45,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser>
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
Subquery<BigDecimal> subq = cq.subquery(BigDecimal.class); Subquery<BigDecimal> subq = cq.subquery(BigDecimal.class);
Root<AccountEvent> acRoot = subq.from(AccountEvent.class); Root<AccountEvent> acRoot = subq.from(AccountEvent.class);
subq.where(cb.equal(acRoot.get(AccountEvent_.user), root)); subq.where(cb.equal(acRoot.get(AccountEvent_.user), root));
......
...@@ -46,7 +46,7 @@ public class EventUserCardStateFilter implements FacadeCallback<EventUser> { ...@@ -46,7 +46,7 @@ public class EventUserCardStateFilter implements FacadeCallback<EventUser> {
this.states = statelist; this.states = statelist;
} }
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
if (states != null && !states.isEmpty()) if (states != null && !states.isEmpty())
{ {
for (CardState s : states) for (CardState s : states)
......
...@@ -32,7 +32,7 @@ import fi.codecrew.moya.utilities.jpa.FacadeCallback; ...@@ -32,7 +32,7 @@ import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> { public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> {
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
predicates.add(cb.isNotEmpty(root.get(EventUser_.groupMemberships))); predicates.add(cb.isNotEmpty(root.get(EventUser_.groupMemberships)));
} }
......
...@@ -66,7 +66,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> { ...@@ -66,7 +66,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> {
return checkedRoles; return checkedRoles;
} }
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
if (roles != null && !roles.isEmpty()) if (roles != null && !roles.isEmpty())
{ {
HashSet<Integer> roleids = new HashSet<Integer>(); HashSet<Integer> roleids = new HashSet<Integer>();
......
...@@ -41,9 +41,9 @@ public class EventuserToUserWrapper implements FacadeCallback<EventUser> { ...@@ -41,9 +41,9 @@ public class EventuserToUserWrapper implements FacadeCallback<EventUser> {
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
for (FacadeCallback<User> subcallback : callbacks) { for (FacadeCallback<User> subcallback : callbacks) {
subcallback.exec(cb, cq, root.get(EventUser_.user), predicates); subcallback.exec(cb, cq, root.get(EventUser_.user), predicates, isFullQuery);
} }
} }
......
...@@ -43,7 +43,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa ...@@ -43,7 +43,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates, boolean isFullQuery) {
if (searchstr == null || attributes == null || attributes.isEmpty()) { if (searchstr == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
...@@ -53,8 +53,10 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T ...@@ -53,8 +53,10 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates, boolean isFullQuery) {
if (!isFullQuery)
return;
Class<?> rettype = cq.getResultType(); Class<?> rettype = cq.getResultType();
// Check if returntype is entity or are we for example counting results // Check if returntype is entity or are we for example counting results
if (!ModelInterface.class.isAssignableFrom(rettype)) { if (!ModelInterface.class.isAssignableFrom(rettype)) {
......
...@@ -61,7 +61,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface, ...@@ -61,7 +61,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface,
} }
@Override @Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> path, List<Predicate> predicates) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> path, List<Predicate> predicates, boolean isFullQuery) {
if (searchstr == null || attributes == null || attributes.isEmpty()) { if (searchstr == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
package fi.codecrew.moya.facade.callbacks.bill;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class BillEventPredicate implements FacadeCallback<Bill> {
private final LanEvent event;
public BillEventPredicate(LanEvent e) {
this.event = e;
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<Bill> root, List<Predicate> predicates, boolean isFullQuery) {
predicates.add(cb.equal(root.get(Bill_.event), event));
}
}
package fi.codecrew.moya.facade.callbacks.bill;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.facade.callbacks.EventUserSearchPredicate;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class BillFilterPredicate extends GenericBillPredicate {
private final Map<String, Object> filters;
private final LanEvent event;
private static final Logger logger = LoggerFactory.getLogger(BillFilterPredicate.class);
public BillFilterPredicate(LanEvent event, Map<String, Object> filters) {
this.filters = filters;
this.event = event;
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<Bill> root, List<Predicate> predicates, boolean isFullQuery) {
filterloop: for (Entry<String, Object> f : filters.entrySet()) {
logger.info("f {} {}", f.getKey(), f.getValue());
SingularAttribute<? super Bill, ?> field = BILL_SEARCH_FIELDS.get(f.getKey());
Object val = f.getValue();
switch (f.getKey()) {
case "sentDate": {
// Not implemented, at least yet..
continue filterloop;
}
case "payer": {
logger.info("Searching user with {}", val);
EventUserSearchPredicate userSearch = new EventUserSearchPredicate(val.toString(), UserFacade.getAttrlist());
userSearch.exec(cb, cq, root.get(Bill_.user), predicates, isFullQuery);
continue filterloop;
}
case "referenceNumber": {
if (f.getValue() == null || f.getValue().toString().length() < 2) {
continue;
}
try {
int ref = Bill.getBillnrFromReference(event, Integer.valueOf(f.getValue().toString()));
if (ref < 0)
continue;
val = Integer.valueOf(ref);
} catch (Exception e) {
logger.info("Exception while parsing referencenumber {}", val);
continue;
}
break;
}
default:
}
predicates.add(cb.equal(root.get(field), val));
}
}
}
package fi.codecrew.moya.facade.callbacks.bill;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.entitysearch.BillSearchQuery;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
public class BillOrderPredicate extends GenericBillPredicate {
private final String sort;
private QuerySortOrder dir;
private static final Logger logger = LoggerFactory.getLogger(BillOrderPredicate.class);
public BillOrderPredicate(BillSearchQuery queryParams) {
this.sort = queryParams.getSort();
this.dir = queryParams.getSortDirection();
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<Bill> root, List<Predicate> predicates, boolean isFullQuery) {
if (!isFullQuery || dir == null || sort == null) {
return;
}
SingularAttribute<? super Bill, ?> s = BILL_SEARCH_FIELDS.get(sort);
if (s == null) {
logger.info("Not found bill sort!: {} dir {}", sort, dir);
return;
}
Path<?> path = root.get(s);
if (s.getJavaMember().getDeclaringClass().equals(EventUser.class)) {
path = ((Path<EventUser>) path).get(EventUser_.user).get(User_.login);
}
Order order = null;
switch (dir) {
case ASCENDING:
order = cb.asc(path);
break;
case DESCENDING:
order = cb.desc(path);
break;
default:
return;
}
cq.orderBy(order);
}
}
package fi.codecrew.moya.facade.callbacks.bill;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class BillUserPredicate implements FacadeCallback<Bill> {
private final EventUser user;
public BillUserPredicate(EventUser user) {
this.user = user;
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<Bill> root, List<Predicate> predicates, boolean isFullQuery) {
if (user != null) {
predicates.add(cb.equal(root.get(Bill_.user), user));
}
}
}
package fi.codecrew.moya.facade.callbacks.bill;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.metamodel.SingularAttribute;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.Bill_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public abstract class GenericBillPredicate implements FacadeCallback<Bill> {
public static final Map<String, SingularAttribute<? super Bill, ?>> BILL_SEARCH_FIELDS;
static {
HashMap<String, SingularAttribute<? super Bill, ?>> m = new HashMap<>();
m.put("address", Bill_.addr1);
m.put("billNumber", Bill_.billNumber);
m.put("user", Bill_.user);
m.put("sentDate", Bill_.sentDate);
m.put("payer", Bill_.user);
m.put("billNumber", Bill_.billNumber);
m.put("referenceNumber", Bill_.billNumber);
m.put("id", Bill_.id);
BILL_SEARCH_FIELDS = Collections.unmodifiableMap(m);
}
}
...@@ -77,7 +77,7 @@ public class CheckoutFiBeanTest { ...@@ -77,7 +77,7 @@ public class CheckoutFiBeanTest {
bill.setAddr2("Hervannantie 1"); bill.setAddr2("Hervannantie 1");
bill.setAddr3("33600 Tampere"); bill.setAddr3("33600 Tampere");
bill.setAddr4("FINLAND"); bill.setAddr4("FINLAND");
bill.setSentDateTime(d); bill.setSentDate(d);
Product prod = new Product(); Product prod = new Product();
prod.setName("Hurr"); prod.setName("Hurr");
prod.setPrice(BigDecimal.valueOf(111.11).setScale(4, RoundingMode.HALF_UP)); prod.setPrice(BigDecimal.valueOf(111.11).setScale(4, RoundingMode.HALF_UP));
......
...@@ -120,10 +120,11 @@ public class Bill extends GenericEntity { ...@@ -120,10 +120,11 @@ public class Bill extends GenericEntity {
@Column(nullable = false, name = "sent_time") @Column(nullable = false, name = "sent_time")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar sentDate = Calendar.getInstance(); private Date sentDate = new Date();
@Column(name = "payment_time", nullable = false) @Column(name = "payment_time", nullable = false)
private Integer paymentTime = 0; private Integer paymentTime = 0;
@Column(name = "notice_days", nullable = false) @Column(name = "notice_days", nullable = false)
private String noticetime = "8 vrk"; private String noticetime = "8 vrk";
@Column(name = "their_reference", nullable = false) @Column(name = "their_reference", nullable = false)
...@@ -137,7 +138,7 @@ public class Bill extends GenericEntity { ...@@ -137,7 +138,7 @@ public class Bill extends GenericEntity {
@Column(name = "expires", nullable = true) @Column(name = "expires", nullable = true)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar expires = null; private Date expires = null;
/** /**
* Notes for the event organisators about the bill. * Notes for the event organisators about the bill.
...@@ -185,6 +186,10 @@ public class Bill extends GenericEntity { ...@@ -185,6 +186,10 @@ public class Bill extends GenericEntity {
return null; return null;
} }
public static Integer getBillnrFromReference(LanEvent event, Integer reference) {
return (reference / 10) - event.getReferenceNumberBase();
}
public Integer getReferenceNumber() public Integer getReferenceNumber()
{ {
return BillUtils.createReferenceNumber(getReferenceNumberBase()); return BillUtils.createReferenceNumber(getReferenceNumberBase());
...@@ -233,7 +238,7 @@ public class Bill extends GenericEntity { ...@@ -233,7 +238,7 @@ public class Bill extends GenericEntity {
return total; return total;
} }
public Bill(LanEvent event, EventUser user, Calendar expires) { public Bill(LanEvent event, EventUser user, Date expires) {
this(event, expires); this(event, expires);
this.setUser(user); this.setUser(user);
this.setAddr1(user.getUser().getFirstnames() + " " + user.getUser().getLastname()); this.setAddr1(user.getUser().getFirstnames() + " " + user.getUser().getLastname());
...@@ -241,35 +246,31 @@ public class Bill extends GenericEntity { ...@@ -241,35 +246,31 @@ public class Bill extends GenericEntity {
this.setAddr3(user.getUser().getZip() + " " + user.getUser().getTown()); this.setAddr3(user.getUser().getZip() + " " + user.getUser().getTown());
} }
public Bill(LanEvent event, Calendar expires) { public Bill(LanEvent event, Date expires) {
this(); this();
this.expires = expires; this.expires = expires;
this.event = event; this.event = event;
} }
public Bill(LanEvent event, EventUser user, long expireTimeHours) { public Bill(LanEvent event, EventUser user, long expireTimeHours) {
this(event, user, Calendar.getInstance()); this(event, user, new Date(System.currentTimeMillis() + (expireTimeHours * 60 * 60 * 1000)));
this.expires.setTimeInMillis((System.currentTimeMillis() + (expireTimeHours * 60 * 60 * 1000)));
} }
public Bill(LanEvent event, long expireTimeHours) { public Bill(LanEvent event, long expireTimeHours) {
this(event, Calendar.getInstance()); this(event, new Date(System.currentTimeMillis() + (expireTimeHours * 60 * 60 * 1000)));
this.expires.setTimeInMillis((System.currentTimeMillis() + (expireTimeHours * 60 * 60 * 1000)));
} }
public Bill() { public Bill() {
super(); super();
this.expires = new Date(System.currentTimeMillis() + 14 * 24 * 60 * 60 * 1000); // 2vk
this.expires = Calendar.getInstance();
this.expires.setTimeInMillis((System.currentTimeMillis() + 1209600000)); // 2vk
} }
public Calendar getDueDate() { public Date getDueDate() {
Calendar dueDate = Calendar.getInstance(); Calendar dueDate = Calendar.getInstance();
dueDate.setTime(this.getSentDate().getTime()); dueDate.setTime(this.getSentDate());
dueDate.add(Calendar.DATE, this.getPaymentTime()); dueDate.add(Calendar.DATE, this.getPaymentTime());
return dueDate; return dueDate.getTime();
} }
public String getNotes() { public String getNotes() {
...@@ -419,35 +420,11 @@ public class Bill extends GenericEntity { ...@@ -419,35 +420,11 @@ public class Bill extends GenericEntity {
this.paidDate = paidDate; this.paidDate = paidDate;
} }
public Date getSentDateTime() public Date getSentDate() {
{
Date ret = null;
if (sentDate != null)
{
ret = sentDate.getTime();
}
return ret;
}
public void setSentDateTime(Date date)
{
if (date == null)
{
sentDate = null;
} else {
if (sentDate == null)
{
sentDate = Calendar.getInstance();
}
sentDate.setTime(date);
}
}
public Calendar getSentDate() {
return sentDate; return sentDate;
} }
public void setSentDate(Calendar sentDate) { public void setSentDate(Date sentDate) {
this.sentDate = sentDate; this.sentDate = sentDate;
} }
...@@ -475,11 +452,11 @@ public class Bill extends GenericEntity { ...@@ -475,11 +452,11 @@ public class Bill extends GenericEntity {
return false; return false;
} }
public Calendar getExpires() { public Date getExpires() {
return expires; return expires;
} }
public void setExpires(Calendar expires) { public void setExpires(Date expires) {
this.expires = expires; this.expires = expires;
} }
...@@ -487,14 +464,14 @@ public class Bill extends GenericEntity { ...@@ -487,14 +464,14 @@ public class Bill extends GenericEntity {
if (isPaid() || expires == null) if (isPaid() || expires == null)
return false; return false;
return Calendar.getInstance().after(expires); return new Date().after(expires);
} }
public void markExpired() { public void markExpired() {
if (isExpired() || isPaid()) if (isExpired() || isPaid())
return; return;
expires = Calendar.getInstance(); expires = new Date();
} }
@Transient @Transient
......
...@@ -34,7 +34,6 @@ import fi.codecrew.moya.utilities.jpa.ModelInterface; ...@@ -34,7 +34,6 @@ import fi.codecrew.moya.utilities.jpa.ModelInterface;
public class GenericEntity extends EntityEquals implements ModelInterface, EntityMeta { public class GenericEntity extends EntityEquals implements ModelInterface, EntityMeta {
private static final long serialVersionUID = -9041737052951021560L; private static final long serialVersionUID = -9041737052951021560L;
public static final String ID_COLUMN = "id";
@Id @Id
@Column(name = ID_COLUMN, nullable = false, updatable = false) @Column(name = ID_COLUMN, nullable = false, updatable = false)
......
../pom.xml
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fi.codecrew.moya</groupId>
<artifactId>moya</artifactId>
<name>Moya Online Youth Accumulator</name>
<packaging>pom</packaging>
<version>1.2-SNAPSHOT</version>
<modules>
<module>moya-parent</module>
<module>moya-authmodule</module>
<module>moya-cardprinter</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java-version>1.8</java-version>
<!-- plugin versions -->
<ejb-plugin-version>2.3</ejb-plugin-version>
<war-plugin-version>2.4</war-plugin-version>
<ear-plugin-version>2.9</ear-plugin-version>
<compiler-plugin-version>3.2</compiler-plugin-version>
<!-- dependency versions -->
<javaee-api-version>7.0</javaee-api-version>
<!-- EJB spec version -->
<ejb-spec-version>3.2</ejb-spec-version>
<swagger.version>1.3.12</swagger.version>
<slf4j.version>1.7.12</slf4j.version>
<logback.version>1.1.3</logback.version>
<testng.version>6.8.21</testng.version>
<javamelody.version>1.55.0</javamelody.version>
<primefaces.version>5.1</primefaces.version>
</properties>
<url>http://codecrew.fi</url>
<organization>
<name>Codecrew RY</name>
<url>http://codecrew.fi</url>
</organization>
<scm>
<connection>scm:git@gitlab.codecrew.fi:codecrew/moya.git</connection>
<url>http://gitlab.codecrew.fi</url>
</scm>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin-version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>iudex</id>
<url>http://iudex.fi/maven/</url>
</repository>
<repository>
<id>jvnet-nexus-releases</id>
<name>jvnet-nexus-releases</name>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
</repository>
<repository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</repository>
<repository>
<id>clojars.org</id>
<url>http://clojars.org/repo</url>
</repository>
</repositories>
</project>
...@@ -138,14 +138,36 @@ ...@@ -138,14 +138,36 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.wordnik</groupId> <groupId>com.wordnik</groupId>
<artifactId>swagger-jaxrs_2.11</artifactId> <artifactId>swagger-jersey2-jaxrs_2.11</artifactId>
<version>${swagger.version}</version> <version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.wordnik</groupId> <groupId>com.wordnik</groupId>
<artifactId>swagger-servlet_2.11</artifactId> <artifactId>swagger-servlet_2.11</artifactId>
<version>${swagger.version}</version> <version>${swagger.version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<parent> <parent>
......
...@@ -38,8 +38,6 @@ public class EventUserRestPojo { ...@@ -38,8 +38,6 @@ public class EventUserRestPojo {
public EventUserRestPojo() { public EventUserRestPojo() {
} }
@XmlElement() @XmlElement()
@ApiModelProperty("Nickname") @ApiModelProperty("Nickname")
public String getNick() { public String getNick() {
......
...@@ -47,6 +47,10 @@ public class SearchQuery implements Serializable { ...@@ -47,6 +47,10 @@ public class SearchQuery implements Serializable {
this.sortDirection = direction; this.sortDirection = direction;
} }
public int getFirstElement() {
return page * pagesize;
}
public int getPage() { public int getPage() {
return page; return page;
} }
......
...@@ -30,5 +30,5 @@ public interface FacadeCallback<C extends ModelInterface> { ...@@ -30,5 +30,5 @@ public interface FacadeCallback<C extends ModelInterface> {
// void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<C> root, // void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<C> root,
// List<Predicate> predicates); // List<Predicate> predicates);
void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<C> root, List<Predicate> predicates); void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<C> root, List<Predicate> predicates, boolean isFullQuery);
} }
...@@ -39,9 +39,6 @@ public abstract class GenericFacade<C extends ModelInterface> { ...@@ -39,9 +39,6 @@ public abstract class GenericFacade<C extends ModelInterface> {
private final Class<C> entClass; private final Class<C> entClass;
// private static final Logger logger =
// LoggerFactory.getLogger(GenericFacade.class);
public GenericFacade(Class<C> entityClass) { public GenericFacade(Class<C> entityClass) {
this.entClass = entityClass; this.entClass = entityClass;
} }
...@@ -115,35 +112,6 @@ public abstract class GenericFacade<C extends ModelInterface> { ...@@ -115,35 +112,6 @@ public abstract class GenericFacade<C extends ModelInterface> {
* vain ko. tapahtumaan / käyttäjään / muuhun olioon liittyvät Jos oikeasti * vain ko. tapahtumaan / käyttäjään / muuhun olioon liittyvät Jos oikeasti
* tarpeellinen luo funktio facadeen! * tarpeellinen luo funktio facadeen!
*/ */
// @Deprecated
// public List<C> findAll() {
// return findAll(null);
// }
//
// @Deprecated
// public List<C> findAll(String sort) {
// return findAll(0, 0, sort);
// }
//
// @Deprecated
// public List<C> findRange(int[] range) {
// CriteriaQuery<C> cq =
// getEm().getCriteriaBuilder().createQuery(getEntityClass());
// cq.select(cq.from(getEntityClass()));
// TypedQuery<C> q = getEm().createQuery(cq);
// q.setMaxResults(range[1] - range[0]);
// q.setFirstResult(range[0]);
// return q.getResultList();
// }
// @Deprecated
// public long count() {
// CriteriaQuery<Long> cq =
// getEm().getCriteriaBuilder().createQuery(Long.class);
// Root<C> rt = cq.from(getEntityClass());
// cq.select(getEm().getCriteriaBuilder().count(rt));
// TypedQuery<Long> q = getEm().createQuery(cq);
// return q.getSingleResult();
// }
protected static <K> K getSingleNullableResult(TypedQuery<K> q) { protected static <K> K getSingleNullableResult(TypedQuery<K> q) {
K ret = null; K ret = null;
...@@ -155,21 +123,6 @@ public abstract class GenericFacade<C extends ModelInterface> { ...@@ -155,21 +123,6 @@ public abstract class GenericFacade<C extends ModelInterface> {
return ret; return ret;
} }
// @Deprecated
// protected List<C> search(String query, String[] fields, String
// orderfield) {
// return search(0, 0, query, fields, orderfield);
// }
//
// @Deprecated
// protected SearchResult<C> searcher(int page, int pagesize, String query,
// String[] fields, String orderfield) {
// SearchResult<C> ret = new SearchResult<C>();
// ret.setResults(search(page, pagesize, query, fields, orderfield));
// ret.setResultcount(searchCount(query, fields));
// return ret;
// }
// Le fu... Tuota.. generics ei hanskaa '...' operaattoria.. tehdään siis // Le fu... Tuota.. generics ei hanskaa '...' operaattoria.. tehdään siis
// näin... :( // näin... :(
protected SearchResult<C> searcher(SearchQuery search, FacadeCallback<C> callback) { protected SearchResult<C> searcher(SearchQuery search, FacadeCallback<C> callback) {
...@@ -209,29 +162,28 @@ public abstract class GenericFacade<C extends ModelInterface> { ...@@ -209,29 +162,28 @@ public abstract class GenericFacade<C extends ModelInterface> {
CriteriaQuery<C> listCQuery = cb.createQuery(getEntityClass()); CriteriaQuery<C> listCQuery = cb.createQuery(getEntityClass());
CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class); CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class);
searchCallbacks(listCQuery, list); searchCallbacks(listCQuery, list, true);
Path<C> countRoot = searchCallbacks(countCQuery, list); Path<C> countRoot = searchCallbacks(countCQuery, list, false);
countCQuery.select(cb.count(countRoot)); countCQuery.select(cb.count(countRoot.get(ModelInterface.ID_COLUMN)));
TypedQuery<Long> countQ = getEm().createQuery(countCQuery); TypedQuery<Long> countQ = getEm().createQuery(countCQuery);
TypedQuery<C> listQ = getEm().createQuery(listCQuery); TypedQuery<C> listQ = getEm().createQuery(listCQuery);
if (search.getPagesize() > 0) { if (search.getPagesize() > 0) {
listQ.setFirstResult(search.getPage() * search.getPagesize()); listQ.setFirstResult(search.getPage() * search.getPagesize());
listQ.setMaxResults(search.getPagesize()); listQ.setMaxResults(search.getPagesize());
} }
return new SearchResult<C>(listQ.getResultList(), countQ.getSingleResult()); return new SearchResult<C>(listQ.getResultList(), countQ.getSingleResult());
} }
protected From<?, C> searchCallbacks(CriteriaQuery<?> cq, List<FacadeCallback<C>> list) { protected From<?, C> searchCallbacks(CriteriaQuery<?> cq, List<FacadeCallback<C>> list, boolean isFullQuery) {
return searchCallbacks(cq, list, getEntityClass()); return searchCallbacks(cq, list, getEntityClass(), isFullQuery);
} }
protected <T extends ModelInterface> From<?, T> searchCallbacks(CriteriaQuery<?> cq, List<FacadeCallback<T>> list, Class<T> clazz) { protected <T extends ModelInterface> From<?, T> searchCallbacks(CriteriaQuery<?> cq, List<FacadeCallback<T>> list, Class<T> clazz, boolean isFullQuery) {
Root<T> root = cq.from(clazz); Root<T> root = cq.from(clazz);
ArrayList<Predicate> predicates = handlePredicates(cq, list, root); ArrayList<Predicate> predicates = handlePredicates(cq, list, root, isFullQuery);
if (!predicates.isEmpty()) { if (!predicates.isEmpty()) {
Predicate[] preds = predicates.toArray(new Predicate[predicates.size()]); Predicate[] preds = predicates.toArray(new Predicate[predicates.size()]);
cq.where(preds); cq.where(preds);
...@@ -241,91 +193,20 @@ public abstract class GenericFacade<C extends ModelInterface> { ...@@ -241,91 +193,20 @@ public abstract class GenericFacade<C extends ModelInterface> {
} }
protected <T extends ModelInterface> ArrayList<Predicate> handlePredicates(CriteriaQuery<?> cq, List<FacadeCallback<T>> list, From<?, T> root) { protected <T extends ModelInterface> ArrayList<Predicate> handlePredicates(CriteriaQuery<?> cq, List<FacadeCallback<T>> list, From<?, T> root, boolean isFullQuery) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
ArrayList<Predicate> predicates = new ArrayList<Predicate>(); ArrayList<Predicate> predicates = new ArrayList<Predicate>();
for (FacadeCallback<T> fc : list) { for (FacadeCallback<T> fc : list) {
if (fc != null) { if (fc != null) {
fc.exec(cb, cq, root, predicates); fc.exec(cb, cq, root, predicates, isFullQuery);
} }
} }
return predicates; return predicates;
} }
// @Deprecated
// protected List<C> search(int page, int pagesize, String query, String[]
// fields, String orderfield) {
//
// CriteriaBuilder cb = getEm().getCriteriaBuilder();
// CriteriaQuery<C> cq = cb.createQuery(getEntityClass());
//
// Root<C> root = cq.from(getEntityClass());
//
// addPredicates(cq, root, query, fields);
//
// TypedQuery<C> q = getEm().createQuery(cq);
// if (pagesize > 0) {
// q.setFirstResult(page * pagesize);
// q.setMaxResults(pagesize);
//
// }
// List<C> ret = q.getResultList();
// return ret;
// }
//
// @Deprecated
// protected void addPredicates(CriteriaQuery<?> cq, Root<C> root, String
// query, String[] fields) {
// CriteriaBuilder cb = getEm().getCriteriaBuilder();
// if (query != null && !query.isEmpty() && fields != null && fields.length
// > 0) {
// List<Predicate> preds = new ArrayList<Predicate>();
// for (String field : fields) {
// Path<String> rootfield = root.get(field);
// preds.add(cb.like(cb.lower(rootfield), query));
// }
// cq.where(cb.or(preds.toArray(new Predicate[preds.size()])));
// }
//
// }
//
// @Deprecated
// protected long searchCount(String query, String[] fields) {
// CriteriaBuilder cb = getEm().getCriteriaBuilder();
// CriteriaQuery<Long> cq = cb.createQuery(Long.class);
// Root<C> root = cq.from(getEntityClass());
//
// addPredicates(cq, root, query, fields);
// cq.select(getEm().getCriteriaBuilder().count(root));
//
// TypedQuery<Long> q = getEm().createQuery(cq);
// return q.getSingleResult();
// }
// @Deprecated
// public List<C> findAll(int page, int pagesize, String sort) {
// CriteriaBuilder cb = getEm().getCriteriaBuilder();
// CriteriaQuery<C> cq = cb.createQuery(getEntityClass());
// Root<C> root = cq.from(getEntityClass());
//
// if (sort != null) {
// cq.orderBy(cb.asc(root.get(sort)));
// }
//
// cq.select(cq.from(getEntityClass()));
// TypedQuery<C> q = getEm().createQuery(cq);
//
// if (pagesize > 0) {
// q.setFirstResult(page * pagesize);
// q.setMaxResults(pagesize);
// }
//
// return q.getResultList();
// }
/** /**
* Synchronize the persistence context to the underlying database. * Synchronize the persistence context to the underlying database.
* *
......
...@@ -21,6 +21,7 @@ package fi.codecrew.moya.utilities.jpa; ...@@ -21,6 +21,7 @@ package fi.codecrew.moya.utilities.jpa;
import java.io.Serializable; import java.io.Serializable;
public interface ModelInterface extends Serializable { public interface ModelInterface extends Serializable {
public static final String ID_COLUMN = "id";
Integer getId(); Integer getId();
......
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:users="http://java.sun.com/jsf/composite/tools/user" xmlns:c="http://java.sun.com/jsp/jstl/core"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:users="http://java.sun.com/jsf/composite/tools/user" xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
...@@ -15,15 +16,19 @@ ...@@ -15,15 +16,19 @@
<h:form id="billform"> <h:form id="billform">
<p:panelGrid columns="2"> <p:panelGrid columns="2">
<h:outputLabel for="billid" value="#{i18n['bill.id']}:" /> <h:outputLabel for="billid" value="#{i18n['bill.id']}:" />
<h:inputText id="billid" value="#{billEditView.bill.id}" /> <h:inputText id="billid" value="#{billEditView.bill.id}" />
<h:outputLabel for="sentDate" value="#{i18n['bill.sentDate']}:" />
<p:calendar id="sentDate" value="#{billEditView.bill.sentDate}" pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
<h:outputLabel for="expires" value="#{i18n['bill.expires']}:" />
<p:calendar id="expires" value="#{billEditView.bill.expires}" pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
<h:outputLabel for="paidDate" value="#{i18n['bill.paidDate']}:" /> <h:outputLabel for="paidDate" value="#{i18n['bill.paidDate']}:" />
<h:inputText id="paidDate" value="#{billEditView.bill.paidDate}"> <p:calendar id="paidDate" value="#{billEditView.bill.paidDate}" pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:inputText>
<h:outputLabel for="billnr" value="#{i18n['bill.billNumber']}:" /> <h:outputLabel for="billnr" value="#{i18n['bill.billNumber']}:" />
<h:inputText id="billnr" value="#{billEditView.bill.billNumber}" /> <h:inputText id="billnr" value="#{billEditView.bill.billNumber}" />
...@@ -42,10 +47,6 @@ ...@@ -42,10 +47,6 @@
<h:outputLabel for="addr5" value="#{i18n['bill.addr5']}:" /> <h:outputLabel for="addr5" value="#{i18n['bill.addr5']}:" />
<h:inputText id="addr5" value="#{billEditView.bill.addr5}" /> <h:inputText id="addr5" value="#{billEditView.bill.addr5}" />
<h:outputLabel for="sentDate" value="#{i18n['bill.sentDate']}:" />
<h:inputText id="sentDate" value="#{billEditView.bill.sentDateTime}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:inputText>
<h:outputLabel for="paymenttime" value="#{i18n['bill.paymentTime']}:" /> <h:outputLabel for="paymenttime" value="#{i18n['bill.paymentTime']}:" />
<h:inputText id="paymenttime" value="#{billEditView.bill.paymentTime}" /> <h:inputText id="paymenttime" value="#{billEditView.bill.paymentTime}" />
......
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:bills="http://java.sun.com/jsf/composite/cditools/bills" xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html" xmlns:bills="http://java.sun.com/jsf/composite/cditools/bills" xmlns:p="http://primefaces.org/ui">
xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"
>
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:viewParam name="userid" value="#{userView.userid}" /> <f:viewParam name="userid" value="#{userView.userid}" />
<f:event type="preRenderView" listener="#{billListView.initUsersBills}" /> <f:event type="preRenderView" listener="#{billListView.initUsersBills}" />
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<bills:list /> <h:form id="billList" styleClass="moya_datatable3">
<p:outputPanel rendered="#{placeGroupView.useEticket}" >
<p:dataTable sortBy="#{user.sentDateTime}" sortOrder="descending" sortField="sentDate" paginator="true" lazy="true" rows="100" styleClass="bordertable" id="billList" value="#{billListView.lazyBillList}" var="bill"
rowStyleClass="#{bill.expired ? 'expired' : (bill.paidDate != null ? 'paid' : null)}" expandedRow="true">
<p:column >
<f:facet name="header">
<h:outputText value="${i18n['bill.sentDate']}" />
</f:facet>
<h:outputText value="#{bill.sentDateTime}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText>
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="${i18n['bill.id']}" />
</f:facet>
<h:outputText value="#{bill.id}" />
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="${i18n['bill.billNumber']}" />
</f:facet>
<h:outputText value="#{bill.billNumber}" />
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="${i18n['bill.referencenumber']}" />
</f:facet>
<h:outputText value="#{bill.referenceNumberBase}">
<f:converter binding="#{referenceNumberConverter}" />
</h:outputText>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.totalPrice']}" />
</f:facet>
<h:outputText value="#{bill.totalPrice()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2" minFractionDigits="2" type="currency" locale="#{sessionHandler.locale}" />
</h:outputText>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.vat']}" />
</f:facet>
<h:outputText value="#{bill.totalVat()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2" minFractionDigits="2" type="currency" locale="#{sessionHandler.locale}" />
</h:outputText>
</p:column>
<p:column rendered="#{(!bill.expired and sessionHandler.isEventBoolProperty('ALLOW_BILLING')) or billListView.canWriteBill}">
<ui:fragment>
<a href="#{request.contextPath}/PrintBill?billid=#{bill.id}" target="_blank">#{i18n['bill.printBill']}</a>
</ui:fragment>
</p:column>
<p:column>
<h:link outcome="/bill/showBill" value="#{i18n['bill.show']}">
<f:param name="billid" value="#{bill.id}" />
</h:link>
</p:column>
<p:rowExpansion>
<p:dataList value="#{bill.billLines}" var="line">
<h:outputText value="#{line.name}" />:
<h:outputText value="#{line.quantity}">
<f:convertNumber minFractionDigits="0" maxFractionDigits="0" />
</h:outputText>
</p:dataList>
</p:rowExpansion>
</p:dataTable>
</h:form>
<p:outputPanel rendered="#{placeGroupView.useEticket}">
<p> <p>
<p:button outcome="/place/myEtickets" value="#{i18n['placegroup.showEticket']}" /> <p:button outcome="/place/myEtickets" value="#{i18n['placegroup.showEticket']}" />
</p> </p>
</p:outputPanel> </p:outputPanel>
<br /><br /> <br />
<br />
</ui:define> </ui:define>
</ui:composition> </ui:composition>
</h:body> </h:body>
......
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
xmlns:h="http://java.sun.com/jsf/html" xmlns:bills="http://java.sun.com/jsf/composite/cditools/bills"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:event type="preRenderView" listener="#{billListView.initAllBills}" /> <f:event type="preRenderView" listener="#{billListView.initAllBills}" />
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<bills:list />
<h:form rendered="#{billListView.canWriteBill}">
<p:commandButton ajax="false" action="#{billListView.showPayButtonsAction()}" value="#{i18n['bill.showPayButtons']}" />
</h:form>
<h:form id="billList" styleClass="moya_datatable3">
<p:dataTable sortBy="#{user.sentDateTime}" sortOrder="descending" sortField="sentDate" paginator="true" lazy="true" rows="100" styleClass="bordertable" id="billList" value="#{billListView.lazyBillList}" var="bill"
rowStyleClass="#{bill.expired ? 'expired' : (bill.paidDate != null ? 'paid' : null)}">
<p:column width="35">
<p:commandButton ajax="true" update=":billInfoPanel" oncomplete="PF('billInfoPanel').show('#{component.clientId}');" icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{bill}" target="#{billListView.selectedBill}" />
</p:commandButton>
</p:column>
<p:column id="payerCol" field="payer" filterBy="#{bill.user.user.id}" sortBy="#{bill.user.user.login}">
<f:facet name="header">
<h:outputText value="#{i18n['bill.payer']}" />
</f:facet>
<h:link outcome="/useradmin/edit" value="#{bill.user.user.login} #{bill.addr1}">
<f:param name="userid" value="#{bill.user.user.id}" />
</h:link>
</p:column>
<p:column field="sentDate" sortBy="#{bill.sentDateTime}">
<f:facet name="header">
<h:outputText value="${i18n['bill.sentDate']}" />
</f:facet>
<h:outputText value="#{bill.sentDateTime}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText>
</p:column>
<p:column field="id" filterBy="#{bill.id}" sortBy="#{bill.id}">
<f:facet name="header">
<h:outputText value="${i18n['bill.id']}" />
</f:facet>
<h:outputText value="#{bill.id}" />
</p:column>
<p:column field="billNumber" filterBy="#{bill.billNumber}" sortBy="#{bill.billNumber}">
<f:facet name="header">
<h:outputText value="${i18n['bill.billNumber']}" />
</f:facet>
<h:outputText value="#{bill.billNumber}" />
</p:column>
<p:column field="referenceNumber" filterBy="#{bill.billNumber}" sortBy="#{bill.billNumber}">
<f:facet name="header">
<h:outputText value="${i18n['bill.referencenumber']}" />
</f:facet>
<h:outputText value="#{bill.referenceNumberBase}">
<f:converter binding="#{referenceNumberConverter}" />
</h:outputText>
</p:column>
<!--
<p:column headerText="#{i18n['bill.notes']}" rendered="#{productShopView.gatherBillInfo}">
<h:outputText value="#{bill.notes}" />
</p:column>
-->
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.totalPrice']}" />
</f:facet>
<h:outputText value="#{bill.totalPrice()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2" minFractionDigits="2" type="currency" locale="#{sessionHandler.locale}" />
</h:outputText>
</p:column>
<p:column>
<h:link outcome="/bill/showBill" value="#{i18n['bill.show']}">
<f:param name="billid" value="#{bill.id}" />
</h:link>
<br />
<h:link outcome="/bill/edit" value="#{i18n['bill.edit']}">
<f:param name="billid" value="#{bill.id}" />
</h:link>
<br />
<a href="#{request.contextPath}/PrintBill?billid=#{bill.id}" target="_blank">#{i18n['bill.printBill']}</a>
</p:column>
<p:column>
<p:commandButton update="billList" onerror="location.reload(true)" rendered="#{bill.paidDate == null and billListView.showPayButtons}" action="#{billListView.markPaid()}" value="#{i18n['bill.markPaid']}" />
<h:outputText rendered="#{bill.paidDate != null}" value="#{i18n['bill.isPaid']}" />
<h:outputText rendered="#{bill.paidDate == null and !billListView.showPayButtons}" value="#{i18n['bill.isNotPaid']}" />
</p:column>
</p:dataTable>
</h:form>
<p:overlayPanel appendToBody="true" id="billInfoPanel" dynamic="false" widgetVar="billInfoPanel" showEffect="fade" hideEffect="fade" dismissable="true" showCloseIcon="true" style="width:800px;min-height:80px">
<h:panelGrid columns="2">
<h:outputText value="${i18n['bill.payer']}: " />
<h:outputText value="#{billListView.selectedBill.user.wholeName}" />
<h:outputText value="${i18n['bill.id']}: " />
<h:outputText value="#{billListView.selectedBill.id}" />
<h:outputText value="${i18n['bill.vat']}: " />
<h:outputText value="#{billListView.selectedBill.totalVat()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2" minFractionDigits="2" type="currency" locale="#{sessionHandler.locale}" />
</h:outputText>
<h:outputText value="${i18n['bill.totalPrice']}: " />
<h:outputText value="#{billListView.selectedBill.totalPrice()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2" minFractionDigits="2" type="currency" locale="#{sessionHandler.locale}" />
</h:outputText>
</h:panelGrid>
<ui:fragment rendered="#{! empty billListView.paytrailMerchantId}">
<form id="paymentcheckform" target="_blank" action="https://payment.paytrail.com/check-payment" method="post">
<input name="MERCHANT_ID" type="hidden" value="#{billListView.paytrailMerchantId}" />
<input id="paymentordernr" name="ORDER_NUMBER" type="hidden" value="#{billListView.selectedBill.id}" />
<input id="paymentauthcode" name="AUTHCODE" type="hidden" value="#{billListView.paytrailAuthcodeForSelected}" />
<input name="VERSION" type="hidden" value="2" />
<input name="submit" type="submit" value="#{i18n['bill.checkPaytrail']}" />
</form>
</ui:fragment>
<p:dataTable value="#{billListView.selectedBill.billLines}" var="line">
<p:column width="49%" headerText="#{i18n['billine.product']}">
<h:outputText value="#{line.name}" />:
</p:column>
<p:column width="17%" headerText="#{i18n['billine.quantity']}">
<h:outputText value="#{line.quantity}">
<f:convertNumber minFractionDigits="0" maxFractionDigits="2" />
</h:outputText>
</p:column>
<p:column width="17%" headerText="#{i18n['billine.linePrice']}">
<h:outputText value="#{line.linePrice}">
<f:convertNumber currencyCode="EUR" type="currency" minFractionDigits="0" maxFractionDigits="2" />
</h:outputText>
</p:column>
<p:column width="17%" headerText="#{i18n['billine.vat']}">
<h:outputText value="#{line.lineVat}">
<f:convertNumber currencyCode="EUR" type="currency" minFractionDigits="0" maxFractionDigits="2" />
</h:outputText>
</p:column>
</p:dataTable>
</p:overlayPanel>
</ui:define> </ui:define>
</ui:composition> </ui:composition>
</h:body> </h:body>
......
...@@ -78,11 +78,11 @@ ...@@ -78,11 +78,11 @@
<f:facet name="header"> <f:facet name="header">
<h:outputLabel value="#{i18n['foodWave.billLines']}" /> <h:outputLabel value="#{i18n['foodWave.billLines']}" />
</f:facet> </f:facet>
<p:column sortBy="#{bill.sentDate.getTime()}"> <p:column sortBy="#{bill.sentDate}">
<f:facet name="header"> <f:facet name="header">
<h:outputLabel value="#{i18n['billLine.time']}" /> <h:outputLabel value="#{i18n['billLine.time']}" />
</f:facet> </f:facet>
<h:outputText value="#{bill.sentDate.getTime()}"> <h:outputText value="#{bill.sentDate}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
</p:column> </p:column>
......
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:tools="http://java.sun.com/jsf/composite/tools">
<composite:interface>
</composite:interface>
<composite:implementation>
<h:outputText rendered="#{billListView.bills.rowCount le 0}"
value="#{i18n['bills.noBills']}" />
<h:form rendered="#{billListView.canWriteBill}">
<p:commandButton ajax="false"
action="#{billListView.showPayButtonsAction()}"
value="#{i18n['bill.showPayButtons']}" />
</h:form>
<h:form rendered="#{billListView.bills.rowCount gt 0}" id="billList" styleClass="moya_datatable3">
<p:dataTable styleClass="bordertable" id="billList"
value="#{billListView.bills}" var="bill"
rowStyleClass="#{bill.expired ? 'expired' : (bill.paidDate != null ? 'paid' : null)}"
expandedRow="true">
<p:column style="width:16px"
rendered="#{billListView.bills.rowCount lt 20}">
<p:rowToggler />
</p:column>
<p:column rendered="#{billListView.canWriteBill}">
<f:facet name="header">
<h:outputText value="#{i18n['bill.payer']}" />
</f:facet>
<h:link rendered="#{billListView.canWriteBill}" outcome="/useradmin/edit" value="#{bill.user.user.login} #{bill.addr1}">
<f:param name="userid" value="#{bill.user.user.id}" />
</h:link>
<h:outputText rendered="#{not billListView.canWriteBill}"
value="#{bill.addr1}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.sentDate']}" />
</f:facet>
<h:outputText value="#{bill.sentDateTime}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}"
timeZone="#{sessionHandler.timezone}" />
</h:outputText>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.id']}" />
</f:facet>
<h:outputText value="#{bill.id}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.billNumber']}" />
</f:facet>
<h:outputText value="#{bill.billNumber}" />
</p:column>
<p:column rendered="#{billListView.canWriteBill}">
<f:facet name="header">
<h:outputText value="${i18n['bill.referencenumber']}" />
</f:facet>
<h:outputText value="#{bill.referenceNumberBase}">
<f:converter binding="#{referenceNumberConverter}" />
</h:outputText>
</p:column>
<!--
<p:column headerText="#{i18n['bill.notes']}" rendered="#{productShopView.gatherBillInfo}">
<h:outputText value="#{bill.notes}" />
</p:column>
-->
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.totalPrice']}" />
</f:facet>
<h:outputText value="#{bill.totalPrice()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2"
minFractionDigits="2" type="currency"
locale="#{sessionHandler.locale}" />
</h:outputText>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="${i18n['bill.vat']}" />
</f:facet>
<h:outputText value="#{bill.totalVat()}">
<f:convertNumber currencyCode="EUR" maxFractionDigits="2"
minFractionDigits="2" type="currency"
locale="#{sessionHandler.locale}" />
</h:outputText>
</p:column>
<p:column
rendered="#{(!bill.expired and sessionHandler.isEventBoolProperty('ALLOW_BILLING')) or billListView.canWriteBill}">
<ui:fragment>
<a href="#{request.contextPath}/PrintBill?billid=#{bill.id}"
target="_blank">#{i18n['bill.printBill']}</a>
</ui:fragment>
</p:column>
<p:column>
<h:link outcome="/bill/showBill" value="#{i18n['bill.show']}">
<f:param name="billid" value="#{bill.id}" />
</h:link>
</p:column>
<p:column rendered="#{billListView.canWriteBill}">
<h:link outcome="/bill/edit" value="#{i18n['bill.edit']}">
<f:param name="billid" value="#{bill.id}" />
</h:link>
</p:column>
<p:column rendered="#{billListView.canWriteBill}">
<p:commandButton update="billList" onerror="location.reload(true)"
rendered="#{bill.paidDate == null and billListView.showPayButtons}"
action="#{billListView.markPaid()}"
value="#{i18n['bill.markPaid']}" />
<h:outputText rendered="#{bill.paidDate != null}"
value="#{i18n['bill.isPaid']}" />
<h:outputText
rendered="#{bill.paidDate == null and !billListView.showPayButtons}"
value="#{i18n['bill.isNotPaid']}" />
</p:column>
<p:column rendered="#{!billListView.canWriteBill}">
<h:outputText rendered="#{bill.paidDate != null}"
value="#{i18n['bill.isPaid']}" />
<h:outputText rendered="#{bill.paidDate == null}"
value="#{i18n['bill.isNotPaid']}" />
</p:column>
<p:column rendered="#{billListView.canWriteBill and not empty billListView.paytrailMerchantId}">
<button onclick="showPaymentstatus('#{bill.id}'); return false;"><h:outputText value="#{i18n['bill.checkPaytrail']}" /></button>
</p:column>
<p:rowExpansion rendered="#{billListView.bills.rowCount lt 20}">
<p:dataList value="#{bill.billLines}" var="line">
<h:outputText value="#{line.name}" />:
<h:outputText value="#{line.quantity}">
<f:convertNumber minFractionDigits="0" maxFractionDigits="0" />
</h:outputText>
</p:dataList>
</p:rowExpansion>
</p:dataTable>
</h:form>
<form id="paymentcheckform" target="_blank" action="https://payment.paytrail.com/check-payment" method="post">
<input name="MERCHANT_ID" type="hidden" value="#{billListView.paytrailMerchantId}" />
<input id="paymentordernr" name="ORDER_NUMBER" type="hidden" value="" />
<input id="paymentauthcode" name="AUTHCODE" type="hidden" value="" />
<input name="VERSION" type="hidden" value="2" />
</form>
<script type="text/javascript" >
function showPaymentstatus(id) {
$("#paymentordernr").val(id);
$("#paymentauthcode").val(authcodes[id]);
$("#paymentcheckform").submit();
return false;
}
var authcodes ={};
<ui:repeat var="ac" value="#{billListView.paytrailAuthcodes}">
<h:outputText value="authcodes['#{ac.key}'] ='#{ac.value}';" />
</ui:repeat>
</script>
</composite:implementation>
</html>
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
</h:outputText> </h:outputText>
<h:outputLabel for="sentDate" value="#{i18n['bill.sentDate']}:" /> <h:outputLabel for="sentDate" value="#{i18n['bill.sentDate']}:" />
<h:outputText id="sentDate" value="#{cc.attrs.bill.sentDateTime}"> <h:outputText id="sentDate" value="#{cc.attrs.bill.sentDate}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
...@@ -40,7 +40,7 @@ ...@@ -40,7 +40,7 @@
<h:outputText rendered="{!cc.attrs.bill.expired and sessionHandler.isEventBoolProperty('ALLOW_BILLING')}" id="noticetime" value="#{cc.attrs.bill.noticetime}" /> <h:outputText rendered="{!cc.attrs.bill.expired and sessionHandler.isEventBoolProperty('ALLOW_BILLING')}" id="noticetime" value="#{cc.attrs.bill.noticetime}" />
<h:outputLabel rendered="#{cc.attrs.bill != null}" for="expires" value="#{i18n['bill.expires']}:" /> <h:outputLabel rendered="#{cc.attrs.bill != null}" for="expires" value="#{i18n['bill.expires']}:" />
<h:outputText rendered="#{cc.attrs.bill != null}" id="expires" value="#{cc.attrs.bill.expires.time}"> <h:outputText rendered="#{cc.attrs.bill != null}" id="expires" value="#{cc.attrs.bill.expires}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
......
...@@ -50,11 +50,11 @@ ...@@ -50,11 +50,11 @@
<h:message for="maxnum" /> <h:message for="maxnum" />
<h:outputLabel for="validFrom" value="#{i18n['discount.validFrom']}:" /> <h:outputLabel for="validFrom" value="#{i18n['discount.validFrom']}:" />
<p:calendar id="validFrom" value="#{productView.discount.validFromTime}" style="simple" pattern="#{sessionHandler.datetimeFormat}" /> <p:calendar id="validFrom" value="#{productView.discount.validFrom}" style="simple" pattern="#{sessionHandler.datetimeFormat}" />
<h:message for="validFrom" /> <h:message for="validFrom" />
<h:outputLabel for="validTo" value="#{i18n['discount.validTo']}:" /> <h:outputLabel for="validTo" value="#{i18n['discount.validTo']}:" />
<p:calendar id="validTo" value="#{productView.discount.validToTime}" style="simple" pattern="#{sessionHandler.datetimeFormat}" /> <p:calendar id="validTo" value="#{productView.discount.validTo}" style="simple" pattern="#{sessionHandler.datetimeFormat}" />
<h:message for="validTo" /> <h:message for="validTo" />
<h:outputLabel for="active" value="#{i18n['discount.active']}" /> <h:outputLabel for="active" value="#{i18n['discount.active']}" />
......
<?xml version='1.0' encoding='UTF-8' ?> <?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:composite="http://java.sun.com/jsf/composite" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui" xmlns:tools="http://java.sun.com/jsf/composite/tools"> xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui" xmlns:tools="http://java.sun.com/jsf/composite/tools">
<composite:interface> <composite:interface>
</composite:interface> </composite:interface>
<composite:implementation> <composite:implementation>
<h:outputScript library="primefaces" name="jquery/jquery.js" target="head" /> <h:outputScript library="primefaces" name="jquery/jquery.js" target="head" />
<p:dataTable id="user" value="#{userSearchView.userModel}" styleClass="moya_datatable4" rows="100" var="wra" paginator="true" lazy="true"> <p:dataTable id="user" value="#{userSearchView.userModel}" styleClass="moya_datatable4" rows="100" var="wra" paginator="true" lazy="true" sortBy="sentDate" sortOrder="descending">
<p:column sortBy="#{wra.user.nick}" headerText="#{i18n['user.nick']}"> <p:column sortBy="#{wra.user.nick}" headerText="#{i18n['user.nick']}">
<h:outputText value="#{(empty wra.user.nick)?'----':wra.user.nick}" /> <h:outputText value="#{(empty wra.user.nick)?'----':wra.user.nick}" />
......
...@@ -13,43 +13,54 @@ ...@@ -13,43 +13,54 @@
<ui:define name="title"> <ui:define name="title">
<h1>#{i18n['user.edit.title']}</h1> <h1>#{i18n['user.edit.title']}</h1>
</ui:define> </ui:define>
<ui:define name="content">
<ui:define name="content">
<h:form> <h:form>
<h:outputText value="#{userCartView.current+1}" /> / <h:outputText value="#{userCartView.userCartSize}" /> <p:toolbar>
<h:commandButton action="#{userCartView.prev()}" value="#{i18n['usercart.prev']}" rendered="#{userCartView.current > 0}" /> <f:facet name="left">
<h:commandButton action="#{userCartView.removeCurrent()}" value="#{i18n['usercart.removeCurrent']}" /> <h:outputText value="#{userCartView.current+1}" /> / <h:outputText value="#{userCartView.userCartSize}" />
<h:commandButton action="#{userCartView.next()}" value="#{i18n['usercart.next']}" rendered="#{userCartView.userCartSize > (userCartView.current+1)}" /> <span class="ui-separator"><span class="ui-icon ui-icon-grip-dotted-vertical" /></span>
<p:commandButton action="#{userCartView.prev()}" value="#{i18n['usercart.prev']}"
icon="ui-icon-circle-arrow-w" ajax="false"
rendered="#{userCartView.current > 0}" />
<p:commandButton action="#{userCartView.removeCurrent()}" value="#{i18n['usercart.removeCurrent']}"
icon="ui-icon-close" ajax="false"/>
<p:commandButton action="#{userCartView.next()}" value="#{i18n['usercart.next']}"
icon="ui-icon-circle-arrow-e" ajax="false"
rendered="#{userCartView.userCartSize > (userCartView.current+1)}" />
</f:facet>
</p:toolbar>
</h:form> </h:form>
<ui:fragment rendered="#{userView.hasPrintedCard}"> <ui:fragment rendered="#{userView.hasPrintedCard}">
<h2>Card</h2> <h2>Card</h2>
<h:form> <h:form>
<p:panelGrid columns="2"> <p:panelGrid columns="2">
<h:outputText value="#{i18n[card.name]}" /> <h:outputText value="#{i18n['printedCard.template']}" />
<h:outputText value="#{userView.printedCard.template.name}" /> <h:outputText value="#{userView.printedCard.template.name}" />
<h:selectOneMenu value="#{userView.printedCard.cardState}"> <h:outputText value="#{i18n['printedCard.cardState']}"/>
<p:selectOneButton value="#{userView.printedCard.cardState}"
valueChangeListener="#{userView.cardStateChangeListener}">
<f:selectItems value="#{userView.printedCardStates}" /> <f:selectItems value="#{userView.printedCardStates}" />
</h:selectOneMenu> <f:ajax/>
<h:commandButton action="#{userView.setCardState()}" value="#{i18n['printedCard.setState']}" /> </p:selectOneButton>
</p:panelGrid> </p:panelGrid>
</h:form> </h:form>
</ui:fragment> </ui:fragment>
<h:link outcome="/card/massprint" value="Mass Print"> <p>
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}" /> <h:link outcome="/card/massprint" value="Mass Print">
</h:link> <f:param name="cid" value="#{javax.enterprise.context.conversation.id}" />
</h:link>
</p>
<p> <p>
<h:link outcome="/useradmin/changePassword" value="#{i18n['submenu.user.changePassword']}"> <h:link outcome="/useradmin/changePassword" value="#{i18n['submenu.user.changePassword']}">
<f:param name="userid" value="#{userView.user.user.id}" /> <f:param name="userid" value="#{userView.user.user.id}" />
</h:link> </h:link>
</p> </p>
<users:edit id="useredit" commitaction="#{userCartView.saveUser()}" commitvalue="#{i18n['user.save']}" /> <users:edit id="useredit" commitaction="#{userCartView.saveUser()}" commitvalue="#{i18n['user.save']}" />
<h:form id="roleform" rendered="#{roleView.canReadRoles}"> <h:form id="roleform" rendered="#{roleView.canReadRoles}">
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<br /> <br />
<h:form id="vipform"> <h:form id="vipform">
<p:dataTable id="vip" value="#{vipListView.viplist}" widgetVar="viplist" styleClass="moya_datatable4" var="vip" filteredValue="#{vipListView.filteredVips}"> <p:dataTable id="vipList" value="#{vipListView.viplist}" widgetVar="viplist" styleClass="moya_datatable4" var="vip" filteredValue="#{vipListView.filteredVips}">
<!-- f:facet name="header"> <!-- f:facet name="header">
<p:outputPanel> <p:outputPanel>
<h:outputText value="Search all fields:" /> <h:outputText value="Search all fields:" />
...@@ -61,14 +61,19 @@ ...@@ -61,14 +61,19 @@
<p:column style="width: 90px; text-align: center;"> <p:column style="width: 90px; text-align: center;">
<p:commandButton id="delivebtn" rendered="#{not empty vip.id}" value="#{i18n['vip.deliver']}" actionListener="#{vipListView.deliverDialog}" > <p:commandButton id="delivebtn" rendered="#{not empty vip.id}" value="#{i18n['vip.deliver']}" actionListener="#{vipListView.deliverDialog}" >
<p:ajax event="dialogReturn" listener="#{vipListView.updateViplist()}" update="vip" /> <p:ajax event="dialogReturn" listener="#{vipListView.updateViplist()}" update="vipList" />
</p:commandButton> </p:commandButton>
</p:column> </p:column>
<p:column style="width: 90px;"> <p:column style="width: 70px;">
<h:link outcome="/vip/edit" value="#{i18n['vip.edit']}" > <h:link outcome="/vip/edit" value="#{i18n['vip.edit']}" >
<f:param name="id" value="#{vip.id}" /> <f:param name="id" value="#{vip.id}" />
</h:link> </h:link>
</p:column> </p:column>
<p:column style="width: 70px;">
<p:commandLink actionListener="#{vipListView.deleteEntry(vip)}" update="vipList">
<h:outputText value="#{i18n['vip.delete']}"/>
</p:commandLink>
</p:column>
</p:dataTable> </p:dataTable>
</h:form> </h:form>
</ui:define> </ui:define>
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
<configuration> <configuration>
<warSourceDirectory>WebContent</warSourceDirectory> <warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>
<packagingIncludes>WEB-INF/lib/moya-restpojo*,WEB-INF/lib/primefaces*,WEB-INF/lib/*-1.0.8.jar,**/*.xml,**/*.xhtml,**/*.properties,**/*.class,**/*.png,**/*.css,**/*.js,resources/*,swagger/**</packagingIncludes> <packagingIncludes>WEB-INF/lib/moya-restpojo*,WEB-INF/lib/primefaces*,WEB-INF/lib/all-themes-*.jar,**/*.xml,**/*.xhtml,**/*.properties,**/*.class,**/*.png,**/*.css,**/*.js,resources/*,swagger/**</packagingIncludes>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
<artifactId>moya-beans-client</artifactId> <artifactId>moya-beans-client</artifactId>
<version>1.2-SNAPSHOT</version> <version>1.2-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.primefaces</groupId> <groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId> <artifactId>primefaces</artifactId>
...@@ -32,10 +32,9 @@ ...@@ -32,10 +32,9 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.primefaces.extensions</groupId> <groupId>org.primefaces.themes</groupId>
<artifactId>all-themes</artifactId> <artifactId>all-themes</artifactId>
<version>1.0.8</version> <version>${primefaces.themeversion}</version>
<type>pom</type>
</dependency> </dependency>
<dependency> <dependency>
...@@ -43,6 +42,18 @@ ...@@ -43,6 +42,18 @@
<artifactId>moya-restpojo</artifactId> <artifactId>moya-restpojo</artifactId>
<version>1.2-SNAPSHOT</version> <version>1.2-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.16</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
......
...@@ -18,12 +18,52 @@ ...@@ -18,12 +18,52 @@
*/ */
package fi.codecrew.moya.rest; package fi.codecrew.moya.rest;
import com.wordnik.swagger.config.ScannerFactory;
import com.wordnik.swagger.jaxrs.config.BeanConfig;
import com.wordnik.swagger.jaxrs.config.ReflectiveJaxrsScanner;
import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader;
import com.wordnik.swagger.jersey.JerseyApiReader;
import com.wordnik.swagger.jersey.listing.ApiListingResourceJSON;
import com.wordnik.swagger.jersey.listing.JerseyApiDeclarationProvider;
import com.wordnik.swagger.jersey.listing.JerseyResourceListingProvider;
import com.wordnik.swagger.reader.ClassReaders;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath; import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath(RestApplicationEntrypoint.REST_PATH) @ApplicationPath(RestApplicationEntrypoint.REST_PATH)
public class RestApplicationEntrypoint extends Application { public class RestApplicationEntrypoint extends ResourceConfig {
public static final String REST_PATH = "/rest"; public static final String REST_PATH = "/rest";
private static final String BASE_URL = "/MoyaWeb";
private static final String API_RESOURCE_PACKAGE = "fi.codecrew.moya.rest";
public RestApplicationEntrypoint() {
// swagger
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setBasePath(BASE_URL + REST_PATH);
beanConfig.setResourcePackage(API_RESOURCE_PACKAGE);
beanConfig.setScan(true);
register(beanConfig);
//ReflectiveJaxrsScanner scanner = new ReflectiveJaxrsScanner();
//scanner.setResourcePackage(API_RESOURCE_PACKAGE);
//ScannerFactory.setScanner(scanner);
//ClassReaders.setReader(new JerseyApiReader());
//ClassReaders.setReader(new DefaultJaxrsApiReader());
register(ApiListingResourceJSON.class);
register(JerseyApiDeclarationProvider.class);
register(JerseyResourceListingProvider.class);
// mime multipart image uploads
register(MultiPartFeature.class);
// packages to scan
packages("com.wordnik.swagger.jaxrs.json", "fi.codecrew.moya.rest");
}
} }
...@@ -20,25 +20,29 @@ package fi.codecrew.moya.rest; ...@@ -20,25 +20,29 @@ package fi.codecrew.moya.rest;
import java.io.IOException; import java.io.IOException;
import java.security.Principal; import java.security.Principal;
import java.util.Collection;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.print.attribute.standard.Media;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part; import javax.servlet.http.Part;
import javax.ws.rs.*; import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -47,22 +51,27 @@ import com.wordnik.swagger.annotations.ApiOperation; ...@@ -47,22 +51,27 @@ import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiParam;
import fi.codecrew.moya.beans.CardTemplateBeanLocal; import fi.codecrew.moya.beans.CardTemplateBeanLocal;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal; import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.PlaceBeanLocal; import fi.codecrew.moya.beans.PlaceBeanLocal;
import fi.codecrew.moya.beans.PlaceGroupBeanLocal; import fi.codecrew.moya.beans.PlaceGroupBeanLocal;
import fi.codecrew.moya.beans.ReaderBeanLocal; import fi.codecrew.moya.beans.ReaderBeanLocal;
import fi.codecrew.moya.beans.TicketBeanLocal; import fi.codecrew.moya.beans.TicketBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.ReaderEvent;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.rest.pojo.userinfo.v1.EventUserRestPojo; import fi.codecrew.moya.rest.pojo.userinfo.v1.EventUserRestPojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.PrintedCardRestPojo; import fi.codecrew.moya.rest.pojo.userinfo.v1.PrintedCardRestPojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.SimpleEventuserRoot; import fi.codecrew.moya.rest.pojo.userinfo.v1.SimpleEventuserRoot;
import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationPlacePojo; import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationPlacePojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationRoot; import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationRoot;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder; import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import sun.security.provider.certpath.OCSPResponse;
@RequestScoped @RequestScoped
@Path("/user") @Path("/user")
...@@ -270,21 +279,6 @@ public class UserRestView { ...@@ -270,21 +279,6 @@ public class UserRestView {
return new EventUserRestPojo(); return new EventUserRestPojo();
} }
@POST
@Path("/create")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Create user", response = EventUserRestPojo.class)
public Response createEventUser() {
if (permbean.hasPermission(UserPermission.CREATE_NEW) == false) {
return Response.status(Status.FORBIDDEN).build();
}
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@GET @GET
@Path("/") @Path("/")
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
......
...@@ -17,25 +17,21 @@ import javax.ws.rs.core.MediaType; ...@@ -17,25 +17,21 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.ResponseBuilder;
import fi.codecrew.moya.enums.apps.MapPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.PermissionBeanLocal; import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.PlaceBeanLocal; import fi.codecrew.moya.beans.PlaceBeanLocal;
import fi.codecrew.moya.beans.QueueBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.beans.map.QueueBeanLocal;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventMap; import fi.codecrew.moya.model.EventMap;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Place; import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.rest.PojoUtils; import fi.codecrew.moya.rest.PojoUtils;
import fi.codecrew.moya.rest.pojo.placemap.v1.IntegerRoot; import fi.codecrew.moya.rest.pojo.placemap.v1.IntegerRoot;
import fi.codecrew.moya.rest.pojo.placemap.v1.PlacemapMapRootPojo; import fi.codecrew.moya.rest.pojo.placemap.v1.PlacemapMapRootPojo;
import fi.codecrew.moya.rest.pojo.placemap.v1.SimplePlacePojo;
import fi.codecrew.moya.rest.pojo.placemap.v1.SimplePlacelistRoot; import fi.codecrew.moya.rest.pojo.placemap.v1.SimplePlacelistRoot;
import fi.codecrew.moya.web.annotations.SelectedUser;
import fi.codecrew.moya.web.cdiview.user.UserView; import fi.codecrew.moya.web.cdiview.user.UserView;
@RequestScoped @RequestScoped
...@@ -96,8 +92,6 @@ public class PlacemapRestViewV1 { ...@@ -96,8 +92,6 @@ public class PlacemapRestViewV1 {
} }
@GET @GET
@Path("{id}/hilightedPlaces/{userid}") @Path("{id}/hilightedPlaces/{userid}")
public Response getHilightedPlaces(@PathParam("id") Integer mapId, @PathParam("userid") Integer userId) public Response getHilightedPlaces(@PathParam("id") Integer mapId, @PathParam("userid") Integer userId)
...@@ -117,7 +111,6 @@ public class PlacemapRestViewV1 { ...@@ -117,7 +111,6 @@ public class PlacemapRestViewV1 {
return Response.ok(PojoUtils.parseSimplePlaces(map.getPlaces(), user, permbean.hasPermission(UserPermission.VIEW_ALL), true)).build(); return Response.ok(PojoUtils.parseSimplePlaces(map.getPlaces(), user, permbean.hasPermission(UserPermission.VIEW_ALL), true)).build();
} }
@GET @GET
@Path("{id}/places") @Path("{id}/places")
public SimplePlacelistRoot getPlaces(@PathParam("id") Integer mapId) public SimplePlacelistRoot getPlaces(@PathParam("id") Integer mapId)
......
package fi.codecrew.moya.rest.v2;
import fi.codecrew.moya.enums.Gender;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.rest.v2.pojo.UserPojo;
import java.io.Serializable;
/**
* Created by jkj on 2015-05-31.
*/
public class PojoFactoryV2 implements Serializable {
public UserPojo createUserPojo(EventUser eventUser) {
User user = eventUser.getUser();
UserPojo pojo = new UserPojo();
pojo.eventuserId = eventUser.getId();
pojo.userId = user.getId();
pojo.nick = user.getNick();
pojo.login = user.getLogin();
pojo.firstname = user.getFirstnames();
pojo.lastname = user.getLastname();
pojo.birthday = user.getBirthday();
if (user.getGender() == Gender.MALE) {
pojo.gender = UserPojo.UserGender.MALE;
} else if (user.getGender() == Gender.FEMALE) {
pojo.gender = UserPojo.UserGender.FEMALE;
} else {
pojo.gender = UserPojo.UserGender.UNSPECIFIED;
}
pojo.phoneNumber = user.getPhone();
pojo.streetAddress = user.getAddress();
pojo.zipCode = user.getZip();
pojo.postOffice = user.getTown();
return pojo;
}
}
package fi.codecrew.moya.rest.v2;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.enums.Gender;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.rest.PojoUtils;
import fi.codecrew.moya.rest.pojo.userinfo.v1.EventUserRestPojo;
import fi.codecrew.moya.rest.v2.pojo.UserPojo;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
@RequestScoped
@Path("/v2/user")
@Api(value = "/v2/user", description = "User operations")
public class UserRestViewV2 {
private static final Logger logger = LoggerFactory.getLogger(UserRestViewV2.class);
@EJB
EventBeanLocal eventBean;
@EJB
PermissionBeanLocal permissionBean;
@EJB
UserBeanLocal userBean;
@Inject
PojoFactoryV2 pojoFactory;
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find user", response = UserPojo.class)
public Response getEventUser(@QueryParam("email") @ApiParam("Email address") String email,
@QueryParam("login") @ApiParam("Username") String userName) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
// If username not given, try to find username by email
if (userName == null || userName.isEmpty()) {
userName = userBean.findUsernameByEmailUsername(email);
}
// Get the user
EventUser eventUser = userBean.findEventuserByLogin(userName);
if (eventUser == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// Return the EventUser
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Finding event user failed", e);
return Response.serverError().build();
}
}
@POST
@Path("/create")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create user", response = UserPojo.class)
public Response createUser(UserPojo userPojo) {
if (permissionBean.hasPermission(UserPermission.CREATE_NEW) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
try {
EventUser eventUser = new EventUser(new User(), eventBean.getCurrentEvent(), permissionBean.getCurrentUser());
eventUser.setNick(userPojo.nick);
eventUser.setLogin(userPojo.login);
eventUser.setFirstnames(userPojo.firstname);
eventUser.setLastname(userPojo.lastname);
eventUser.setBirthday(userPojo.birthday);
if (userPojo.gender == UserPojo.UserGender.MALE) {
eventUser.setGender(Gender.MALE);
} else if (userPojo.gender == UserPojo.UserGender.FEMALE) {
eventUser.setGender(Gender.FEMALE);
} else {
eventUser.setGender(Gender.UNDEFINED);
}
eventUser.setPhone(userPojo.phoneNumber);
eventUser.setEmail(userPojo.email);
eventUser.setAddress(userPojo.streetAddress);
eventUser.setZip(userPojo.zipCode);
eventUser.setTown(userPojo.postOffice);
userBean.createNewUser(eventUser, userPojo.password);
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch(Exception e) {
logger.error("Creating user failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
/**
* Post forma parameter "image" with the image data in it.
* @param request
* @param userId
* @return
* @throws IOException
*/
@PUT
@Path("/{userid}/image")
@ApiOperation(value = "Upload image", response = EventUserRestPojo.class)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateUserImage(@Context HttpServletRequest request,
@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormDataParam("image") FormDataContentDisposition imageInfo,
@FormDataParam("image") InputStream imageStream,
@FormDataParam("image") FormDataBodyPart body) {
logger.info("Starting to upload new user image for user {}", userId);
try {
if (permissionBean.hasPermission(UserPermission.MODIFY) == false || permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser eventUser = userBean.findByUserId(userId, true);
logger.info("Mimetype: " + body.getMediaType());
userBean.uploadImage(eventUser, body.getMediaType().getType(), imageStream, imageInfo.getFileName(), null);
logger.info("Image uploaded");
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Image upload failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Image upload failed")).build();
}
}
/**
* Get user image
* @param userId
* @return
*/
@GET
@Path("/{userid}/image")
@ApiOperation(value = "Download user image")
//@Consumes()
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
//@Produces({MediaType.APPLICATION_JSON, "image/png", "image/jpeg"})
//@Produces({MediaType.MULTIPART_FORM_DATA, "image/png", "image/jpeg"})
public Response downloadUserImage(@PathParam("userid") @ApiParam("User ID") Integer userId) {
try {
User user = userBean.getUser(userId);
UserImage image = user.getCurrentImage();
//logger.info("Mimetype: " + body.getMediaType());
// XXX: Vectorama2015 - assume image/jpeg if mime type not known
String mimeType = image.getMimeType();
if (mimeType != null) {
if (!mimeType.equals("image/png") && !mimeType.equals("image/gif")) {
// fallback
mimeType = "image/jpeg";
}
} else {
// fallback if null
mimeType = "image/jpeg";
}
return Response.ok(image.getImageData(), mimeType).build();
} catch(Exception e) {
logger.error("Getting image failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
@POST
@Path("/{userid}/check-password")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Check user password", response = UserPojo.class)
public Response checkPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("Password") String password) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser user = userBean.findByUserId(userId, true);
if (user == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
//boolean passwordOk = user.checkPassword(password);
boolean passwordOk = userBean.checkPassword(user, password);
if (passwordOk) {
return Response.ok(pojoFactory.createUserPojo(user), MediaType.APPLICATION_JSON_TYPE).build();
}
return Response.status(Response.Status.UNAUTHORIZED).entity(PojoUtils.initErrorPojo("Wrong password")).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Checking password failed")).build();
}
}
}
package fi.codecrew.moya.rest.v2.pojo;
import com.wordnik.swagger.annotations.ApiModel;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
/**
* Created by jkj on 2015-05-31.
*/
@XmlRootElement()
@ApiModel(description = "User")
public class UserPojo {
public enum UserGender {
MALE,
FEMALE,
UNSPECIFIED
}
public String nick = "";
public String login = "";
public Integer eventuserId = 0;
public Integer userId = 0;
public String firstname = "";
public String lastname = "";
public String password = "";
// foo..
public Date birthday;
public UserGender gender;
public String phoneNumber;
public String email;
// address info
public String streetAddress;
public String zipCode;
public String postOffice;
}
package fi.codecrew.moya.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wordnik.swagger.config.ConfigFactory;
import com.wordnik.swagger.config.ScannerFactory;
import com.wordnik.swagger.config.SwaggerConfig;
import com.wordnik.swagger.jaxrs.config.ReflectiveJaxrsScanner;
import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader;
import com.wordnik.swagger.reader.ClassReaders;
import fi.codecrew.moya.rest.RestApplicationEntrypoint;
@WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 1, description = "Configure Swaggered API documentation")
public class SwaggerJaxrsConfig extends HttpServlet {
private static final long serialVersionUID = 35868122371671912L;
private static final Logger log = LoggerFactory.getLogger(SwaggerJaxrsConfig.class);
private static final String BASE_URL = "/MoyaWeb";
private static final String API_RESOURCE_PACKAGE = "fi.codecrew.moya.rest";
@Override
public void init() throws ServletException {
log.info("Initializing Swagger configuration servlet");
try {
// Configure basic API settings shown in API doc JSON.
SwaggerConfig swaggerConfig = new SwaggerConfig();
swaggerConfig.setBasePath(BASE_URL + RestApplicationEntrypoint.REST_PATH);
swaggerConfig.setApiVersion("1.0.0");
ConfigFactory.setConfig(swaggerConfig);
// Configure scanning for API annotations in desired packaget
// ServletScanner scanner = new ServletScanner();
// scanner.setResourcePackage(API_RESOURCE_PACKAGE);
// DefaultJaxrsScanner scanner = new DefaultJaxrsScanner();
ReflectiveJaxrsScanner scanner = new ReflectiveJaxrsScanner();
scanner.setResourcePackage(API_RESOURCE_PACKAGE);
ScannerFactory.setScanner(scanner);
// Reads annotations from the scanned classes.
ClassReaders.setReader(new DefaultJaxrsApiReader());
log.info("Initializing Swagger configuration succeeded.");
} catch (Exception e) {
log.error("Initializing Swagger configuration failed", e);
}
}
@Override
public void destroy() {
log.info("Destroying Swagger configuration servlet");
}
}
...@@ -20,28 +20,32 @@ package fi.codecrew.moya.web.cdiview.shop; ...@@ -20,28 +20,32 @@ package fi.codecrew.moya.web.cdiview.shop;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped; import javax.enterprise.context.ConversationScoped;
import javax.faces.model.ListDataModel;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.management.RuntimeErrorException;
import org.primefaces.model.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.BillBeanLocal; import fi.codecrew.moya.beans.BillBeanLocal;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.VerkkomaksutFiBeanLocal; import fi.codecrew.moya.beans.VerkkomaksutFiBeanLocal;
import fi.codecrew.moya.bortal.views.BillSummary; import fi.codecrew.moya.bortal.views.BillSummary;
import fi.codecrew.moya.entitysearch.BillSearchQuery;
import fi.codecrew.moya.enums.apps.BillPermission; import fi.codecrew.moya.enums.apps.BillPermission;
import fi.codecrew.moya.exceptions.BillException; import fi.codecrew.moya.exceptions.BillException;
import fi.codecrew.moya.model.Bill; import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.annotations.SelectedUser; import fi.codecrew.moya.web.annotations.SelectedUser;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
import fi.codecrew.moya.web.helpers.LazyEntityDataModel;
@Named @Named
@ConversationScoped @ConversationScoped
...@@ -56,59 +60,73 @@ public class BillListView extends GenericCDIView { ...@@ -56,59 +60,73 @@ public class BillListView extends GenericCDIView {
@SelectedUser @SelectedUser
private transient EventUser user; private transient EventUser user;
private Bill selectedBill;
@EJB @EJB
private transient BillBeanLocal billbean; private transient BillBeanLocal billbean;
@EJB
private EventBeanLocal eventbean;
private transient ListDataModel<Bill> bills; // private transient ListDataModel<Bill> bills;
//
private boolean writeBill; private boolean writeBill;
private ArrayList<BillSummary> billsummary; private ArrayList<BillSummary> billsummary;
private boolean showPayButtons = false; private boolean showPayButtons = false;
public String showPayButtonsAction()
{
if (super.hasPermission(BillPermission.WRITE_ALL))
{
showPayButtons = true;
}
return null;
}
@EJB @EJB
private VerkkomaksutFiBeanLocal paytrailBean; private VerkkomaksutFiBeanLocal paytrailBean;
private String paytrailMerchantId; private String paytrailMerchantId;
private Map<Integer, String> paytrailAuthcodes; private LazyBillDataModel lazyBillList;
public void showPayButtonsAction()
{
if (super.hasPermission(BillPermission.WRITE_ALL)) {
showPayButtons = true;
}
}
private static final Logger logger = LoggerFactory.getLogger(BillListView.class);
public void initAllBills() { public void initAllBills() {
if (super.requirePermissions(BillPermission.READ_ALL)) { if (super.requirePermissions(BillPermission.READ_ALL) && lazyBillList == null) {
beginConversation(); beginConversation();
List<Bill> billList = billbean.findAll(); logger.info("Initializing lazyList");
bills = new ListDataModel<Bill>(billList); lazyBillList = new LazyBillDataModel(true);
writeBill = permbean.hasPermission(BillPermission.WRITE_ALL); writeBill = permbean.hasPermission(BillPermission.WRITE_ALL);
if (paytrailBean.isSvmEnabled()) { if (paytrailBean.isSvmEnabled() && writeBill) {
setPaytrailMerchantId(paytrailBean.getMerchantId()); paytrailMerchantId = paytrailBean.getMerchantId();
paytrailAuthcodes = paytrailBean.getAuthcodeForBills(billList);
} }
// List<Bill> billList = billbean.findAll();
// bills = new ListDataModel<Bill>(billList);
// if (paytrailBean.isSvmEnabled()) {
// setPaytrailMerchantId(paytrailBean.getMerchantId());
// paytrailAuthcodes = paytrailBean.getAuthcodeForBills(billList);
// }
} }
} }
public Object[] getPaytrailAuthcodes() { public String getPaytrailAuthcodeForSelected() {
Object[] retarr = null; return paytrailBean.getAuthcodeForBill(selectedBill);
if (paytrailAuthcodes != null)
{
Set<Entry<Integer, String>> ret = paytrailAuthcodes.entrySet();
retarr = ret.toArray();
}
return retarr;
} }
public String getAuthcodeForBill(Integer id) { // public Object[] getPaytrailAuthcodes() {
return paytrailAuthcodes.get(id); // Object[] retarr = null;
} // if (paytrailAuthcodes != null)
// {
// Set<Entry<Integer, String>> ret = paytrailAuthcodes.entrySet();
// retarr = ret.toArray();
// }
// return retarr;
// }
// public String getAuthcodeForBill(Integer id) {
// return paytrailAuthcodes.get(id);
// }
public void initSummaryView() public void initSummaryView()
{ {
...@@ -120,7 +138,9 @@ public class BillListView extends GenericCDIView { ...@@ -120,7 +138,9 @@ public class BillListView extends GenericCDIView {
public void initUsersBills() { public void initUsersBills() {
if (requirePermissions(BillPermission.VIEW_OWN, permbean.isLoggedIn())) { if (requirePermissions(BillPermission.VIEW_OWN, permbean.isLoggedIn())) {
beginConversation(); beginConversation();
bills = new ListDataModel<Bill>(billbean.find(user)); lazyBillList = new LazyBillDataModel(false);
// bills = new ListDataModel<Bill>(billbean.find(user));
writeBill = permbean.hasPermission(BillPermission.WRITE_ALL); writeBill = permbean.hasPermission(BillPermission.WRITE_ALL);
} }
...@@ -130,7 +150,8 @@ public class BillListView extends GenericCDIView { ...@@ -130,7 +150,8 @@ public class BillListView extends GenericCDIView {
if (permbean.hasPermission(BillPermission.WRITE_ALL)) { if (permbean.hasPermission(BillPermission.WRITE_ALL)) {
try { try {
billbean.markPaid(bills.getRowData(), Calendar.getInstance(), false); Bill bill = lazyBillList.getRowData();
billbean.markPaid(bill, Calendar.getInstance(), false);
} catch (BillException x) { } catch (BillException x) {
throw new RuntimeException(x); throw new RuntimeException(x);
} }
...@@ -142,15 +163,15 @@ public class BillListView extends GenericCDIView { ...@@ -142,15 +163,15 @@ public class BillListView extends GenericCDIView {
return null; return null;
} }
public void setBills(ListDataModel<Bill> bills) { // public void setBills(ListDataModel<Bill> bills) {
this.bills = bills; // this.bills = bills;
} // }
//
public ListDataModel<Bill> getBills() { // public ListDataModel<Bill> getBills() {
//
return bills; // return bills;
} // }
//
public boolean isCanWriteBill() { public boolean isCanWriteBill() {
return writeBill; return writeBill;
} }
...@@ -183,4 +204,54 @@ public class BillListView extends GenericCDIView { ...@@ -183,4 +204,54 @@ public class BillListView extends GenericCDIView {
this.paytrailMerchantId = paytrailMerchantId; this.paytrailMerchantId = paytrailMerchantId;
} }
public LazyBillDataModel getLazyBillList() {
return lazyBillList;
}
public void setLazyBillList(LazyBillDataModel lazyBillList) {
this.lazyBillList = lazyBillList;
}
public Bill getSelectedBill() {
return selectedBill;
}
public void setSelectedBill(Bill selectedBill) {
logger.info("Setting selected bill to {}", selectedBill);
this.selectedBill = selectedBill;
}
public class LazyBillDataModel extends LazyEntityDataModel<Bill> {
private static final long serialVersionUID = -7870775597332505494L;
private final boolean allBills;
private EventUser user;
public LazyBillDataModel(boolean allBills) {
this.allBills = allBills;
}
@Override
public List<Bill> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
logger.info("Loading with {}, {}", first, pageSize);
QuerySortOrder sort = getSort(sortOrder);
BillSearchQuery q = new BillSearchQuery(first, pageSize, sortField, sort, filters);
q.setUser(user);
SearchResult<Bill> ret;
if (allBills) {
ret = billbean.findAll(q);
} else {
ret = billbean.findUsers(q);
}
this.setRowCount((int) ret.getResultcount());
return ret.getResults();
}
@Override
protected Bill findEntity(Integer id) {
return billbean.findById(id);
}
}
} }
...@@ -32,12 +32,12 @@ import fi.codecrew.moya.beans.EventBeanLocal; ...@@ -32,12 +32,12 @@ import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.OrgRoleBeanLocal; import fi.codecrew.moya.beans.OrgRoleBeanLocal;
import fi.codecrew.moya.beans.RoleBeanLocal; import fi.codecrew.moya.beans.RoleBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.UserPermission; import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.OrgRole; import fi.codecrew.moya.model.OrgRole;
import fi.codecrew.moya.model.Role; import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
......
...@@ -34,6 +34,7 @@ import org.slf4j.LoggerFactory; ...@@ -34,6 +34,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.RoleBeanLocal; import fi.codecrew.moya.beans.RoleBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.BortalApplication; import fi.codecrew.moya.enums.BortalApplication;
import fi.codecrew.moya.enums.apps.IAppPermission; import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.UserPermission; import fi.codecrew.moya.enums.apps.UserPermission;
...@@ -41,7 +42,6 @@ import fi.codecrew.moya.model.ApplicationPermission; ...@@ -41,7 +42,6 @@ import fi.codecrew.moya.model.ApplicationPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Role; import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
import fi.codecrew.moya.web.helpers.BortalApplicationWrapper; import fi.codecrew.moya.web.helpers.BortalApplicationWrapper;
......
...@@ -33,10 +33,10 @@ import org.slf4j.Logger; ...@@ -33,10 +33,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.UserPermission; import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder; import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.ModelInterface; import fi.codecrew.moya.utilities.jpa.ModelInterface;
......
...@@ -29,6 +29,8 @@ import javax.enterprise.context.ConversationScoped; ...@@ -29,6 +29,8 @@ import javax.enterprise.context.ConversationScoped;
import javax.enterprise.inject.Produces; import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext; import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.json.JsonObject; import javax.json.JsonObject;
...@@ -657,4 +659,8 @@ public class UserView extends GenericCDIView { ...@@ -657,4 +659,8 @@ public class UserView extends GenericCDIView {
this.emailCheck = emailCheck; this.emailCheck = emailCheck;
} }
public void cardStateChangeListener(ValueChangeEvent valueChange) {
logger.debug("PrintedCard state changed from {} to {}", valueChange.getOldValue(), valueChange.getNewValue());
setCardState();
}
} }
...@@ -71,6 +71,12 @@ public class VipListView extends PaginationView<Vip> { ...@@ -71,6 +71,12 @@ public class VipListView extends PaginationView<Vip> {
RequestContext.getCurrentInstance().openDialog("/vip/deliver", options, params); RequestContext.getCurrentInstance().openDialog("/vip/deliver", options, params);
} }
public void deleteEntry(Vip item) {
vipBean.delete(item);
viplist = null;
initView();
}
public ListDataModel<Vip> getViplist() { public ListDataModel<Vip> getViplist() {
return viplist; return viplist;
} }
......
...@@ -16,12 +16,12 @@ import fi.codecrew.moya.beans.PermissionBeanLocal; ...@@ -16,12 +16,12 @@ import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.ProductBeanLocal; import fi.codecrew.moya.beans.ProductBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.beans.VipBeanLocal; import fi.codecrew.moya.beans.VipBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.VipPermission; import fi.codecrew.moya.enums.apps.VipPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Product; import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.Vip; import fi.codecrew.moya.model.Vip;
import fi.codecrew.moya.model.VipProduct; import fi.codecrew.moya.model.VipProduct;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
......
...@@ -19,13 +19,14 @@ ...@@ -19,13 +19,14 @@
package fi.codecrew.moya.web.flow; package fi.codecrew.moya.web.flow;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.ReaderEvent; import fi.codecrew.moya.model.ReaderEvent;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
import fi.codecrew.moya.web.cdiview.reader.ReaderView; import fi.codecrew.moya.web.cdiview.reader.ReaderView;
import fi.codecrew.moya.web.cdiview.user.UserView; import fi.codecrew.moya.web.cdiview.user.UserView;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -33,6 +34,7 @@ import javax.ejb.EJB; ...@@ -33,6 +34,7 @@ import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped; import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.util.List; import java.util.List;
@Named @Named
......
...@@ -20,6 +20,7 @@ package fi.codecrew.moya.web.helper; ...@@ -20,6 +20,7 @@ package fi.codecrew.moya.web.helper;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -51,7 +52,7 @@ public class ProductShopItemHelper extends GenericCDIView { ...@@ -51,7 +52,7 @@ public class ProductShopItemHelper extends GenericCDIView {
} else { } else {
item.setInternalPrice(item.getProduct().getPrice().abs().multiply(item.getCount())); item.setInternalPrice(item.getProduct().getPrice().abs().multiply(item.getCount()));
item.setInternalDiscounts(discountBean.getActiveDiscountsByProduct(item.getProduct(), item.getCount(), Calendar.getInstance(), item.getUser())); item.setInternalDiscounts(discountBean.getActiveDiscountsByProduct(item.getProduct(), item.getCount(), new Date(), item.getUser()));
item.setInternalDiscountValues(new HashMap<Integer, BigDecimal>()); item.setInternalDiscountValues(new HashMap<Integer, BigDecimal>());
......
package fi.codecrew.moya.web.helpers;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import fi.codecrew.moya.model.GenericEntity;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
public abstract class LazyEntityDataModel<T extends GenericEntity> extends LazyDataModel<T> {
private static final long serialVersionUID = -7424836549904164915L;
@Override
public abstract List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters);
@Override
public T getRowData(String key) {
if (key == null || key.isEmpty() || key.equals("0"))
return null;
return findEntity(Integer.parseInt(key));
}
protected abstract T findEntity(Integer id);
@Override
public Object getRowKey(T entity) {
Integer ret = 0;
if (entity != null)
ret = entity.getId();
return ret;
}
protected QuerySortOrder getSort(SortOrder sortOrder) {
QuerySortOrder sort = QuerySortOrder.UNSORTED;
switch (sortOrder) {
case ASCENDING:
sort = QuerySortOrder.ASCENDING;
break;
case DESCENDING:
sort = QuerySortOrder.DESCENDING;
break;
case UNSORTED:
default:
sort = QuerySortOrder.UNSORTED;
break;
}
return sort;
}
}
...@@ -31,11 +31,11 @@ import javax.inject.Named; ...@@ -31,11 +31,11 @@ import javax.inject.Named;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.LectureBeanLocal; import fi.codecrew.moya.beans.LectureBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal; import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.LecturePermission; import fi.codecrew.moya.enums.apps.LecturePermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Lecture; import fi.codecrew.moya.model.Lecture;
import fi.codecrew.moya.model.LectureGroup; import fi.codecrew.moya.model.LectureGroup;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.web.cdiview.GenericCDIView; import fi.codecrew.moya.web.cdiview.GenericCDIView;
import fi.codecrew.moya.web.cdiview.user.UserView; import fi.codecrew.moya.web.cdiview.user.UserView;
......
...@@ -536,3 +536,4 @@ vipProduct.name = Tuote ...@@ -536,3 +536,4 @@ vipProduct.name = Tuote
vipProduct.quantity = Lukum\u00E4\u00E4r\u00E4 vipProduct.quantity = Lukum\u00E4\u00E4r\u00E4
yes = Kyll\u00E4 yes = Kyll\u00E4
vip.delete=Poista
...@@ -72,7 +72,7 @@ bill.billMarkedPaidMail.subject = Bill marked paid ...@@ -72,7 +72,7 @@ bill.billMarkedPaidMail.subject = Bill marked paid
bill.billNumber = Order number bill.billNumber = Order number
bill.billPaidDate = Paid date bill.billPaidDate = Paid date
bill.cancel = Cancel bill bill.cancel = Cancel bill
bill.checkPaytrail = Check payment bill.checkPaytrail = Check payment status
bill.deliveryTerms = Delivery terms bill.deliveryTerms = Delivery terms
bill.edit = edit bill.edit = edit
bill.expires = Expires bill.expires = Expires
...@@ -119,6 +119,7 @@ billedit.billnotfound = Bill not found. Select again. ...@@ -119,6 +119,7 @@ billedit.billnotfound = Bill not found. Select again.
billine.linePrice = Total (inc. vat) billine.linePrice = Total (inc. vat)
billine.name = Ticket billine.name = Ticket
billine.product = Product
billine.quantity = Quantityicket billine.quantity = Quantityicket
billine.referencedProduct = Referenced product billine.referencedProduct = Referenced product
billine.save = Save billine.save = Save
...@@ -1777,3 +1778,4 @@ voting.create.voteEnd = Voting close ...@@ -1777,3 +1778,4 @@ voting.create.voteEnd = Voting close
voting.create.voteStart = Voting start voting.create.voteStart = Voting start
yes = Yes yes = Yes
vip.delete=Delete
...@@ -1761,3 +1761,4 @@ voting.create.voteEnd = \u00C4\u00E4nestys kiinni ...@@ -1761,3 +1761,4 @@ voting.create.voteEnd = \u00C4\u00E4nestys kiinni
voting.create.voteStart = \u00C4\u00E4nestys auki voting.create.voteStart = \u00C4\u00E4nestys auki
yes = Kyll\u00E4 yes = Kyll\u00E4
vip.delete=Poista
...@@ -32,7 +32,8 @@ ...@@ -32,7 +32,8 @@
<logback.version>1.1.3</logback.version> <logback.version>1.1.3</logback.version>
<testng.version>6.8.21</testng.version> <testng.version>6.8.21</testng.version>
<javamelody.version>1.55.0</javamelody.version> <javamelody.version>1.55.0</javamelody.version>
<primefaces.version>5.1</primefaces.version> <primefaces.version>5.2</primefaces.version>
<primefaces.themeversion>1.0.10</primefaces.themeversion>
</properties> </properties>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!