package service; import api.v1.Product; import com.avaje.ebean.Expr; import exceptions.PoseidonException; import kundedb.service.KundedbService; import mapper.ProductMapper; import models.OrderStatus; import models.ProductModel; import models.OrderModel; import org.joda.time.DateTime; import play.mvc.Http; import validators.ProductValidator; import validators.ValidationResult; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ProductService extends PoseidonService { public ProductService(String username) { super(username); } public List<ProductModel> findAll() { return ProductModel.find.all(); } public ProductModel getById(long id) { return ProductModel.find.byId(id); } public ProductModel findByName(String name) { return ProductModel.find.where().ieq("name", name).findUnique(); } public ProductModel findBySku(String sku) { return ProductModel.find.where().ieq("sku", sku).findUnique(); } public ProductModel createOrUpdate(Product apiProduct) { ProductModel mProduct = null; if ((apiProduct.id != null) && (apiProduct.id > 0)) { mProduct = updateExisting(apiProduct); } else { ProductModel p = ProductModel.findByName(apiProduct.name); if (p != null && p.deleted == null) { throw new PoseidonException(Http.Status.BAD_REQUEST, "Produktets navn er ikke unikt"); } if (p != null) { // exists, but deleted, resurrect it mProduct = p; mProduct.deleted = null; mProduct.deletedBy = null; } else { mProduct = new ProductMapper().mapToModel(apiProduct,mProduct); } mProduct.created = PoseidonService.getNow().toDate(); mProduct.createdBy = getUser(); } mProduct.save(); return mProduct; } private ProductModel updateExisting(Product aProduct) { ProductModel mProduct = getById(aProduct.id); mProduct.name = aProduct.name; mProduct.price = aProduct.price; mProduct.sku = aProduct.sku; mProduct.positionRequired = aProduct.positionRequired; mProduct.updated = PoseidonService.getNow().toDate(); mProduct.updatedBy = getUser(); return mProduct; } public ProductModel deleteProduct(Long id) { ProductModel productModel = getById(id); if (productModel != null) { productModel.deleted = PoseidonService.getNow().toDate(); productModel.deletedBy = getUser(); productModel.save(); } return productModel; } }