Moderate severityNVD Advisory· Published Mar 29, 2022· Updated Sep 16, 2024
Shopizer - Stored XSS in Manage Images
CVE-2022-23059
Description
A Stored Cross Site Scripting (XSS) vulnerability exists in Shopizer versions 2.0 through 2.17.0 via the “Manage Images” tab, which allows an attacker to upload a SVG file containing malicious JavaScript code.
Affected packages
Versions sourced from the GitHub Security Advisory.
| Package | Affected versions | Patched versions |
|---|---|---|
com.shopizer:shopizerMaven | >= 2.0.2, < 3.0.0 | 3.0.0 |
Affected products
1- Range: 2.0
Patches
16b9f1ecd303bworking version 3.0.alpha
158 files changed · +2785 −19192
pom.xml+2 −2 modified@@ -22,7 +22,7 @@ <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> - <version>2.3.8.RELEASE</version> + <version>2.5.5</version> </parent> <modules> @@ -611,4 +611,4 @@ </plugins> </build> -</project> +</project> \ No newline at end of file
README.md+258 −0 modified@@ -1,3 +1,6 @@ +------------------------------------------------------------------------ +English +------------------------------------------------------------------------ Shopizer (for java 1.8 +) ------------------- @@ -119,4 +122,259 @@ If you have interest in giving feedback or for participating to Shopizer project Feel to use the contact form <http://www.shopizer.com/contact.html> and share your email address so we can send an invite to our Slack channel +### How to Contribute: +------------------- +Fork the repository to your GitHub account + +Clone from fork repository +------------------- + + $ git clone https://github.com/yourusername/shopizer.git + +Build application according to steps provided above + +Synchronize lastest version with the upstream +------------------- + + $ git remote add upstream https://github.com/yourusername/shopizer.git + $ git pull upstream 2.17.0 + +Create new branch in your repository +------------------- + + $ git checkout -b branch-name + + +Check your branch status before commit to the branch +------------------- + + $ git status + $ git commit + +Push changes to GitHub +------------------- + + $ git push -u origin HEAD + + + +------------------------------------------------------------------------ +FRENCH +------------------------------------------------------------------------ + +Shopizer (pour java 1.8 +) +------------------- + +[](https://github.com/shopizer-ecommerce/shopizer/tree/2.12.0) +[](http://www.shopizer.com/) +[](https://hub.docker.com/r/shopizerecomm/shopizer) +[](http://stackoverflow.com/questions/tagged/shopizer) + + +Logiciel de commerce électronique open source Java + +- Panier +- Catalogue +- Chercher +- Check-out +- Administration +- API REST + +Voir la démo (jsp): +------------------- +http://aws-demo.shopizer.com:8080/ + +Voir la démo (angular): +------------------- +Bientôt disponible + + +Obtenez le code: +------------------- +Clonez le référentiel: + + $ git clone git://github.com/shopizer-ecommerce/shopizer.git + +Si c'est la première fois que vous utilisez Github, consultez http://help.github.com to learn the basics. + + Vous pouvez également télécharger le fichier zip contenant le code depuis https://github.com/shopizer-ecommerce/shopizer + +Pour créer l'application: +------------------- +Depuis la ligne de commande: + + $ cd shopizer + $ mvnw clean install + + +Exécutez l'application depuis Tomcat +------------------- +copier sm-shop / target / ROOT.war vers tomcat ou tout autre répertoire de déploiement du serveur d'applications + +Augmenter l'espace du tas à 1024 m (Heap space) + +### Configuration de l'espace de tas dans Tomcat (Heap space): + + +Si vous utilisez Tomcat, modifiez catalina.bat pour les utilisateurs Windows ou catalina.sh pour les utilisateurs Linux / Mac + + sous Windows + set JAVA_OPTS="-Xms1024m -Xmx1024m -XX:MaxPermSize=256m" + + sous Linux / Mac + export JAVA_OPTS="-Xms1024m -Xmx1024m -XX:MaxPermSize=256m" + +Exécutez l'application à partir de Spring Boot +------------------- + + $ cd sm-shop + $ mvnw spring-boot:run + +Exécutez l'application à partir de Spring Boot dans eclipse +------------------- + +Faites un clic droit sur com.salesmanager.shop.application.ShopApplication + +exécuter en tant qu'application Java + +### Accédez à l'application: +------------------- + +Accédez à l'application Web déployée à l'adresse: http: //localhost:8080/ + +Accédez à la section d'administration à l'adresse: http://localhost: 8080/admin + +nom d'utilisateur: admin@shopizer.com + +mot de passe: password + +Les instructions ci-dessus vous permettront d'exécuter l'application avec les paramètres et configurations par défaut. +Veuillez lire les instructions pour vous connecter à MySQL, configurer un serveur de messagerie et configurer d'autres sous-systèmes + + +### Documentation: +------------------- + +Documentation disponible sur le wiki <http://shopizer-ecommerce.github.io/shopizer/#> + +ChatOps <https://shopizer.slack.com> - Rejoignez notre chaîne Slack https://shopizer-slackin.herokuapp.com/ + +Plus d'informations sont disponibles sur le site Web de Shopizer ici <http://www.shopizer.com> + +### Participation: +------------------- + +Si vous souhaitez donner votre avis ou participer de quelque manière que ce soit au projet Shopizer +N'hésitez pas à utiliser le formulaire de contact <http://www.shopizer.com/contact.html> et à partager votre adresse email +afin que nous puissions envoyer une invitation sur notre chaîne Slack + + + +------------------------------------------------------------------------ +中文版本 +------------------------------------------------------------------------ +Shopizer(适用于 java 1.8 +) +------------------- + +[](https://github.com/shopizer-ecommerce/shopizer/tree/2.12.0) +[](http://www.shopizer.com/) +[](https://hub.docker.com/r/shopizerecomm/shopizer) +[](http://stackoverflow.com/questions/tagged/shopizer) + +Java开源电子商务软件 + +- 购物车 +- 目录 +- 搜索 +- 查看 +- 行政 +- REST API + +参阅演示(jsp): +------------------- +http://aws-demo.shopizer.com:8080/ + +请参阅演示(角度): +------------------- +即将推出 + + +获取代码: +------------------- +克隆存储库: + +$ git clone git://github.com/shopizer-ecommerce/shopizer.git + +如果这是您第一次使用 Github,请查看 http://help.github.com 以了解基础知识。 + +您还可以从 https://github.com/shopizer-ecommerce/shopizer 下载包含代码的 zip 文件 + +将要构建应用程序: + +------------------- +从命令行: + + $ cd shopizer + $ mvnw clean install + +从 Tomcat 运行应用程序 +------------------- +将 sm-shop/target/ROOT.war 复制到 tomcat 或任何其他应用服务器部署目录 + +将堆空间增加到 1024 m + +###Tomcat中的堆空间配置: + + +如果您使用 Tomcat,请为 windows 用户编辑 catalina.bat 或为 linux / Mac 用户编辑 catalina.sh + +在 Windows 中 +设置 JAVA_OPTS="-Xms1024m -Xmx1024m -XX:MaxPermSize=256m" + +在 Linux / Mac 中 +导出 JAVA_OPTS="-Xms1024m -Xmx1024m -XX:MaxPermSize=256m" + +从 Spring Boot 运行应用程序 +------------------- + + $ cd sm-shop + $ mvnw spring-boot:run + +在 Eclipse 中从 Spring Boot 运行应用程序 +------------------- + +右键单击 com.salesmanager.shop.application.ShopApplication + +作为 Java 应用程序运行 + +### 访问应用程序: +------------------- + +访问已部署的 Web 应用程序:http://localhost:8080/ + +访问管理部分:http://localhost:8080/admin + +用户名:admin@shopizer.com + +密码:password + +上述说明将让您使用默认设置和配置运行应用程序。 +请阅读有关如何连接到 MySQL、配置电子邮件服务器和配置其他子系统的说明 + + +### 文档: +------------------- + +可从 wiki <http://shopizer-ecommerce.github.io/shopizer/#> 获得的文档 + +ChatOps <https://shopizer.slack.com> - 加入我们的 Slack 频道 https://shopizer-slackin.herokuapp.com/ + +更多信息可在此处的购物者网站上获得 <http://www.shopizer.com> + +### 参与: +------------------- + +如果您有兴趣提供反馈或以任何方式参与 Shopizer 项目 +请使用联系表 <http://www.shopizer.com/contact.html> 并分享您的电子邮件地址 +这样我们就可以邀请您进入我们的 Slack 频道
sm-core-model/src/main/java/com/salesmanager/core/constants/SchemaConstant.java+3 −1 modified@@ -12,7 +12,9 @@ public class SchemaConstant { * */ //public static final String[] LANGUAGE_ISO_CODE = {"en", "fr", "ru", "es", "ar"}; - public static final String[] LANGUAGE_ISO_CODE = {"en", "fr", "es"}; + + @Deprecated + public static final String[] LANGUAGE_ISO_CODE = {"en", "fr", "es"}; //which descriptions will ve used for reference data public final static int DESCRIPTION_ID_ALLOCATION_SIZE = 1; public final static int DESCRIPTION_ID_START_VALUE = 2000;
sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/availability/ProductAvailability.java+1 −2 modified@@ -29,7 +29,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.salesmanager.core.constants.SchemaConstant; -import com.salesmanager.core.model.catalog.category.Category; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.ProductDimensions; import com.salesmanager.core.model.catalog.product.price.ProductPrice; @@ -93,7 +92,7 @@ public class ProductAvailability extends SalesManagerEntity<Long, ProductAvailab private String owner; @Column(name = "STATUS") - private boolean productStatus = true; + private boolean productStatus = true; //can be used as flag for instance can be purchase or not @Column(name = "FREE_SHIPPING") private boolean productIsAlwaysFreeShipping;
sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/image/ProductImage.java+12 −0 modified@@ -62,6 +62,10 @@ public class ProductImage extends SalesManagerEntity<Long, ProductImage> { @JoinColumn(name = "PRODUCT_ID", nullable = false) private Product product; + @Column(name = "SORT_ORDER") + private Integer sortOrder = new Integer(0); + + @Transient private InputStream image = null; @@ -85,6 +89,14 @@ public boolean isDefaultImage() { public void setDefaultImage(boolean defaultImage) { this.defaultImage = defaultImage; } + + public Integer getSortOrder() { + return sortOrder; + } + + public void setSortOrder(Integer sortOrder) { + this.sortOrder = sortOrder; + } public int getImageType() { return imageType;
sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/price/FinalPrice.java+9 −0 modified@@ -22,6 +22,7 @@ public class FinalPrice implements Serializable { private BigDecimal finalPrice = null;//final price discount or not private boolean discounted = false; private int discountPercent = 0; + private String stringPrice; private Date discountEndDate = null; @@ -104,4 +105,12 @@ public ProductPrice getProductPrice() { return productPrice; } + public String getStringPrice() { + return stringPrice; + } + + public void setStringPrice(String stringPrice) { + this.stringPrice = stringPrice; + } + }
sm-core/src/main/java/com/salesmanager/core/business/modules/cms/product/ProductFileManagerImpl.java+12 −8 modified@@ -108,8 +108,8 @@ public void addProductImage(ProductImage productImage, ImageContentFile contentI * largeContentImage.setDefaultImage(productImage.isDefaultImage()); * largeContentImage.setImageName(new * StringBuilder().append("L-").append(productImage.getProductImage()).toString()); - * - * + * + * * uploadImage.uploadProductImage(configuration, productImage, largeContentImage); */ @@ -120,7 +120,7 @@ public void addProductImage(ProductImage productImage, ImageContentFile contentI * smallContentImage.setDefaultImage(productImage.isDefaultImage()); * smallContentImage.setImageName(new * StringBuilder().append("S-").append(productImage.getProductImage()).toString()); - * + * * uploadImage.uploadProductImage(configuration, productImage, smallContentImage); */ @@ -179,8 +179,12 @@ public void addProductImage(ProductImage productImage, ImageContentFile contentI // resize large // ByteArrayOutputStream output = new ByteArrayOutputStream(); - BufferedImage largeResizedImage = - ProductImageSizeUtils.resizeWithRatio(bufferedImage, largeImageWidth, largeImageHeight); + BufferedImage largeResizedImage; + if(bufferedImage.getWidth() > largeImageWidth ||bufferedImage.getHeight() > largeImageHeight) { + largeResizedImage = ProductImageSizeUtils.resizeWithRatio(bufferedImage, largeImageWidth, largeImageHeight); + } else { + largeResizedImage = bufferedImage; + } File tempLarge = @@ -294,12 +298,12 @@ public void removeProductImage(ProductImage productImage) throws ServiceExceptio /* * ProductImage large = new ProductImage(); large.setProduct(productImage.getProduct()); * large.setProductImage("L" + productImage.getProductImage()); - * + * * this.removeImage.removeProductImage(large); - * + * * ProductImage small = new ProductImage(); small.setProduct(productImage.getProduct()); * small.setProductImage("S" + productImage.getProductImage()); - * + * * this.removeImage.removeProductImage(small); */
sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/attribute/ProductAttributeRepository.java+3 −0 modified@@ -24,6 +24,9 @@ public interface ProductAttributeRepository extends JpaRepository<ProductAttribu @Query("select distinct p from ProductAttribute p join fetch p.product pr left join fetch p.productOption po left join fetch p.productOptionValue pov left join fetch po.descriptions pod left join fetch pov.descriptions povd left join fetch po.merchantStore pom where pom.id = ?1 and pr.id = ?2 and povd.language.id = ?3") List<ProductAttribute> findByProductId(Integer storeId, Long productId, Integer languageId); + @Query("select distinct p from ProductAttribute p join fetch p.product pr left join fetch p.productOption po left join fetch p.productOptionValue pov left join fetch po.descriptions pod left join fetch pov.descriptions povd left join fetch po.merchantStore pom where pom.id = ?1") + List<ProductAttribute> findByProductId(Integer storeId, Long productId); + @Query(value="select distinct p from ProductAttribute p join fetch p.product pr left join fetch pr.categories prc left join fetch p.productOption po left join fetch p.productOptionValue pov left join fetch po.descriptions pod left join fetch pov.descriptions povd left join fetch po.merchantStore pom where pom.id = ?1 and prc.id IN (select c.id from Category c where c.lineage like ?2% and povd.language.id = ?3)") List<ProductAttribute> findOptionsByCategoryLineage(Integer storeId, String lineage, Integer languageId); }
sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/attribute/ProductOptionSetRepository.java+6 −1 modified@@ -15,7 +15,12 @@ public interface ProductOptionSetRepository extends JpaRepository<ProductOptionS @Query("select distinct p from ProductOptionSet p join fetch p.store pm left join fetch p.option po left join fetch po.descriptions pod left join fetch p.values pv left join fetch pv.descriptions pvd where pm.id = ?1 and pod.language.id = ?2") List<ProductOptionSet> findByStore(Integer storeId, Integer language); - @Query("select distinct p from ProductOptionSet p join fetch p.store pm left join fetch p.productTypes pt left join fetch p.option po left join fetch po.descriptions pod left join fetch p.values pv left join fetch pv.descriptions pvd where pt.id= ?1 and pm.id = ?2 and pod.language.id = ?3") + @Query("select distinct p from ProductOptionSet p " + + "join fetch p.store pm left join fetch p.productTypes pt " + + "left join fetch p.option po " + + "left join fetch po.descriptions pod " + + "left join fetch p.values pv " + + "left join fetch pv.descriptions pvd where pt.id= ?1 and pm.id = ?2 and pod.language.id = ?3") List<ProductOptionSet> findByProductType(Long typeId, Integer storeId, Integer language); @Query("select p from ProductOptionSet p join fetch p.store pm left join fetch p.option po left join fetch po.descriptions pod left join fetch p.values pv left join fetch pv.descriptions pvd where pm.id = ?1 and p.code = ?2")
sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/attribute/ProductAttributeServiceImpl.java+5 −0 modified@@ -91,4 +91,9 @@ public List<ProductAttribute> getProductAttributesByCategoryLineage(MerchantStor return productAttributeRepository.findOptionsByCategoryLineage(store.getId(), lineage, language.getId()); } +@Override +public List<ProductAttribute> getByProductId(MerchantStore store, Product product) throws ServiceException { + return productAttributeRepository.findByProductId(store.getId(), product.getId()); +} + }
sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/attribute/ProductAttributeService.java+3 −0 modified@@ -23,6 +23,9 @@ List<ProductAttribute> getByOptionValueId(MerchantStore store, List<ProductAttribute> getByProductId(MerchantStore store, Product product, Language language) throws ServiceException; + + List<ProductAttribute> getByProductId(MerchantStore store, Product product) + throws ServiceException; List<ProductAttribute> getByAttributeIds(MerchantStore store, Product product, List<Long> ids) throws ServiceException;
sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/image/ProductImageServiceImpl.java+51 −54 modified@@ -27,75 +27,72 @@ import com.salesmanager.core.model.merchant.MerchantStore; @Service("productImage") -public class ProductImageServiceImpl extends SalesManagerEntityServiceImpl<Long, ProductImage> +public class ProductImageServiceImpl extends SalesManagerEntityServiceImpl<Long, ProductImage> implements ProductImageService { - + private ProductImageRepository productImageRepository; @Inject public ProductImageServiceImpl(ProductImageRepository productImageRepository) { super(productImageRepository); this.productImageRepository = productImageRepository; } - + @Inject private ProductFileManager productFileManager; - - - + + + public ProductImage getById(Long id) { - + return productImageRepository.findOne(id); } - - + + @Override public void addProductImages(Product product, List<ProductImage> productImages) throws ServiceException { - + try { for(ProductImage productImage : productImages) { - + Assert.notNull(productImage.getImage()); - + InputStream inputStream = productImage.getImage(); ImageContentFile cmsContentImage = new ImageContentFile(); cmsContentImage.setFileName( productImage.getProductImage() ); cmsContentImage.setFile( inputStream ); cmsContentImage.setFileContentType(FileContentType.PRODUCT); - - - - addProductImage(product,productImage,cmsContentImage); + + + + addProductImage(product,productImage,cmsContentImage); } - + } catch (Exception e) { throw new ServiceException(e); } } - - + + @Override public void addProductImage(Product product, ProductImage productImage, ImageContentFile inputImage) throws ServiceException { - - - - + productImage.setProduct(product); try { - - Assert.notNull(inputImage.getFile(),"ImageContentFile.file cannot be null"); + if (productImage.getImageType() == 0 ) { + Assert.notNull(inputImage.getFile(), "ImageContentFile.file cannot be null"); + productFileManager.addProductImage(productImage, inputImage); + } - productFileManager.addProductImage(productImage, inputImage); - //insert ProductImage this.saveOrUpdate(productImage); - - + + } catch (Exception e) { throw new ServiceException(e); } finally { @@ -106,71 +103,71 @@ public void addProductImage(Product product, ProductImage productImage, ImageCon } } catch(Exception ignore) { - + } } - - + + } - + @Override public void saveOrUpdate(ProductImage productImage) throws ServiceException { - - + + super.save(productImage); - + } - + public void addProductImageDescription(ProductImage productImage, ProductImageDescription description) throws ServiceException { - + if(productImage.getDescriptions()==null) { productImage.setDescriptions(new ArrayList<ProductImageDescription>()); } - + productImage.getDescriptions().add(description); description.setProductImage(productImage); update(productImage); } - + //TODO get default product image - + @Override public OutputContentFile getProductImage(ProductImage productImage, ProductImageSize size) throws ServiceException { - + ProductImage pi = new ProductImage(); String imageName = productImage.getProductImage(); if(size == ProductImageSize.LARGE) { imageName = "L-" + imageName; } - + if(size == ProductImageSize.SMALL) { imageName = "S-" + imageName; } - + pi.setProductImage(imageName); pi.setProduct(productImage.getProduct()); return productFileManager.getProductImage(pi); - + } - + @Override public OutputContentFile getProductImage(final String storeCode, final String productCode, final String fileName, final ProductImageSize size) throws ServiceException { return productFileManager.getProductImage(storeCode, productCode, fileName, size); - + } - + @Override public List<OutputContentFile> getProductImages(Product product) throws ServiceException { return productFileManager.getImages(product); } - + @Override public void removeProductImage(ProductImage productImage) throws ServiceException { @@ -179,21 +176,21 @@ public void removeProductImage(ProductImage productImage) throws ServiceExceptio } ProductImage p = this.getById(productImage.getId()); this.delete(p); - + } @Override public Optional<ProductImage> getProductImage(Long imageId, Long productId, MerchantStore store) { - - + + Optional<ProductImage> image = Optional.empty(); - + ProductImage img = productImageRepository.finById(imageId, productId, store.getCode()); if(img!=null) { image = Optional.of(img); } - + return image; } }
sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductServiceImpl.java+0 −4 modified@@ -128,10 +128,6 @@ public List<Product> getProductsByIds(List<Long> productIds) throws ServiceExcep return productRepository.getProductsListByIds(idSet); } - public Product getById(Long productId) { - return productRepository.getById(productId); - } - @Override public Product getProductWithOnlyMerchantStoreById(Long productId) { return productRepository.getProductWithOnlyMerchantStoreById(productId);
sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityServiceImpl.java+4 −0 modified@@ -44,6 +44,10 @@ public void save(E entity) throws ServiceException { repository.saveAndFlush(entity); } + public void saveAll(Iterable<E> entities) throws ServiceException { + repository.saveAll(entities); + } + public void create(E entity) throws ServiceException { save(entity);
sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityService.java+5 −0 modified@@ -21,6 +21,11 @@ public interface SalesManagerEntityService<K extends Serializable & Comparable<K */ void save(E entity) throws ServiceException; + /** + * Save all + */ + void saveAll(Iterable<E> entities) throws ServiceException; + /** * Met à jour l'entité dans la base de données. *
sm-core/src/main/java/com/salesmanager/core/business/services/merchant/MerchantStoreServiceImpl.java+5 −2 modified@@ -42,13 +42,16 @@ public MerchantStoreServiceImpl(MerchantRepository merchantRepository) { } @Override - @CacheEvict(value="store", key="#store.code") + //@CacheEvict(value="store", key="#store.code") public void saveOrUpdate(MerchantStore store) throws ServiceException { super.save(store); } @Override - @Cacheable(value = "store") + /** + * cache moved in facades + */ + //@Cacheable(value = "store") public MerchantStore getByCode(String code) throws ServiceException { return merchantRepository.findByCode(code); }
sm-core/src/main/java/com/salesmanager/core/business/services/order/OrderServiceImpl.java+59 −59 modified@@ -76,25 +76,25 @@ public class OrderServiceImpl extends SalesManagerEntityServiceImpl<Long, Order @Inject private ShippingService shippingService; - + @Inject private PaymentService paymentService; - + @Inject private ProductService productService; @Inject private TaxService taxService; - + @Inject private CustomerService customerService; - + @Inject private ShoppingCartService shoppingCartService; - + @Inject private TransactionService transactionService; - + @Inject private OrderTotalService orderTotalService; @@ -112,29 +112,29 @@ public void addOrderStatusHistory(Order order, OrderStatusHistory history) throw history.setOrder(order); update(order); } - + @Override public Order processOrder(Order order, Customer customer, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, MerchantStore store) throws ServiceException { - + return process(order, customer, items, summary, payment, null, store); } - + @Override public Order processOrder(Order order, Customer customer, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, Transaction transaction, MerchantStore store) throws ServiceException { - + return process(order, customer, items, summary, payment, transaction, store); } - + private Order process(Order order, Customer customer, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, Transaction transaction, MerchantStore store) throws ServiceException { - - + + Validate.notNull(order, "Order cannot be null"); Validate.notNull(customer, "Customer cannot be null (even if anonymous order)"); Validate.notEmpty(items, "ShoppingCart items cannot be null"); Validate.notNull(payment, "Payment cannot be null"); Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(summary, "Order total Summary cannot be null"); - + UserContext context = UserContext.getCurrentInstance(); if(context != null) { String ipAddress = context.getIpAddress(); @@ -143,10 +143,10 @@ private Order process(Order order, Customer customer, List<ShoppingCartItem> ite } } - + //first process payment Transaction processTransaction = paymentService.processPayment(customer, store, payment, items, order); - + if(order.getOrderHistory()==null || order.getOrderHistory().size()==0 || order.getStatus()==null) { OrderStatus status = order.getStatus(); if(status==null) { @@ -160,13 +160,13 @@ private Order process(Order order, Customer customer, List<ShoppingCartItem> ite statusHistory.setOrder(order); statusHistorySet.add(statusHistory); order.setOrderHistory(statusHistorySet); - + } - + if(customer.getId()==null || customer.getId()==0) { customerService.create(customer); } - + order.setCustomerId(customer.getId()); this.create(order); @@ -178,7 +178,7 @@ private Order process(Order order, Customer customer, List<ShoppingCartItem> ite transactionService.update(transaction); } } - + if(processTransaction!=null) { processTransaction.setOrder(order); if(processTransaction.getId()==null || processTransaction.getId()==0) { @@ -195,8 +195,8 @@ private Order process(Order order, Customer customer, List<ShoppingCartItem> ite Set<OrderProduct> products = order.getOrderProducts(); for(OrderProduct orderProduct : products) { orderProduct.getProductQuantity(); - Product p = productService.getByCode(orderProduct.getSku(), store.getDefaultLanguage()); - if(p == null) + Product p = productService.getById(orderProduct.getId()); + if(p == null) throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH); for(ProductAvailability availability : p.getAvailabilities()) { int qty = availability.getProductQuantity(); @@ -211,7 +211,7 @@ private Order process(Order order, Customer customer, List<ShoppingCartItem> ite } - + return order; } @@ -273,28 +273,28 @@ private OrderTotalSummary caculateOrder(OrderSummary summary, Customer customer, } } } - + //only in order page, otherwise invokes too many processing if( OrderSummaryType.ORDERTOTAL.name().equals(summary.getOrderSummaryType().name()) || OrderSummaryType.SHOPPINGCART.name().equals(summary.getOrderSummaryType().name()) - + ) { //Post processing order total variation modules for sub total calculation - drools, custom modules //may affect the sub total OrderTotalVariation orderTotalVariation = orderTotalService.findOrderTotalVariation(summary, customer, store, language); - + int currentCount = 10; - + if(CollectionUtils.isNotEmpty(orderTotalVariation.getVariations())) { for(OrderTotal variation : orderTotalVariation.getVariations()) { variation.setSortOrder(currentCount++); orderTotals.add(variation); subTotal = subTotal.subtract(variation.getValue()); } } - + } @@ -308,7 +308,7 @@ private OrderTotalSummary caculateOrder(OrderSummary summary, Customer customer, orderTotalSubTotal.setTitle(Constants.OT_SUBTOTAL_MODULE_CODE); orderTotalSubTotal.setSortOrder(5); orderTotalSubTotal.setValue(subTotal); - + orderTotals.add(orderTotalSubTotal); @@ -322,7 +322,7 @@ private OrderTotalSummary caculateOrder(OrderSummary summary, Customer customer, shippingSubTotal.setOrderTotalCode("order.total.shipping"); shippingSubTotal.setTitle(Constants.OT_SHIPPING_MODULE_CODE); shippingSubTotal.setSortOrder(100); - + orderTotals.add(shippingSubTotal); if(!summary.getShippingSummary().isFreeShipping()) { @@ -433,7 +433,7 @@ private OrderTotalSummary caculateShoppingCart( ShoppingCart shoppingCart, final OrderSummary orderSummary = new OrderSummary(); orderSummary.setOrderSummaryType(OrderSummaryType.SHOPPINGCART); - + if(!StringUtils.isBlank(shoppingCart.getPromoCode())) { Date promoDateAdded = shoppingCart.getPromoAdded();//promo valid 1 day if(promoDateAdded == null) { @@ -451,14 +451,14 @@ private OrderTotalSummary caculateShoppingCart( ShoppingCart shoppingCart, final shoppingCart.setPromoCode(null); shoppingCartService.saveOrUpdate(shoppingCart); } - } - + } + List<ShoppingCartItem> itemList = new ArrayList<ShoppingCartItem>(shoppingCart.getLineItems()); //filter out unavailable itemList = itemList.stream().filter(p -> p.getProduct().isAvailable()).collect(Collectors.toList()); orderSummary.setProducts(itemList); - - + + return caculateOrder(orderSummary, customer, store, language); } @@ -474,7 +474,7 @@ private OrderTotalSummary caculateShoppingCart( ShoppingCart shoppingCart, final * @param language * @return {@link OrderTotalSummary} * @throws ServiceException - * + * */ @Override public OrderTotalSummary calculateShoppingCartTotal( @@ -504,7 +504,7 @@ public OrderTotalSummary calculateShoppingCartTotal( * @param language * @return {@link OrderTotalSummary} * @throws ServiceException - * + * */ @Override public OrderTotalSummary calculateShoppingCartTotal( @@ -581,45 +581,45 @@ public void saveOrUpdate(final Order order) throws ServiceException { @Override public boolean hasDownloadFiles(Order order) throws ServiceException { - + Validate.notNull(order,"Order cannot be null"); Validate.notNull(order.getOrderProducts(),"Order products cannot be null"); Validate.notEmpty(order.getOrderProducts(),"Order products cannot be empty"); - + boolean hasDownloads = false; for(OrderProduct orderProduct : order.getOrderProducts()) { - + if(CollectionUtils.isNotEmpty(orderProduct.getDownloads())) { hasDownloads = true; break; } } - + return hasDownloads; } @Override public List<Order> getCapturableOrders(MerchantStore store, Date startDate, Date endDate) throws ServiceException { - + List<Transaction> transactions = transactionService.listTransactions(startDate, endDate); - + List<Order> returnOrders = null; if(!CollectionUtils.isEmpty(transactions)) { - + returnOrders = new ArrayList<Order>(); - + //order id Map<Long,Order> preAuthOrders = new HashMap<Long,Order> (); //order id Map<Long,List<Transaction>> processingTransactions = new HashMap<Long,List<Transaction>> (); - + for(Transaction trx : transactions) { Order order = trx.getOrder(); if(TransactionType.AUTHORIZE.name().equals(trx.getTransactionType().name())) { preAuthOrders.put(order.getId(), order); } - + //put transaction List<Transaction> listTransactions = null; if(processingTransactions.containsKey(order.getId())) { @@ -630,46 +630,46 @@ public List<Order> getCapturableOrders(MerchantStore store, Date startDate, Date } listTransactions.add(trx); } - + //should have when captured /** * Order id Transaction type * 1 AUTHORIZE - * 1 CAPTURE + * 1 CAPTURE */ - + //should have when not captured /** * Order id Transaction type * 2 AUTHORIZE */ - + for(Long orderId : processingTransactions.keySet()) { - + List<Transaction> trx = processingTransactions.get(orderId); if(CollectionUtils.isNotEmpty(trx)) { - + boolean capturable = true; for(Transaction t : trx) { - + if(TransactionType.CAPTURE.name().equals(t.getTransactionType().name())) { capturable = false; } else if(TransactionType.AUTHORIZECAPTURE.name().equals(t.getTransactionType().name())) { capturable = false; } else if(TransactionType.REFUND.name().equals(t.getTransactionType().name())) { capturable = false; } - + } - + if(capturable) { Order o = preAuthOrders.get(orderId); returnOrders.add(o); } - + } - - + + } }
sm-core/src/main/java/com/salesmanager/core/business/utils/ProductImageSizeUtils.java+19 −19 modified@@ -12,12 +12,12 @@ * */ public class ProductImageSizeUtils { - + private ProductImageSizeUtils() { } - + /** * Simple resize, does not maintain aspect ratio @@ -26,7 +26,7 @@ private ProductImageSizeUtils() { * @param height * @return */ - + public static BufferedImage resize(BufferedImage image, int width, int height) { int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image .getType(); @@ -43,9 +43,9 @@ public static BufferedImage resize(BufferedImage image, int width, int height) { g.dispose(); return resizedImage; } - + /** - * + * * @param img * @param targetWidth * @param targetHeight @@ -102,8 +102,8 @@ public static BufferedImage resizeWithHint(BufferedImage img, return ret; } - - + + public static BufferedImage resizeWithRatio(BufferedImage image, int destinationWidth, int destinationHeight) { int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType(); @@ -121,17 +121,17 @@ public static BufferedImage resizeWithRatio(BufferedImage image, int destination //Work out the resized width/height if (image.getHeight() > destinationHeight || image.getWidth() > destinationWidth) { - fHeight = destinationHeight; - int wid = destinationWidth; - float sum = (float)image.getWidth() / (float)image.getHeight(); - fWidth = Math.round(fHeight * sum); - - if (fWidth > wid) { - //rezise again for the width this time - fHeight = Math.round(wid/sum); - fWidth = wid; - } - } + if (image.getHeight() > image.getWidth()) { + fHeight = destinationHeight; + float sum = (float) image.getWidth() / (float) image.getHeight(); + fWidth = Math.round(destinationWidth * sum); + } else if (image.getWidth() > image.getHeight()) { + fWidth = destinationWidth; + float sum = (float) image.getHeight() / (float) image.getWidth(); + fHeight = Math.round(destinationHeight * sum); + } + // else sides are equal and is set to destination size at initialization of + } BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type); Graphics2D g = resizedImage.createGraphics(); @@ -146,6 +146,6 @@ public static BufferedImage resizeWithRatio(BufferedImage image, int destination return resizedImage; } - + }
sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java+18 −0 modified@@ -163,6 +163,8 @@ public FinalPrice getFinalPrice(Product product) { finalPrice.setOriginalPrice(op); } } + + finalPrice.setStringPrice(this.getStringAmount(finalPrice.getFinalPrice())); return finalPrice; @@ -199,6 +201,22 @@ public String getAdminFormatedAmount(MerchantStore store, BigDecimal amount) thr return nf.format(amount); } + public String getStringAmount(BigDecimal amount) { + + if(amount==null) { + return ""; + } + + NumberFormat nf = NumberFormat.getInstance(Constants.DEFAULT_LOCALE); + + nf.setMaximumFractionDigits(Integer.parseInt(Character + .toString(DECIMALCOUNT))); + nf.setMinimumFractionDigits(Integer.parseInt(Character + .toString(DECIMALCOUNT))); + + return nf.format(amount); + } + /** * This method has to be used to format store front amounts
sm-shop/files/store/DownlaodRepository.dat+0 −0 modifiedsm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductAttributeEntity.java+7 −0 modified@@ -9,6 +9,7 @@ public class ReadableProductAttributeEntity extends ProductAttributeEntity { private String productAttributeWeight; private String productAttributePrice; + private String productAttributeUnformattedPrice; private ReadableProductOptionEntity option; private ReadableProductOptionValueEntity optionValue; @@ -36,6 +37,12 @@ public ReadableProductOptionValueEntity getOptionValue() { public void setOptionValue(ReadableProductOptionValueEntity optionValue) { this.optionValue = optionValue; } + public String getProductAttributeUnformattedPrice() { + return productAttributeUnformattedPrice; + } + public void setProductAttributeUnformattedPrice(String productAttributeUnformattedPrice) { + this.productAttributeUnformattedPrice = productAttributeUnformattedPrice; + } }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/PersistableProductAttribute.java+12 −10 modified@@ -12,18 +12,14 @@ public class PersistableProductAttribute extends ProductAttributeEntity private BigDecimal productAttributePrice; private Long productId; - private ProductOption option; - private ProductOptionValue optionValue; - public void setOptionValue(ProductOptionValue optionValue) { - this.optionValue = optionValue; - } - public ProductOptionValue getOptionValue() { - return optionValue; - } - public void setOption(ProductOption option) { + private ProductPropertyOption option; + private PersistableProductOptionValue optionValue; + + + public void setOption(ProductPropertyOption option) { this.option = option; } - public ProductOption getOption() { + public ProductPropertyOption getOption() { return option; } @@ -49,5 +45,11 @@ public Long getProductId() { public void setProductId(Long productId) { this.productId = productId; } + public PersistableProductOptionValue getOptionValue() { + return optionValue; + } + public void setOptionValue(PersistableProductOptionValue optionValue) { + this.optionValue = optionValue; + } }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ProductOptionEntity.java+1 −1 modified@@ -2,7 +2,7 @@ import java.io.Serializable; -public class ProductOptionEntity extends ProductOption implements Serializable { +public class ProductOptionEntity extends ProductPropertyOption implements Serializable { /** *
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ProductPropertyOption.java+1 −1 renamed@@ -4,7 +4,7 @@ import com.salesmanager.shop.model.entity.Entity; -public class ProductOption extends Entity implements Serializable { +public class ProductPropertyOption extends Entity implements Serializable { /** *
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java+1 −1 modified@@ -5,7 +5,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; -public class ReadableProductOption extends ProductOption { +public class ReadableProductOption extends ProductPropertyOption { /** *
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOptionValue.java+9 −9 modified@@ -9,17 +9,9 @@ public class ReadableProductOptionValue extends ProductOptionValue { private String price; private String image; - private String name; + private String description; - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public String getPrice() { return price; } @@ -36,4 +28,12 @@ public void setImage(String image) { this.image = image; } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductProperty.java+30 −0 added@@ -0,0 +1,30 @@ +package com.salesmanager.shop.model.catalog.product.attribute; + +public class ReadableProductProperty extends ProductPropertyOption { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Property use option objects + */ + private ReadableProductOption property = null; + private ReadableProductPropertyValue propertyValue = null; + public ReadableProductOption getProperty() { + return property; + } + public void setProperty(ReadableProductOption property) { + this.property = property; + } + public ReadableProductPropertyValue getPropertyValue() { + return propertyValue; + } + public void setPropertyValue(ReadableProductPropertyValue propertyValue) { + this.propertyValue = propertyValue; + } + + + +}
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductPropertyValue.java+25 −0 added@@ -0,0 +1,25 @@ +package com.salesmanager.shop.model.catalog.product.attribute; + +import java.util.ArrayList; +import java.util.List; + +public class ReadableProductPropertyValue extends ProductOptionValue{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + private List<ProductOptionValueDescription> values = new ArrayList<ProductOptionValueDescription>(); + + public List<ProductOptionValueDescription> getValues() { + return values; + } + + public void setValues(List<ProductOptionValueDescription> values) { + this.values = values; + } + + + +}
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/LightPersistableProduct.java+4 −1 modified@@ -10,11 +10,12 @@ public class LightPersistableProduct implements Serializable { /** - * + * */ private static final long serialVersionUID = 1L; private String price; private boolean available; + private boolean productShipeable; private int quantity; public String getPrice() { return price; @@ -35,5 +36,7 @@ public boolean isAvailable() { public void setAvailable(boolean available) { this.available = available; } + public boolean isProductShipeable() { return productShipeable; } + public void setProductShipeable(Boolean productShipeable) { this.productShipeable = productShipeable; } }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/definition/PersistableProductDefinition.java+8 −0 modified@@ -1,5 +1,6 @@ package com.salesmanager.shop.model.catalog.product.product.definition; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -19,6 +20,7 @@ public class PersistableProductDefinition extends ProductDefinition { private List<Category> categories = new ArrayList<Category>(); private String type; private String manufacturer; + private BigDecimal price; public List<ProductDescription> getDescriptions() { return descriptions; } @@ -49,5 +51,11 @@ public String getManufacturer() { public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } + public BigDecimal getPrice() { + return price; + } + public void setPrice(BigDecimal price) { + this.price = price; + } }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/definition/ProductDefinition.java+49 −4 modified@@ -1,5 +1,6 @@ package com.salesmanager.shop.model.catalog.product.product.definition; +import com.salesmanager.shop.model.catalog.product.ProductSpecification; import com.salesmanager.shop.model.entity.Entity; /** @@ -14,17 +15,24 @@ public class ProductDefinition extends Entity { */ private static final long serialVersionUID = 1L; private boolean visible = true; - private Double rating = 0D; - private int ratingCount; + private boolean shipeable = true; + private boolean virtual = true; + private boolean canBePurchased = true; + //private Double rating = 0D; + //private int ratingCount; private String dateAvailable; private String identifier; + private ProductSpecification productSpecifications; + private int sortOrder; + private int quantity; + public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } - public Double getRating() { +/* public Double getRating() { return rating; } public void setRating(Double rating) { @@ -35,7 +43,7 @@ public int getRatingCount() { } public void setRatingCount(int ratingCount) { this.ratingCount = ratingCount; - } + }*/ public String getDateAvailable() { return dateAvailable; } @@ -48,5 +56,42 @@ public String getIdentifier() { public void setIdentifier(String identifier) { this.identifier = identifier; } + public ProductSpecification getProductSpecifications() { + return productSpecifications; + } + public void setProductSpecifications(ProductSpecification productSpecifications) { + this.productSpecifications = productSpecifications; + } + public int getSortOrder() { + return sortOrder; + } + public void setSortOrder(int sortOrder) { + this.sortOrder = sortOrder; + } + public boolean isShipeable() { + return shipeable; + } + public void setShipeable(boolean shipeable) { + this.shipeable = shipeable; + } + public boolean isVirtual() { + return virtual; + } + public void setVirtual(boolean virtual) { + this.virtual = virtual; + } + public int getQuantity() { + return quantity; + } + public void setQuantity(int quantity) { + this.quantity = quantity; + } + public boolean isCanBePurchased() { + return canBePurchased; + } + public void setCanBePurchased(boolean canBePurchased) { + this.canBePurchased = canBePurchased; + } + }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/definition/ReadableProductDefinition.java+7 −0 modified@@ -22,6 +22,7 @@ public class ReadableProductDefinition extends ProductDefinition { private ProductDescription description = null; private List<PersistableProductAttribute> properties = new ArrayList<PersistableProductAttribute>(); private List<ReadableImage> images = new ArrayList<ReadableImage>(); + private String price; public ReadableProductType getType() { @@ -60,6 +61,12 @@ public List<ReadableImage> getImages() { public void setImages(List<ReadableImage> images) { this.images = images; } + public String getPrice() { + return price; + } + public void setPrice(String price) { + this.price = price; + } }
sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/ReadableProduct.java+11 −0 modified@@ -8,6 +8,7 @@ import com.salesmanager.shop.model.catalog.manufacturer.ReadableManufacturer; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductAttribute; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductOption; +import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductProperty; import com.salesmanager.shop.model.catalog.product.type.ReadableProductType; public class ReadableProduct extends ProductEntity implements Serializable { @@ -26,6 +27,7 @@ public class ReadableProduct extends ProductEntity implements Serializable { private ReadableManufacturer manufacturer; private List<ReadableProductAttribute> attributes = new ArrayList<ReadableProductAttribute>(); private List<ReadableProductOption> options = new ArrayList<ReadableProductOption>(); + private List<ReadableProductProperty> properties = new ArrayList<ReadableProductProperty>(); private List<ReadableCategory> categories = new ArrayList<ReadableCategory>(); private ReadableProductType type; private boolean canBePurchased = false; @@ -145,4 +147,13 @@ public void setProductPrice(ReadableProductPrice productPrice) { this.productPrice = productPrice; } + public List<ReadableProductProperty> getProperties() { + return properties; + } + + public void setProperties(List<ReadableProductProperty> properties) { + this.properties = properties; + } + + }
sm-shop-model/src/main/java/com/salesmanager/shop/model/entity/CodeEntity.java+17 −0 added@@ -0,0 +1,17 @@ +package com.salesmanager.shop.model.entity; + +public class CodeEntity extends Entity { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String code; + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + +}
sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionFacade.java+8 −2 modified@@ -1,18 +1,21 @@ package com.salesmanager.shop.store.controller.product.facade; +import java.util.List; + import org.springframework.web.multipart.MultipartFile; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.model.catalog.product.attribute.PersistableProductAttribute; +import com.salesmanager.shop.model.catalog.product.attribute.PersistableProductOptionValue; import com.salesmanager.shop.model.catalog.product.attribute.api.PersistableProductOptionEntity; -import com.salesmanager.shop.model.catalog.product.attribute.api.PersistableProductOptionValueEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeList; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionList; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueList; +import com.salesmanager.shop.model.entity.CodeEntity; /* @@ -26,8 +29,11 @@ public interface ProductOptionFacade { ReadableProductOptionEntity saveOption(PersistableProductOptionEntity option, MerchantStore store, Language language); - ReadableProductOptionValueEntity saveOptionValue(PersistableProductOptionValueEntity optionValue, MerchantStore store, Language language); + ReadableProductOptionValueEntity saveOptionValue(PersistableProductOptionValue optionValue, MerchantStore store, Language language); + List<CodeEntity> createAttributes(List<PersistableProductAttribute> attributes, Long productId, MerchantStore store); + void updateAttributes(List<PersistableProductAttribute> attributes, Long productId, MerchantStore store); + void addOptionValueImage(MultipartFile image, Long optionValueId, MerchantStore store, Language language); void removeOptionValueImage(Long optionValueId, MerchantStore store, Language language);
sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionSetFacade.java+1 −0 modified@@ -13,6 +13,7 @@ public interface ProductOptionSetFacade { ReadableProductOptionSet get(Long id, MerchantStore store, Language language); boolean exists(String code, MerchantStore store); List<ReadableProductOptionSet> list(MerchantStore store, Language language); + List<ReadableProductOptionSet> list(MerchantStore store, Language language, String type); void create(PersistableProductOptionSet optionSet, MerchantStore store, Language language); void update(Long id, PersistableProductOptionSet optionSet, MerchantStore store, Language language); void delete(Long id, MerchantStore store);
sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductTypeFacade.java+2 −0 modified@@ -12,6 +12,8 @@ public interface ProductTypeFacade { ReadableProductType get(MerchantStore store, Long id, Language language); + ReadableProductType get(MerchantStore store, String code, Language language); + Long save(PersistableProductType type, MerchantStore store, Language language); void update(PersistableProductType type, Long id, MerchantStore store, Language language);
sm-shop/pom.xml+0 −11 modified@@ -23,25 +23,21 @@ <dependencies> - <!-- sm-core --> <dependency> <groupId>com.shopizer</groupId> <artifactId>sm-core</artifactId> </dependency> - <!-- sm-core-model --> <dependency> <groupId>com.shopizer</groupId> <artifactId>sm-core-model</artifactId> </dependency> - <!-- sm-shop-model --> <dependency> <groupId>com.shopizer</groupId> <artifactId>sm-shop-model</artifactId> </dependency> - <!-- sm-search --> <dependency> <groupId>com.shopizer</groupId> <artifactId>sm-search</artifactId> @@ -87,13 +83,6 @@ <scope>provided</scope> </dependency> - <!-- - <dependency> - <groupId>org.springframework.security</groupId> - <artifactId>spring-security-taglibs</artifactId> - </dependency> - --> - <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections --> <!-- For Tiles --> <dependency>
sm-shop/SALESMANAGER.h2.db+0 −0 modifiedsm-shop/SALESMANAGER.trace.db+0 −193 removed@@ -1,193 +0,0 @@ -2020-03-13 11:47:54 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Schema "SALESMANAHER" not found; SQL statement: -select * from SALESMANAHER.CETAGORIES [90079-191] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.getSchema(Parser.java:666) - at org.h2.command.Parser.getSchema(Parser.java:673) - at org.h2.command.Parser.readTableFilter(Parser.java:1203) - at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1884) - at org.h2.command.Parser.parseSelectSimple(Parser.java:2032) - at org.h2.command.Parser.parseSelectSub(Parser.java:1878) - at org.h2.command.Parser.parseSelectUnion(Parser.java:1699) - at org.h2.command.Parser.parseSelect(Parser.java:1687) - at org.h2.command.Parser.parsePrepared(Parser.java:443) - at org.h2.command.Parser.parse(Parser.java:315) - at org.h2.command.Parser.parse(Parser.java:287) - at org.h2.command.Parser.prepareCommand(Parser.java:252) - at org.h2.engine.Session.prepareLocal(Session.java:560) - at org.h2.engine.Session.prepareCommand(Session.java:501) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170) - at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158) - at net.sourceforge.squirrel_sql.client.session.StatementWrapper.execute(StatementWrapper.java:165) - at net.sourceforge.squirrel_sql.client.session.SQLExecuterTask.processQuery(SQLExecuterTask.java:369) - at net.sourceforge.squirrel_sql.client.session.SQLExecuterTask.run(SQLExecuterTask.java:212) - at net.sourceforge.squirrel_sql.fw.util.TaskExecuter.run(TaskExecuter.java:82) - at java.lang.Thread.run(Thread.java:745) -2020-03-13 11:48:06 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Table "CETAGORIES" not found; SQL statement: -select * from SALESMANAGER.CETAGORIES [42102-191] -2020-03-13 11:48:15 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Table "CETEGORIES" not found; SQL statement: -select * from SALESMANAGER.CETEGORIES [42102-191] -2020-03-13 11:48:24 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Table "CATEGORIES" not found; SQL statement: -select * from SALESMANAGER.CATEGORIES [42102-191] -2020-03-13 11:48:25 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Table "CATEGORIES" not found; SQL statement: -select * from SALESMANAGER.CATEGORIES [42102-191] -2020-03-13 11:49:49 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Column "/1" not found; SQL statement: -update SALESMANAGER.CATEGORY set LINEAGE = "/1" where CATEGORY_ID = 1 [42122-191] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:147) - at org.h2.command.dml.Update.prepare(Update.java:192) - at org.h2.command.Parser.prepareCommand(Parser.java:257) - at org.h2.engine.Session.prepareLocal(Session.java:560) - at org.h2.engine.Session.prepareCommand(Session.java:501) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170) - at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158) - at net.sourceforge.squirrel_sql.client.session.StatementWrapper.execute(StatementWrapper.java:165) - at net.sourceforge.squirrel_sql.client.session.SQLExecuterTask.processQuery(SQLExecuterTask.java:369) - at net.sourceforge.squirrel_sql.client.session.SQLExecuterTask.run(SQLExecuterTask.java:212) - at net.sourceforge.squirrel_sql.fw.util.TaskExecuter.run(TaskExecuter.java:82) - at java.lang.Thread.run(Thread.java:745) -2020-10-30 11:55:15 jdbc[3]: exception -org.h2.jdbc.JdbcSQLFeatureNotSupportedException: Feature not supported: "getFunctions" [50100-200] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:507) - at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) - at org.h2.message.DbException.get(DbException.java:205) - at org.h2.message.DbException.get(DbException.java:181) - at org.h2.message.DbException.getUnsupportedException(DbException.java:269) - at org.h2.message.TraceObject.unsupported(TraceObject.java:398) - at org.h2.jdbc.JdbcDatabaseMetaData.getFunctions(JdbcDatabaseMetaData.java:3273) - at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCDatabaseMetaDataImpl.getFunctions(JDBCDatabaseMetaDataImpl.java:229) - at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.loadProcedures(GenericMetaModel.java:279) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.loadProcedures(GenericObjectContainer.java:413) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProcedures(GenericObjectContainer.java:287) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProceduresOnly(GenericObjectContainer.java:313) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProceduresOnly(GenericObjectContainer.java:1) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.base/java.lang.reflect.Method.invoke(Method.java:566) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.extractPropertyValue(DBNDatabaseNode.java:824) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.access$1(DBNDatabaseNode.java:805) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:885) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.model.DBUtils.tryExecuteRecover(DBUtils.java:1679) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadTreeItems(DBNDatabaseNode.java:498) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:421) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.getChildren(DBNDatabaseNode.java:206) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.getChildren(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.ui.navigator.NavigatorUtils.getNodeChildrenFiltered(NavigatorUtils.java:593) - at org.jkiss.dbeaver.ui.controls.itemlist.ItemListControl$ItemLoadService.evaluate(ItemListControl.java:219) - at org.jkiss.dbeaver.ui.controls.itemlist.ItemListControl$ItemLoadService.evaluate(ItemListControl.java:1) - at org.jkiss.dbeaver.ui.LoadingJob.run(LoadingJob.java:86) - at org.jkiss.dbeaver.ui.LoadingJob.run(LoadingJob.java:71) - at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:102) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) -2020-10-30 11:55:15 jdbc[3]: exception -org.h2.jdbc.JdbcSQLFeatureNotSupportedException: Feature not supported: "getFunctions" [50100-200] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:507) - at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) - at org.h2.message.DbException.get(DbException.java:205) - at org.h2.message.DbException.get(DbException.java:181) - at org.h2.message.DbException.getUnsupportedException(DbException.java:269) - at org.h2.message.TraceObject.unsupported(TraceObject.java:398) - at org.h2.jdbc.JdbcDatabaseMetaData.getFunctions(JdbcDatabaseMetaData.java:3273) - at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCDatabaseMetaDataImpl.getFunctions(JDBCDatabaseMetaDataImpl.java:229) - at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.loadProcedures(GenericMetaModel.java:279) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.loadProcedures(GenericObjectContainer.java:413) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getPackages(GenericObjectContainer.java:267) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.base/java.lang.reflect.Method.invoke(Method.java:566) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.extractPropertyValue(DBNDatabaseNode.java:824) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.access$1(DBNDatabaseNode.java:805) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:885) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.model.DBUtils.tryExecuteRecover(DBUtils.java:1679) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadTreeItems(DBNDatabaseNode.java:498) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:421) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.getChildren(DBNDatabaseNode.java:206) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.getChildren(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.ui.navigator.NavigatorUtils.getNodeChildrenFiltered(NavigatorUtils.java:593) - at org.jkiss.dbeaver.ui.controls.itemlist.ItemListControl$ItemLoadService.evaluate(ItemListControl.java:219) - at org.jkiss.dbeaver.ui.controls.itemlist.ItemListControl$ItemLoadService.evaluate(ItemListControl.java:1) - at org.jkiss.dbeaver.ui.LoadingJob.run(LoadingJob.java:86) - at org.jkiss.dbeaver.ui.LoadingJob.run(LoadingJob.java:71) - at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:102) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) -2020-10-30 12:25:27 jdbc[3]: exception -org.h2.jdbc.JdbcSQLFeatureNotSupportedException: Feature not supported: "getFunctions" [50100-200] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:507) - at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) - at org.h2.message.DbException.get(DbException.java:205) - at org.h2.message.DbException.get(DbException.java:181) - at org.h2.message.DbException.getUnsupportedException(DbException.java:269) - at org.h2.message.TraceObject.unsupported(TraceObject.java:398) - at org.h2.jdbc.JdbcDatabaseMetaData.getFunctions(JdbcDatabaseMetaData.java:3273) - at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCDatabaseMetaDataImpl.getFunctions(JDBCDatabaseMetaDataImpl.java:229) - at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.loadProcedures(GenericMetaModel.java:279) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.loadProcedures(GenericObjectContainer.java:413) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProcedures(GenericObjectContainer.java:287) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProceduresOnly(GenericObjectContainer.java:313) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getProceduresOnly(GenericObjectContainer.java:1) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.base/java.lang.reflect.Method.invoke(Method.java:566) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.extractPropertyValue(DBNDatabaseNode.java:824) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.access$1(DBNDatabaseNode.java:805) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:885) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.model.DBUtils.tryExecuteRecover(DBUtils.java:1679) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadTreeItems(DBNDatabaseNode.java:498) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:421) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.reloadChildren(DBNDatabaseNode.java:709) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:435) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.reloadChildren(DBNDatabaseNode.java:709) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.refreshNodeContent(DBNDatabaseNode.java:367) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.refreshNode(DBNDatabaseNode.java:341) - at org.jkiss.dbeaver.ui.navigator.actions.NavigatorHandlerRefresh$1.run(NavigatorHandlerRefresh.java:154) - at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:102) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) -2020-10-30 12:25:27 jdbc[3]: exception -org.h2.jdbc.JdbcSQLFeatureNotSupportedException: Feature not supported: "getFunctions" [50100-200] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:507) - at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) - at org.h2.message.DbException.get(DbException.java:205) - at org.h2.message.DbException.get(DbException.java:181) - at org.h2.message.DbException.getUnsupportedException(DbException.java:269) - at org.h2.message.TraceObject.unsupported(TraceObject.java:398) - at org.h2.jdbc.JdbcDatabaseMetaData.getFunctions(JdbcDatabaseMetaData.java:3273) - at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCDatabaseMetaDataImpl.getFunctions(JDBCDatabaseMetaDataImpl.java:229) - at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.loadProcedures(GenericMetaModel.java:279) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.loadProcedures(GenericObjectContainer.java:413) - at org.jkiss.dbeaver.ext.generic.model.GenericObjectContainer.getPackages(GenericObjectContainer.java:267) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.base/java.lang.reflect.Method.invoke(Method.java:566) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.extractPropertyValue(DBNDatabaseNode.java:824) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.access$1(DBNDatabaseNode.java:805) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:885) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode$PropertyValueReader.run(DBNDatabaseNode.java:1) - at org.jkiss.dbeaver.model.DBUtils.tryExecuteRecover(DBUtils.java:1679) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadTreeItems(DBNDatabaseNode.java:498) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:421) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.reloadChildren(DBNDatabaseNode.java:709) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.loadChildren(DBNDatabaseNode.java:435) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.reloadChildren(DBNDatabaseNode.java:709) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.refreshNodeContent(DBNDatabaseNode.java:367) - at org.jkiss.dbeaver.model.navigator.DBNDatabaseNode.refreshNode(DBNDatabaseNode.java:341) - at org.jkiss.dbeaver.ui.navigator.actions.NavigatorHandlerRefresh$1.run(NavigatorHandlerRefresh.java:154) - at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:102) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/AdminController.java+0 −77 removed@@ -1,77 +0,0 @@ -package com.salesmanager.shop.admin.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.user.UserService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.user.User; -import com.salesmanager.shop.constants.Constants; - - - -@Controller -public class AdminController { - - @Inject - CountryService countryService; - - @Inject - UserService userService; - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value={"/admin/home.html","/admin/"}, method=RequestMethod.GET) - public String displayDashboard(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - Language language = (Language)request.getAttribute("LANGUAGE"); - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("home", "home"); - - model.addAttribute("activeMenus",activeMenus); - - - //get store information - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Map<String,Country> countries = countryService.getCountriesMap(language); - - Country storeCountry = store.getCountry(); - Country country = countries.get(storeCountry.getIsoCode()); - - String sCurrentUser = request.getRemoteUser(); - User currentUser = userService.getByUserName(sCurrentUser); - - model.addAttribute("store", store); - model.addAttribute("country", country); - model.addAttribute("user", currentUser); - //get last 10 orders - //OrderCriteria orderCriteria = new OrderCriteria(); - //orderCriteria.setMaxCount(10); - //orderCriteria.setOrderBy(CriteriaOrderBy.DESC); - - return ControllerConstants.Tiles.adminDashboard; - } - - @RequestMapping( value=Constants.ADMIN_URI , method=RequestMethod.GET) - public String displayStoreLanding(HttpServletRequest request, HttpServletResponse response) { - - return "redirect:" + Constants.ADMIN_URI + Constants.SLASH; - } - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/categories/CategoryController.java+0 −376 removed@@ -1,376 +0,0 @@ -package com.salesmanager.shop.admin.controller.categories; - -import java.util.*; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.category.CategoryDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import com.salesmanager.shop.utils.LabelUtils; - - - -@Controller -public class CategoryController { - - private static final Logger LOGGER = LoggerFactory.getLogger(CategoryController.class); - - @Inject - LanguageService languageService; - - @Inject - CategoryService categoryService; - - @Inject - CountryService countryService; - - @Inject - LabelUtils messages; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/editCategory.html", method=RequestMethod.GET) - public String displayCategoryEdit(@RequestParam("id") long categoryId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayCategory(categoryId,model,request); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/createCategory.html", method=RequestMethod.GET) - public String displayCategoryCreate(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayCategory(null,model,request); - - } - private String displayCategory(Long categoryId, Model model, HttpServletRequest request) throws Exception { - //display menu - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - //get parent categories - List<Category> categories = categoryService.listByStore(store,language); - List<Language> languages = store.getLanguages(); - Optional<Category> category; - if(categoryId!=null && categoryId!=0) {//edit mode - category = Optional.ofNullable(categoryService.getById(categoryId, store.getId())); - if(!category.isPresent() || category.get().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "catalogue-categories"; - } - } else { - category = Optional.of(new Category()); - category.get().setVisible(true); - } - com.salesmanager.shop.admin.model.catalog.Category adminCategory = new com.salesmanager.shop.admin.model.catalog.Category(); - List<CategoryDescription> descriptions = new LinkedList<>(); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - for(Language l : languages) { - CategoryDescription description = null; - for(CategoryDescription desc : category.get().getDescriptions()) { - if(desc.getLanguage().getCode().equals(l.getCode())) { - description = desc; - } - } - if(description==null) { - description = new CategoryDescription(); - description.setLanguage(l); - } - descriptions.add(description); - } - - adminCategory.setDescriptions(descriptions); - adminCategory.setCategory(category.get()); - - model.addAttribute("category", adminCategory); - model.addAttribute("categories", readableCategories); - - return "catalogue-categories-category"; - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/save.html", method=RequestMethod.POST) - public String saveCategory(@Valid @ModelAttribute("category") com.salesmanager.shop.admin.model.catalog.Category category, BindingResult result, Model model, HttpServletRequest request) throws Exception { - - model.addAttribute("category",category); - Language language = (Language)request.getAttribute("LANGUAGE"); - //display menu - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - if(category.getCategory().getId() != null && category.getCategory().getId() >0) { //edit entry - //get from DB - Optional<Category> currentCategory = Optional.ofNullable(categoryService.getById(category.getCategory().getId(), store.getId())); - - if(!currentCategory.isPresent() || currentCategory.get().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "catalogue-categories"; - } - } - Map<String,Language> langs = languageService.getLanguagesMap(); - List<CategoryDescription> descriptions = category.getDescriptions(); - if(descriptions!=null) { - Set<CategoryDescription> categoryDescriptions = new HashSet<>(); - for(CategoryDescription description : descriptions) { - - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - description.setLanguage(l); - description.setCategory(category.getCategory()); - categoryDescriptions.add(description); - - } - category.getCategory().setDescriptions(categoryDescriptions); - } - //save to DB - category.getCategory().setMerchantStore(store); - //} - if (result.hasErrors()) { - return "catalogue-categories-category"; - } - //check parent - if(category.getCategory().getParent()!=null) { - if(category.getCategory().getParent().getId()==-1) {//this is a root category - category.getCategory().setParent(null); - category.getCategory().setLineage("/" + category.getCategory().getId() + "/"); - category.getCategory().setDepth(0); - } - } - category.getCategory().getAuditSection().setModifiedBy(request.getRemoteUser()); - categoryService.saveOrUpdate(category.getCategory()); - //ajust lineage and depth - if(category.getCategory().getParent()!=null && category.getCategory().getParent().getId()!=-1) { - Category parent = new Category(); - parent.setId(category.getCategory().getParent().getId()); - parent.setMerchantStore(store); - categoryService.addChild(parent, category.getCategory()); - } - //get parent categories - List<Category> categories = categoryService.listByStore(store,language); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("categories", readableCategories); - model.addAttribute("success","success"); - return "catalogue-categories-category"; - } - - - //category list - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/categories.html", method=RequestMethod.GET) - public String displayCategories(Model model, HttpServletRequest request) throws Exception { - setMenu(model,request); - //does nothing, ajax subsequent request - return "catalogue-categories"; - } - - @SuppressWarnings({ "unchecked"}) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageCategories(HttpServletRequest request) { - String categoryName = request.getParameter("name"); - String categoryCode = request.getParameter("code"); - AjaxResponse resp = new AjaxResponse(); - try { - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - List<Category> categories = null; - if(!StringUtils.isBlank(categoryName)) { - categories = categoryService.getByName(store, categoryName, language); - } else if(!StringUtils.isBlank(categoryCode)) { - categoryService.listByCodes(store, new ArrayList<>(Collections.singletonList(categoryCode)), language); - } else { - categories = categoryService.listByStore(store, language); - } - for(Category category : categories) { - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("categoryId", category.getId()); - CategoryDescription description = category.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - entry.put("code", category.getCode()); - entry.put("visible", category.isVisible()); - resp.addDataEntry(entry); - } - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - } catch (Exception e) { - LOGGER.error("Error while paging categories", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - - return new ResponseEntity<>(returnString, httpHeaders, HttpStatus.OK); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/hierarchy.html", method=RequestMethod.GET) - public String displayCategoryHierarchy(Model model, HttpServletRequest request) throws Exception { - setMenu(model,request); - //get the list of categories - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Category> categories = categoryService.listByStore(store, language); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("categories", readableCategories); - - return "catalogue-categories-hierarchy"; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteCategory(HttpServletRequest request, Locale locale) { - String sid = request.getParameter("categoryId"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - try { - Long id = Long.parseLong(sid); - Optional<Category> category = Optional.ofNullable(categoryService.getById(id, store.getId())); - if(category.isPresent() || category.get().getMerchantStore().getId().intValue() !=store.getId().intValue() ) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } else { - categoryService.delete(category.get()); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - } - } catch (Exception e) { - LOGGER.error("Error while deleting category", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - return new ResponseEntity<>(returnString, httpHeaders, HttpStatus.OK); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/moveCategory.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> moveCategory(HttpServletRequest request, Locale locale) { - String parentid = request.getParameter("parentId"); - String childid = request.getParameter("childId"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - try { - Long parentId = Long.parseLong(parentid); - Long childId = Long.parseLong(childid); - Optional<Category> child = Optional.ofNullable(categoryService.getById(childId, store.getId())); - Optional<Category> parent = Optional.ofNullable(categoryService.getById(parentId, store.getId())); - if(child.isPresent()&& child.get().getParent().getId().equals(parentId)) { - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - //String returnString = resp.toJSONString(); - } - if(parentId!=1) { - if(isValid(store, child, parent)) { - return getResponseAjax(locale, resp, httpHeaders); - } - } - parent.get().getAuditSection().setModifiedBy(request.getRemoteUser()); - categoryService.addChild(parent.get(), child.get()); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while moving category", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<>(returnString, httpHeaders, HttpStatus.OK); - } - - private boolean isValid(MerchantStore store, Optional<Category> child, Optional<Category> parent) { - return !child.isPresent()|| !parent.isPresent()|| !child.get().getMerchantStore().getId().equals(store.getId()) || !parent.get().getMerchantStore().getId().equals(store.getId()); - } - - private ResponseEntity<String> getResponseAjax(Locale locale, AjaxResponse resp, HttpHeaders httpHeaders) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - return getResponseAjax(resp, httpHeaders, AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/categories/checkCategoryCode.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkCategoryCode(HttpServletRequest request) { - String code = request.getParameter("code"); - String id = request.getParameter("id"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON); - if(StringUtils.isBlank(code)) { - return getResponseAjax(resp, httpHeaders, AjaxResponse.CODE_ALREADY_EXIST); - } - try { - Optional<Category> category =Optional.ofNullable(categoryService.getByCode(store, code)); - if(category.isPresent() && StringUtils.isBlank(id)) { - return getResponseAjax(resp, httpHeaders, AjaxResponse.CODE_ALREADY_EXIST); - } - if(category.isPresent() && !StringUtils.isBlank(id)) { - try { - long lid = Long.parseLong(id); - if(category.get().getCode().equals(code) && category.get().getId() ==lid) { - return getResponseAjax(resp, httpHeaders, AjaxResponse.CODE_ALREADY_EXIST); - } - } catch (Exception e) { - return getResponseAjax(resp, httpHeaders, AjaxResponse.CODE_ALREADY_EXIST); - } - } - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - } catch (Exception e) { - LOGGER.error("Error while getting category", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - String returnString = resp.toJSONString(); - return new ResponseEntity<>(returnString, httpHeaders, HttpStatus.OK); - } - - private ResponseEntity<String> getResponseAjax(AjaxResponse resp, HttpHeaders httpHeaders, int codeAlreadyExist) { - resp.setStatus(codeAlreadyExist); - String returnString = resp.toJSONString(); - return new ResponseEntity<>(returnString, httpHeaders, HttpStatus.OK); - } - - private void setMenu(Model model, HttpServletRequest request) { - //display menu - Map<String,String> activeMenus = new HashMap<>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-categories", "catalogue-categories"); - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - Menu currentMenu = menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/configurations/CacheController.java+0 −115 removed@@ -1,115 +0,0 @@ -package com.salesmanager.shop.admin.controller.configurations; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.salesmanager.core.business.utils.CacheUtils; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - - - - -@Controller -public class CacheController { - - private static final Logger LOGGER = LoggerFactory.getLogger(CacheController.class); - - @Inject - private CacheUtils cache; - - - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/cache/cacheManagement.html", method=RequestMethod.GET) - public String displayAccounts(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get cache keys - List<String> cacheKeysList = cache.getCacheKeys(store); - - model.addAttribute("keys", cacheKeysList); - - return ControllerConstants.Tiles.Configuration.cache; - - } - - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/cache/clear.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> clearCache(HttpServletRequest request, HttpServletResponse response) { - String cacheKey = request.getParameter("cacheKey"); - - AjaxResponse resp = new AjaxResponse(); - - try { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - StringBuilder key = new StringBuilder(); - key.append(store.getId()).append("_").append(cacheKey); - - if(cacheKey!=null) { - cache.removeFromCache(key.toString()); - } else { - cache.removeAllFromCache(store); - } - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while updateing groups", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("cache", "cache"); - - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("cache"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/configurations/ConfigurationController.java+0 −234 removed@@ -1,234 +0,0 @@ -package com.salesmanager.shop.admin.controller.configurations; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.salesmanager.core.business.modules.email.EmailConfig; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.services.system.MerchantConfigurationService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.system.MerchantConfiguration; -import com.salesmanager.core.model.system.MerchantConfigurationType; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.ConfigListWrapper; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - - - - -@Controller -public class ConfigurationController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationController.class); - - private static final String P_MASK = "*****"; - - @Inject - private MerchantConfigurationService merchantConfigurationService; - - @Inject - private EmailService emailService; - - @Inject - Environment env; - - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/accounts.html", method=RequestMethod.GET) - public String displayAccountsConfguration(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setConfigurationMenu(model, request); - List<MerchantConfiguration> configs = new ArrayList<MerchantConfiguration>(); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - MerchantConfiguration merchantFBConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_FACEBOOK_PAGE_URL,store); - if(null == merchantFBConfiguration) - { - merchantFBConfiguration = new MerchantConfiguration(); - merchantFBConfiguration.setKey(Constants.KEY_FACEBOOK_PAGE_URL); - merchantFBConfiguration.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - } - configs.add(merchantFBConfiguration); - - MerchantConfiguration merchantGoogleAnalyticsConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_GOOGLE_ANALYTICS_URL,store); - if(null == merchantGoogleAnalyticsConfiguration) - { - merchantGoogleAnalyticsConfiguration = new MerchantConfiguration(); - merchantGoogleAnalyticsConfiguration.setKey(Constants.KEY_GOOGLE_ANALYTICS_URL); - merchantGoogleAnalyticsConfiguration.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - } - configs.add(merchantGoogleAnalyticsConfiguration); - - MerchantConfiguration merchantInstagramConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_INSTAGRAM_URL,store); - if(null == merchantInstagramConfiguration) - { - merchantInstagramConfiguration = new MerchantConfiguration(); - merchantInstagramConfiguration.setKey(Constants.KEY_INSTAGRAM_URL); - merchantInstagramConfiguration.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - } - configs.add(merchantInstagramConfiguration); - - MerchantConfiguration merchantPinterestConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_PINTEREST_PAGE_URL,store); - if(null == merchantPinterestConfiguration) - { - merchantPinterestConfiguration = new MerchantConfiguration(); - merchantPinterestConfiguration.setKey(Constants.KEY_PINTEREST_PAGE_URL); - merchantPinterestConfiguration.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - } - configs.add(merchantPinterestConfiguration); - - /** - MerchantConfiguration merchantGoogleApiConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_GOOGLE_API_KEY,store); - if(null == merchantGoogleApiConfiguration) - { - merchantGoogleApiConfiguration = new MerchantConfiguration(); - merchantGoogleApiConfiguration.setKey(Constants.KEY_GOOGLE_API_KEY); - merchantGoogleApiConfiguration.setMerchantConfigurationType(MerchantConfigurationType.CONFIG); - } - configs.add(merchantGoogleApiConfiguration); - **/ - - MerchantConfiguration twitterConfiguration = merchantConfigurationService.getMerchantConfiguration(Constants.KEY_TWITTER_HANDLE,store); - if(null == twitterConfiguration) - { - twitterConfiguration = new MerchantConfiguration(); - twitterConfiguration.setKey(Constants.KEY_TWITTER_HANDLE); - twitterConfiguration.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - } - configs.add(twitterConfiguration); - - ConfigListWrapper configWrapper = new ConfigListWrapper(); - configWrapper.setMerchantConfigs(configs); - model.addAttribute("configuration",configWrapper); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Configuration.accounts; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/saveConfiguration.html", method=RequestMethod.POST) - public String saveConfigurations(@ModelAttribute("configuration") ConfigListWrapper configWrapper, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception - { - setConfigurationMenu(model, request); - List<MerchantConfiguration> configs = configWrapper.getMerchantConfigs(); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - for(MerchantConfiguration mConfigs : configs) - { - mConfigs.setMerchantStore(store); - if(!StringUtils.isBlank(mConfigs.getValue())) { - mConfigs.setMerchantConfigurationType(MerchantConfigurationType.SOCIAL); - merchantConfigurationService.saveOrUpdate(mConfigs); - } else {//remove if submited blank and exists - MerchantConfiguration config = merchantConfigurationService.getMerchantConfiguration(mConfigs.getKey(), store); - if(config!=null) { - merchantConfigurationService.delete(config); - } - } - } - model.addAttribute("success","success"); - model.addAttribute("configuration",configWrapper); - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Configuration.accounts; - - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/email.html", method=RequestMethod.GET) - public String displayEmailSettings(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - setEmailConfigurationMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - EmailConfig emailConfig = emailService.getEmailConfiguration(store); - if(emailConfig == null){ - emailConfig = new EmailConfig(); - //TODO: Need to check below properties. When there are no record available in MerchantConfguration table with EMAIL_CONFIG key, - // instead of showing blank fields in setup screen, show default configured values from email.properties - emailConfig.setProtocol(env.getProperty("mailSender.protocol")); - emailConfig.setHost(env.getProperty("mailSender.host")); - emailConfig.setPort(env.getProperty("mailSender.port}")); - emailConfig.setUsername(env.getProperty("mailSender.username")); - //emailConfig.setPassword(env.getProperty("mailSender.password")); - emailConfig.setPassword(P_MASK); - emailConfig.setSmtpAuth(Boolean.parseBoolean(env.getProperty("mailSender.mail.smtp.auth"))); - emailConfig.setStarttls(Boolean.parseBoolean(env.getProperty("mail.smtp.starttls.enable"))); - } - - model.addAttribute("configuration", emailConfig); - return ControllerConstants.Tiles.Configuration.email; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/saveEmailConfiguration.html", method=RequestMethod.POST) - public String saveEmailSettings(@ModelAttribute("configuration") EmailConfig config, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - setEmailConfigurationMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - EmailConfig emailConfig = emailService.getEmailConfiguration(store); - if(emailConfig == null){ - emailConfig = new EmailConfig(); - } - - // populte EmailConfig model from UI values - emailConfig.setProtocol(config.getProtocol()); - emailConfig.setHost(config.getHost()); - emailConfig.setPort(config.getPort()); - emailConfig.setUsername(config.getUsername()); - emailConfig.setPassword(emailConfig.getPassword()); - if(!StringUtils.isBlank(config.getPassword())) { - if(!config.getPassword().equals(P_MASK)) { - emailConfig.setPassword(config.getPassword()); - } - } - emailConfig.setSmtpAuth(config.isSmtpAuth()); - emailConfig.setStarttls(config.isStarttls()); - - emailService.saveEmailConfiguration(emailConfig, store); - - model.addAttribute("configuration", emailConfig); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Configuration.email; - } - - private void setConfigurationMenu(Model model, HttpServletRequest request) throws Exception { - - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("configuration", "configuration"); - activeMenus.put("accounts-conf", "accounts-conf"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("configuration"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - } - - private void setEmailConfigurationMenu(Model model, HttpServletRequest request) throws Exception { - - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("configuration", "configuration"); - activeMenus.put("email-conf", "email-conf"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("configuration"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - } -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/configurations/SystemConfigurationController.java+0 −88 removed@@ -1,88 +0,0 @@ -package com.salesmanager.shop.admin.controller.configurations; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.salesmanager.core.business.services.system.MerchantConfigurationService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.system.MerchantConfig; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - - - -@Controller -public class SystemConfigurationController { - - private static final Logger LOGGER = LoggerFactory.getLogger(SystemConfigurationController.class); - - @Inject - private MerchantConfigurationService merchantConfigurationService; - - @Inject - Environment env; - - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/system.html", method=RequestMethod.GET) - public String displaySysyemConfgurations(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - MerchantConfig merchantConfiguration = merchantConfigurationService.getMerchantConfig(store); - - if(merchantConfiguration==null) { - merchantConfiguration = new MerchantConfig(); - } - - model.addAttribute("store", store); - model.addAttribute("configuration",merchantConfiguration); - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Configuration.system; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/configuration/saveSystemConfiguration.html", method=RequestMethod.POST) - public String saveSystemConfigurations(@ModelAttribute("configuration") MerchantConfig merchantConfiguration, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception - { - setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - merchantConfigurationService.saveMerchantConfig(merchantConfiguration, store); - model.addAttribute("success","success"); - model.addAttribute("store", store); - model.addAttribute("configuration",merchantConfiguration); - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Configuration.system; - - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("configuration", "configuration"); - activeMenus.put("system-configurations", "system-configurations"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("configuration"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - } -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/content/ContentBoxesController.java+0 −215 removed@@ -1,215 +0,0 @@ -package com.salesmanager.shop.admin.controller.content; - -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.model.content.Content; -import com.salesmanager.core.model.content.ContentDescription; -import com.salesmanager.core.model.content.ContentType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class ContentBoxesController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ContentBoxesController.class); - - @Inject - private ContentService contentService; - - @Inject - LanguageService languageService; - - @ModelAttribute("boxPositions") - public Set<Map.Entry<String, String>> boxPositions() { - final Map<String, String> map = new HashMap<String, String>(); - - map.put("LEFT", "LEFT"); - map.put("RIGHT", "RIGHT"); - - - return (map.entrySet()); - } - - - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/boxes/list.html", method=RequestMethod.GET) - public String listContentBoxes(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - model.addAttribute("boxes", true); - return ControllerConstants.Tiles.Content.contentPages; - - - } - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/boxes/create.html", method=RequestMethod.GET) - public String createBox(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - model.addAttribute("boxes", true); - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Content content = new Content(); - content.setMerchantStore(store); - content.setContentType(ContentType.BOX); - - - List<Language> languages = store.getLanguages(); - - - for(Language l : languages) { - - ContentDescription description = new ContentDescription(); - description.setLanguage(l); - content.getDescriptions().add(description); - } - - //add positions - List<String> positions = new ArrayList<String>(); - positions.add("LEFT"); - positions.add("RIGHT"); - - model.addAttribute("positions",positions); - model.addAttribute("content",content); - - - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/boxes/details.html", method=RequestMethod.GET) - public String getContentDetails(@RequestParam("id") Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - model.addAttribute("boxes", true); - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Content content = contentService.getById(id); - - - List<String> positions = new ArrayList<String>(); - positions.add("LEFT"); - positions.add("RIGHT"); - - model.addAttribute("positions",positions); - - if(content==null) { - LOGGER.error("Content entity null for id " + id); - return "redirect:/admin/content/boxes/listContent.html"; - } - - if(content.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - LOGGER.error("Content id " + id + " does not belong to merchant " + store.getId()); - return "redirect:/admin/content/boxes/listContent.html"; - } - - if(!content.getContentType().name().equals(ContentType.BOX.name())) { - LOGGER.error("This controller does not handle content type " + content.getContentType().name()); - return "redirect:/admin/content/boxes/listContent.html"; - } - - List<Language> languages = store.getLanguages(); - - List<ContentDescription> descriptions = new ArrayList<ContentDescription>(); - for(Language l : languages) { - for(ContentDescription description : content.getDescriptions()) { - if(description.getLanguage().getCode().equals(l.getCode())) { - descriptions.add(description); - } - } - } - content.setDescriptions(descriptions); - - model.addAttribute("content",content); - - - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - - - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/boxes/save.html", method=RequestMethod.POST) - public String saveContent(@Valid @ModelAttribute Content content, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - model.addAttribute("boxes", true); - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<String> positions = new ArrayList<String>(); - positions.add("LEFT"); - positions.add("RIGHT"); - - model.addAttribute("positions",positions); - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Content.contentPagesDetails; - } - - Map<String,Language> langs = languageService.getLanguagesMap(); - - List<ContentDescription> descriptions = content.getDescriptions(); - for(ContentDescription description : descriptions) { - Language l = langs.get(description.getLanguage().getCode()); - description.setLanguage(l); - description.setContent(content); - } - - content.setContentType(ContentType.BOX); - content.setMerchantStore(store); - contentService.saveOrUpdate(content); - - - model.addAttribute("content",content); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("content", "content"); - activeMenus.put("content-boxes", "content-boxes"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("content"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/content/ContentImageController.java+0 −263 removed@@ -1,263 +0,0 @@ -package com.salesmanager.shop.admin.controller.content; - -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.content.FileContentType; -import com.salesmanager.core.model.content.InputContentFile; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.content.ContentFiles; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.ImageFilePath; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.io.ByteArrayInputStream; -import java.util.*; - -/** - * Manage static content type image - * - Add images - * - Remove images - * @author Carl Samson - * - */ -@Controller -public class ContentImageController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ContentImageController.class); - - @Inject - private ContentService contentService; - - @Inject - @Qualifier("img") - private ImageFilePath imageUtils; - - /** - * Entry point for the file browser used from the javascript - * content editor - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value={"/admin/content/fileBrowser.html"}, method=RequestMethod.GET) - public String displayFileBrowser(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - return ControllerConstants.Tiles.ContentImages.fileBrowser; - - } - - - - /** - * Get images for a given merchant store - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value={"/admin/content/contentImages.html","/admin/content/contentManagement.html"}, method=RequestMethod.GET) - public String getContentImages(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - return ControllerConstants.Tiles.ContentImages.contentImages; - - } - - - @SuppressWarnings({ "unchecked"}) - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/images/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageImages(HttpServletRequest request, HttpServletResponse response) { - AjaxResponse resp = new AjaxResponse(); - - try { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<String> imageNames = contentService.getContentFilesNames(store.getCode(),FileContentType.IMAGE); - - if(imageNames!=null) { - - for(String name : imageNames) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("picture", new StringBuilder().append(request.getContextPath()).append(imageUtils.buildStaticImageUtils(store, name)).toString()); - - entry.put("name", name); - entry.put("id", name); - resp.addDataEntry(entry); - - } - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging content images", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - /** - * Controller methods which allow Admin to add content images to underlying - * Infinispan cache. - * @param model model object - * @param request http request object - * @param response http response object - * @return view allowing user to add content images - * @throws Exception - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/createContentImages.html", method=RequestMethod.GET) - public String displayContentImagesCreate(final Model model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { - - return ControllerConstants.Tiles.ContentImages.addContentImages; - - } - - /** - * Method responsible for adding content images to underlying Infinispan cache. - * It will add given content image(s) for given merchant store in the cache. - * Following steps will be performed in order to add images - * <pre> - * 1. Validate form data - * 2. Get Merchant Store based on merchant Id. - * 3. Call {@link InputContentFile} to add image(s). - * </pre> - * - * @param contentImages - * @param bindingResult - * @param model - * @param request - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/saveContentImages.html", method=RequestMethod.POST) - public String saveContentImages(@ModelAttribute(value="contentFiles") @Valid final ContentFiles contentImages, final BindingResult bindingResult,final Model model, final HttpServletRequest request) throws Exception{ - - this.setMenu(model, request); - if (bindingResult.hasErrors()) { - LOGGER.info( "Found {} Validation errors", bindingResult.getErrorCount()); - return ControllerConstants.Tiles.ContentImages.addContentImages; - - } - final List<InputContentFile> contentImagesList=new ArrayList<InputContentFile>(); - final MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - if(CollectionUtils.isNotEmpty( contentImages.getFile() )){ - LOGGER.info("Saving {} content images for merchant {}",contentImages.getFile().size(),store.getId()); - for(final MultipartFile multipartFile:contentImages.getFile()){ - if(!multipartFile.isEmpty()){ - ByteArrayInputStream inputStream = new ByteArrayInputStream( multipartFile.getBytes() ); - InputContentFile cmsContentImage = new InputContentFile(); - cmsContentImage.setFileName(multipartFile.getOriginalFilename() ); - cmsContentImage.setMimeType( multipartFile.getContentType() ); - cmsContentImage.setFile( inputStream ); - cmsContentImage.setFileContentType(FileContentType.IMAGE); - contentImagesList.add( cmsContentImage); - } - } - - if(CollectionUtils.isNotEmpty( contentImagesList )){ - contentService.addContentFiles( store.getCode(), contentImagesList ); - } - else{ - // show error message on UI - } - } - - return ControllerConstants.Tiles.ContentImages.contentImages; - } - - - /** - * Removes a content image from the CMS - * @param request - * @param response - * @param locale - * @return - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/removeImage.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeImage(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String imageName = request.getParameter("name"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - - contentService.removeFile(store.getCode(), FileContentType.IMAGE, imageName); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("content", "content"); - activeMenus.put("content-images", "content-images"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("content"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/content/ContentPagesController.java+0 −389 removed@@ -1,389 +0,0 @@ -package com.salesmanager.shop.admin.controller.content; - -import com.salesmanager.core.business.services.catalog.product.relationship.ProductRelationshipService; -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationship; -import com.salesmanager.core.model.content.Content; -import com.salesmanager.core.model.content.ContentDescription; -import com.salesmanager.core.model.content.ContentType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class ContentPagesController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ContentPagesController.class); - - @Inject - private ContentService contentService; - - @Inject - LanguageService languageService; - - @Inject - ProductRelationshipService productRelationshipService; - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/pages/list.html", method=RequestMethod.GET) - public String listContentPages(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - return ControllerConstants.Tiles.Content.contentPages; - - - } - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/pages/create.html", method=RequestMethod.GET) - public String createPage(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Content content = new Content(); - content.setMerchantStore(store); - content.setContentType(ContentType.PAGE); - - - List<Language> languages = store.getLanguages(); - - - for(Language l : languages) { - - ContentDescription description = new ContentDescription(); - description.setLanguage(l); - content.getDescriptions().add(description); - } - - List<ProductRelationship> relationships = productRelationshipService.getGroups(store); - if(!CollectionUtils.isEmpty(relationships)) { - model.addAttribute("productGroups", relationships); - } - - - - model.addAttribute("content",content); - - - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/pages/details.html", method=RequestMethod.GET) - public String getContentDetails(@RequestParam("id") Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Content content = contentService.getById(id); - - - - if(content==null) { - LOGGER.error("Content entity null for id " + id); - return "redirect:/admin/content/pages/listContent.html"; - } - - if(content.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - LOGGER.error("Content id " + id + " does not belong to merchant " + store.getId()); - return "redirect:/admin/content/pages/listContent.html"; - } - - if(!content.getContentType().name().equals(ContentType.PAGE.name())) { - LOGGER.error("This controller does not handle content type " + content.getContentType().name()); - return "redirect:/admin/content/pages/listContent.html"; - } - - List<Language> languages = store.getLanguages(); - - List<ContentDescription> descriptions = new ArrayList<ContentDescription>(); - for(Language l : languages) { - for(ContentDescription description : content.getDescriptions()) { - if(description.getLanguage().getCode().equals(l.getCode())) { - descriptions.add(description); - } - } - } - content.setDescriptions(descriptions); - model.addAttribute("content",content); - - List<ProductRelationship> relationships = productRelationshipService.getGroups(store); - if(!CollectionUtils.isEmpty(relationships)) { - model.addAttribute("productGroups", relationships); - } - - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeContent(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String id = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - //get the content first - Long lid = Long.parseLong(id); - - Content dbContent = contentService.getById(lid); - - if(dbContent==null) { - LOGGER.error("Invalid content id ", id); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(dbContent!=null && dbContent.getMerchantStore().getId().intValue()!= store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - contentService.delete(dbContent); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @SuppressWarnings({ "unchecked"}) - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/page.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageStaticContent(@RequestParam("contentType") String contentType, HttpServletRequest request, HttpServletResponse response) { - AjaxResponse resp = new AjaxResponse(); - - try { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - - - - - ContentType cType = ContentType.PAGE; - if(ContentType.BOX.name().equals(contentType)) { - cType = ContentType.BOX; - } - List<Content> contentList = contentService.listByType(cType, store, language); - - if(contentList!=null) { - - for(Content content : contentList) { - - List<ContentDescription> descriptions = content.getDescriptions(); - ContentDescription description = descriptions.get(0); - for(ContentDescription desc : descriptions) { - if(desc.getLanguage().getCode().equals(language.getCode())) { - description = desc; - break; - } - } - - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("id", content.getId()); - entry.put("code", content.getCode()); - entry.put("name", description.getName()); - resp.addDataEntry(entry); - - } - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging content", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/pages/save.html", method=RequestMethod.POST) - public String saveContent(@Valid @ModelAttribute Content content, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Content.contentPagesDetails; - } - - Map<String,Language> langs = languageService.getLanguagesMap(); - - List<ContentDescription> descriptions = content.getDescriptions(); - for(ContentDescription description : descriptions) { - Language l = langs.get(description.getLanguage().getCode()); - description.setLanguage(l); - description.setContent(content); - } - - if(content.getSortOrder()==null) { - content.setSortOrder(0); - } - - content.setContentType(ContentType.PAGE); - content.setMerchantStore(store); - - contentService.saveOrUpdate(content); - - List<ProductRelationship> relationships = productRelationshipService.getGroups(store); - if(!CollectionUtils.isEmpty(relationships)) { - model.addAttribute("productGroups", relationships); - } - - - model.addAttribute("content",content); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Content.contentPagesDetails; - - - } - - /** - * Check if the content code filled in by the - * user is unique - * @param request - * @param response - * @param locale - * @return - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/checkContentCode.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkContentCode(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - String code = request.getParameter("code"); - String id = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - try { - - Content content = contentService.getByCode(code, store); - - - if(!StringUtils.isBlank(id)) { - try { - Long lid = Long.parseLong(id); - - if(content!=null && content.getCode().equals(code) && content.getId().longValue()==lid) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - } catch (Exception e) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - } else { - if(content!=null) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - } - - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while getting content", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("content", "content"); - activeMenus.put("content-pages", "content-pages"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("content"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/content/StaticContentController.java+0 −255 removed@@ -1,255 +0,0 @@ -package com.salesmanager.shop.admin.controller.content; - -import java.io.ByteArrayInputStream; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import javax.inject.Inject; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; - -import com.salesmanager.core.model.content.FileContentType; -import com.salesmanager.core.model.content.InputContentFile; -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.content.ContentFiles; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.ImageFilePath; - - -@Controller -public class StaticContentController { - - private static final Logger LOGGER = LoggerFactory.getLogger(StaticContentController.class); - - @Inject - private ContentService contentService; - - - @Inject - @Qualifier("img") - private ImageFilePath imageUtils; - - - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value={"/admin/content/static/contentFiles.html","/admin/content/static/contentManagement.html"}, method=RequestMethod.GET) - public String getContentImages(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - return ControllerConstants.Tiles.ContentFiles.contentFiles; - - } - - - /** - * Display files in a List grid - * @param request - * @param response - * @return - */ - @SuppressWarnings({ "unchecked"}) - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/static/page.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageStaticContent(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<String> fileNames = contentService.getContentFilesNames(store.getCode(), FileContentType.STATIC_FILE); - -/* Map<String,String> configurations = (Map<String, String>)request.getSession().getAttribute(Constants.STORE_CONFIGURATION); - String scheme = Constants.HTTP_SCHEME; - if(configurations!=null) { - scheme = (String)configurations.get("scheme"); - } - - - StringBuilder storePath = new StringBuilder(); - storePath.append(scheme).append("://") - .append(store.getDomainName()) - .append(request.getContextPath()); -*/ - - if(fileNames!=null) { - - for(String name : fileNames) { - - String mimeType = URLConnection.getFileNameMap().getContentTypeFor(name); - - //StringBuilder filePath = new StringBuilder(); - - //filePath.append(storePath.toString()).append(filePathUtils.buildStaticFilePath(store,name)); - - String filePath = imageUtils.buildStaticContentFilePath(store,name); - - //String filePath = filePathUtils.buildStaticFileAbsolutePath(store, name); - - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("name", name); - entry.put("path", filePath.toString()); - entry.put("mimeType", mimeType); - resp.addDataEntry(entry); - - } - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging content images", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - /** - * Method responsible for adding content files to underlying Infinispan cache. - * It will add given content file(s) for given merchant store in the cache. - * Following steps will be performed in order to add files - * <pre> - * 1. Validate form data - * 2. Get Merchant Store based on merchant Id. - * 3. Call {@link InputContentFile} to add file(s). - * </pre> - * - * @param contentImages - * @param bindingResult - * @param model - * @param request - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/static/saveFiles.html", method=RequestMethod.POST) - public String saveFiles(@ModelAttribute(value="contentFiles") @Valid final ContentFiles contentFiles, final BindingResult bindingResult,final Model model, final HttpServletRequest request) throws Exception{ - - this.setMenu(model, request); - if (bindingResult.hasErrors()) { - LOGGER.info( "Found {} Validation errors", bindingResult.getErrorCount()); - return ControllerConstants.Tiles.ContentFiles.contentFiles; - - } - final List<InputContentFile> contentFilesList=new ArrayList<InputContentFile>(); - final MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - if(CollectionUtils.isNotEmpty( contentFiles.getFile() )){ - LOGGER.info("Saving {} content files for merchant {}",contentFiles.getFile().size(),store.getId()); - for(final MultipartFile multipartFile:contentFiles.getFile()){ - if(!multipartFile.isEmpty()){ - ByteArrayInputStream inputStream = new ByteArrayInputStream( multipartFile.getBytes() ); - InputContentFile cmsContentImage = new InputContentFile(); - cmsContentImage.setFileName(multipartFile.getOriginalFilename() ); - cmsContentImage.setFileContentType( FileContentType.STATIC_FILE ); - cmsContentImage.setFile( inputStream ); - contentFilesList.add( cmsContentImage); - } - } - - if(CollectionUtils.isNotEmpty( contentFilesList )){ - contentService.addContentFiles( store.getCode(), contentFilesList ); - } - else{ - // show error message on UI - } - } - - return ControllerConstants.Tiles.ContentFiles.contentFiles; - } - - - /** - * Removes a static file from the CMS - * @param request - * @param response - * @param locale - * @return - */ - @PreAuthorize("hasRole('CONTENT')") - @RequestMapping(value="/admin/content/static/removeFile.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeFile(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String fileName = request.getParameter("name"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - - contentService.removeFile(store.getCode(), FileContentType.STATIC_FILE, fileName); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("content", "content"); - activeMenus.put("content-files", "content-files"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("content"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/ControllerConstants.java+0 −106 removed@@ -1,106 +0,0 @@ -package com.salesmanager.shop.admin.controller; - -/** - * Interface contain constant for Controller.These constant will be used throughout - * sm-shop to providing constant values to various Controllers being used in the - * application. - * @author Umesh A - * - */ -public interface ControllerConstants -{ - - interface Tiles{ - - final String adminDashboard="admin-dashboard"; - interface ContentImages{ - final String addContentImages="admin-contentImages-add"; - final String contentImages="admin-content-images"; - final String fileBrowser="admin-content-filebrowser"; - - } - - interface ContentFiles{ - final String addContentFiles="admin-content-files-add"; - final String contentFiles="admin-content-files"; - - - } - - interface Content{ - final String contentPages="admin-content-pages"; - final String contentPagesDetails="admin-content-pages-details"; - - } - - interface Customer{ - final String optionsList="admin-customer-options-list"; - final String optionDetails="admin-customer-options-details"; - final String optionsValuesList="admin-customer-options-values-list"; - final String optionsValueDetails="admin-customer-options-values-details"; - final String optionsSet="admin-customer-options-set"; - - } - - interface Product{ - final String productReviews="catalogue-product-reviews"; - final String productPrices="admin-products-prices"; - final String productPrice="admin-products-price"; - final String relatedItems="admin-products-related"; - final String digitalProduct="admin-products-digital"; - final String productImages="admin-products-images"; - final String productImagesUrl="admin-products-images-url"; - final String productKeywords="admin-products-keywords"; - final String customGroups="admin-products-groups"; - final String customGroupsDetails="admin-products-groups-details"; - final String manufacturerList="admin-products-manufacturer"; - final String manufacturerDetails="admin-products-manufacturer-details"; - } - - interface User{ - final String profile="admin-user-profile"; - final String users="admin-users"; - final String password="admin-user-password"; - } - - interface Store{ - final String stores="admin-stores"; - } - - - interface Shipping{ - final String shippingMethod="shipping-method"; - final String shippingMethods="shipping-methods"; - final String shippingOptions="shipping-options"; - final String shippingPackaging="shipping-packaging"; - final String customShippingWeightBased="admin-shipping-custom"; - } - - interface Payment{ - final String paymentMethods="payment-methods"; - final String paymentMethod="payment-method"; - } - - interface Order{ - final String orders="admin-orders"; - final String ordersEdit="admin-orders-edit"; - final String ordersTransactions="admin-orders-transactions"; - } - - interface Configuration{ - final String accounts="config-accounts"; - final String email="config-email"; - final String cache="admin-cache"; - final String system="config-system"; - } - - interface Tax{ - final String taxClasses="tax-classes"; - final String taxClass="tax-class"; - final String taxConfiguration="tax-configuration"; - final String taxRates="tax-rates"; - final String taxRate="tax-rate"; - } - - } -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/customers/CustomerController.java+0 −845 removed@@ -1,845 +0,0 @@ -package com.salesmanager.shop.admin.controller.customers; - -import com.salesmanager.core.business.services.customer.CustomerService; -import com.salesmanager.core.business.services.customer.attribute.CustomerAttributeService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionSetService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionValueService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.customer.Customer; -import com.salesmanager.core.model.customer.CustomerCriteria; -import com.salesmanager.core.model.customer.CustomerList; -import com.salesmanager.core.model.customer.attribute.CustomerAttribute; -import com.salesmanager.core.model.customer.attribute.CustomerOptionSet; -import com.salesmanager.core.model.customer.attribute.CustomerOptionType; -import com.salesmanager.core.model.customer.attribute.CustomerOptionValueDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.reference.zone.Zone; -import com.salesmanager.core.model.user.Group; -import com.salesmanager.core.model.user.GroupType; -import com.salesmanager.shop.admin.model.customer.attribute.CustomerOption; -import com.salesmanager.shop.admin.model.customer.attribute.CustomerOptionValue; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.populator.customer.ReadableCustomerOptionPopulator; -import com.salesmanager.shop.store.controller.customer.facade.CustomerFacade; -import com.salesmanager.shop.utils.EmailUtils; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.LocaleUtils; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; -import java.util.regex.Pattern; - - - -@Controller -public class CustomerController { - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class); - - private static final String CUSTOMER_ID_PARAMETER = "customer"; - - - - @Inject - private LabelUtils messages; - - @Inject - private GroupService groupService; - - @Inject - private CustomerService customerService; - - @Inject - private CustomerOptionService customerOptionService; - - @Inject - private CustomerOptionValueService customerOptionValueService; - - @Inject - private CustomerOptionSetService customerOptionSetService; - - @Inject - private CountryService countryService; - - @Inject - private ZoneService zoneService; - - @Inject - private LanguageService languageService; - - @Inject - private CustomerAttributeService customerAttributeService; - - @Inject - @Named("passwordEncoder") - private PasswordEncoder passwordEncoder; - - @Inject - private EmailService emailService; - - @Inject - private EmailUtils emailUtils; - - @Inject - private CustomerFacade customerFacade; - - - /** - * Customer details - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/customer.html", method=RequestMethod.GET) - public String displayCustomer(Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - //display menu - this.setMenu(model, request); - - //get groups - List<Group> groups = new ArrayList<Group>(); - List<Group> userGroups = groupService.listGroup(GroupType.CUSTOMER); - for(Group group : userGroups) { - groups.add(group); - } - - model.addAttribute("groups",groups); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = languageService.getLanguages(); - - model.addAttribute("languages",languages); - - Customer customer = null; - - //if request.attribute contains id then get this customer from customerService - if(id!=null && id!=0) {//edit mode - - //get from DB - customer = customerService.getById(id); - if(customer==null) { - return "redirect:/admin/customers/list.html"; - } - if(customer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/customers/list.html"; - } - - } else { - customer = new Customer(); - } - //get list of countries (see merchant controller) - Language language = (Language)request.getAttribute("LANGUAGE"); - //get countries - List<Country> countries = countryService.getCountries(language); - - //get list of zones - List<Zone> zones = zoneService.list(); - - this.getCustomerOptions(model, customer, store, language); - - model.addAttribute("zones", zones); - model.addAttribute("countries", countries); - model.addAttribute("customer", customer); - return "admin-customer"; - - } - - private void getCustomerOptions(Model model, Customer customer, MerchantStore store, Language language) throws Exception { - - Map<Long,CustomerOption> options = new HashMap<Long,CustomerOption>(); - //get options - List<CustomerOptionSet> optionSet = customerOptionSetService.listByStore(store, language); - if(!CollectionUtils.isEmpty(optionSet)) { - - - ReadableCustomerOptionPopulator optionPopulator = new ReadableCustomerOptionPopulator(); - - Set<CustomerAttribute> customerAttributes = customer.getAttributes(); - - for(CustomerOptionSet optSet : optionSet) { - - com.salesmanager.core.model.customer.attribute.CustomerOption custOption = optSet.getCustomerOption(); - if(!custOption.isActive()) { - continue; - } - CustomerOption customerOption = options.get(custOption.getId()); - - optionPopulator.setOptionSet(optSet); - - - - if(customerOption==null) { - customerOption = new CustomerOption(); - customerOption.setId(custOption.getId()); - customerOption.setType(custOption.getCustomerOptionType()); - customerOption.setName(custOption.getDescriptionsSettoList().get(0).getName()); - - } - - optionPopulator.populate(custOption, customerOption, store, language); - options.put(customerOption.getId(), customerOption); - - if(!CollectionUtils.isEmpty(customerAttributes)) { - for(CustomerAttribute customerAttribute : customerAttributes) { - if(customerAttribute.getCustomerOption().getId().longValue()==customerOption.getId()){ - CustomerOptionValue selectedValue = new CustomerOptionValue(); - com.salesmanager.core.model.customer.attribute.CustomerOptionValue attributeValue = customerAttribute.getCustomerOptionValue(); - selectedValue.setId(attributeValue.getId()); - CustomerOptionValueDescription optValue = attributeValue.getDescriptionsSettoList().get(0); - selectedValue.setName(optValue.getName()); - customerOption.setDefaultValue(selectedValue); - if(customerOption.getType().equalsIgnoreCase(CustomerOptionType.Text.name())) { - selectedValue.setName(customerAttribute.getTextValue()); - } - } - } - } - } - } - - - model.addAttribute("options", options.values()); - - - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/save.html", method=RequestMethod.POST) - public String saveCustomer(@Valid @ModelAttribute("customer") Customer customer, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception{ - - this.setMenu(model, request); - - String email_regEx = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b"; - Pattern pattern = Pattern.compile(email_regEx); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - List<Language> languages = languageService.getLanguages(); - - model.addAttribute("languages",languages); - - //get groups - List<Group> groups = new ArrayList<Group>(); - List<Group> userGroups = groupService.listGroup(GroupType.CUSTOMER); - for(Group group : userGroups) { - groups.add(group); - } - - model.addAttribute("groups",groups); - - this.getCustomerOptions(model, customer, store, language); - - //get countries - List<Country> countries = countryService.getCountries(language); - - - if(!StringUtils.isBlank(customer.getEmailAddress() ) ){ - java.util.regex.Matcher matcher = pattern.matcher(customer.getEmailAddress()); - - if(!matcher.find()) { - ObjectError error = new ObjectError("customerEmailAddress",messages.getMessage("Email.customer.EmailAddress", locale)); - result.addError(error); - } - }else{ - ObjectError error = new ObjectError("customerEmailAddress",messages.getMessage("NotEmpty.customer.EmailAddress", locale)); - result.addError(error); - } - - - - if( StringUtils.isBlank(customer.getBilling().getFirstName() ) ){ - ObjectError error = new ObjectError("billingFirstName", messages.getMessage("NotEmpty.customer.billingFirstName", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(customer.getBilling().getLastName() ) ){ - ObjectError error = new ObjectError("billingLastName", messages.getMessage("NotEmpty.customer.billingLastName", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(customer.getBilling().getAddress() ) ){ - ObjectError error = new ObjectError("billingAddress", messages.getMessage("NotEmpty.customer.billingStreetAddress", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(customer.getBilling().getCity() ) ){ - ObjectError error = new ObjectError("billingCity",messages.getMessage("NotEmpty.customer.billingCity", locale)); - result.addError(error); - } - - if( customer.getShowBillingStateList().equalsIgnoreCase("yes" ) && customer.getBilling().getZone().getCode() == null ){ - ObjectError error = new ObjectError("billingState",messages.getMessage("NotEmpty.customer.billingState", locale)); - result.addError(error); - - }else if( customer.getShowBillingStateList().equalsIgnoreCase("no" ) && customer.getBilling().getState() == null ){ - ObjectError error = new ObjectError("billingState",messages.getMessage("NotEmpty.customer.billingState", locale)); - result.addError(error); - - } - - if( StringUtils.isBlank(customer.getBilling().getPostalCode() ) ){ - ObjectError error = new ObjectError("billingPostalCode", messages.getMessage("NotEmpty.customer.billingPostCode", locale)); - result.addError(error); - } - - //check if error from the @valid - if (result.hasErrors()) { - model.addAttribute("countries", countries); - return "admin-customer"; - } - - Customer newCustomer = new Customer(); - - if( customer.getId()!=null && customer.getId().longValue()>0 ) { - newCustomer = customerService.getById( customer.getId() ); - - if(newCustomer==null) { - return "redirect:/admin/customers/list.html"; - } - - if(newCustomer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/customers/list.html"; - } - - - - }else{ - // new customer set marchant_Id - MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - newCustomer.setMerchantStore(merchantStore); - } - - List<Group> submitedGroups = customer.getGroups(); - Set<Integer> ids = new HashSet<Integer>(); - for(Group group : submitedGroups) { - ids.add(Integer.parseInt(group.getGroupName())); - } - - List<Group> newGroups = groupService.listGroupByIds(ids); - newCustomer.setGroups(newGroups); - - - newCustomer.setEmailAddress(customer.getEmailAddress() ); - - //get Customer country/zone - Country deliveryCountry = countryService.getByCode( customer.getDelivery().getCountry().getIsoCode()); - Country billingCountry = countryService.getByCode( customer.getBilling().getCountry().getIsoCode()) ; - - Zone deliveryZone = customer.getDelivery().getZone(); - Zone billingZone = customer.getBilling().getZone(); - - - - if ("yes".equalsIgnoreCase(customer.getShowDeliveryStateList())) { - if(customer.getDelivery().getZone()!=null) { - deliveryZone = zoneService.getByCode(customer.getDelivery().getZone().getCode()); - customer.getDelivery().setState( null ); - } - - }else if ("no".equalsIgnoreCase(customer.getShowDeliveryStateList())){ - if(customer.getDelivery().getState()!=null) { - deliveryZone = null ; - customer.getDelivery().setState( customer.getDelivery().getState() ); - } - } - - if ("yes".equalsIgnoreCase(customer.getShowBillingStateList())) { - if(customer.getBilling().getZone()!=null) { - billingZone = zoneService.getByCode(customer.getBilling().getZone().getCode()); - customer.getBilling().setState( null ); - } - - }else if ("no".equalsIgnoreCase(customer.getShowBillingStateList())){ - if(customer.getBilling().getState()!=null) { - billingZone = null ; - customer.getBilling().setState( customer.getBilling().getState() ); - } - } - - - - newCustomer.setDefaultLanguage(customer.getDefaultLanguage() ); - - customer.getDelivery().setZone( deliveryZone); - customer.getDelivery().setCountry(deliveryCountry ); - newCustomer.setDelivery( customer.getDelivery() ); - - customer.getBilling().setZone( billingZone); - customer.getBilling().setCountry(billingCountry ); - newCustomer.setBilling( customer.getBilling() ); - - customerService.saveOrUpdate(newCustomer); - - model.addAttribute("customer", newCustomer); - model.addAttribute("countries", countries); - model.addAttribute("success","success"); - - return "admin-customer"; - - } - - /** - * Deserves shop and admin - * @param request - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value={"/admin/customers/attributes/save.html"}, method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> saveCustomerAttributes(HttpServletRequest request, Locale locale) throws Exception { - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //1=1&2=on&3=eeee&4=on&customer=1 - - @SuppressWarnings("rawtypes") - Enumeration parameterNames = request.getParameterNames(); - - Customer customer = null; - - while(parameterNames.hasMoreElements()) { - - String parameterName = (String)parameterNames.nextElement(); - String parameterValue = request.getParameter(parameterName); - if(CUSTOMER_ID_PARAMETER.equals(parameterName)) { - customer = customerService.getById(new Long(parameterValue)); - break; - } - } - - if(customer==null) { - LOGGER.error("Customer id [customer] is not defined in the parameters"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(customer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - LOGGER.error("Customer id does not belong to current store"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - List<CustomerAttribute> customerAttributes = customerAttributeService.getByCustomer(store, customer); - Map<Long,CustomerAttribute> customerAttributesMap = new HashMap<Long,CustomerAttribute>(); - - for(CustomerAttribute attr : customerAttributes) { - customerAttributesMap.put(attr.getCustomerOption().getId(), attr); - } - - parameterNames = request.getParameterNames(); - - while(parameterNames.hasMoreElements()) { - - String parameterName = (String)parameterNames.nextElement(); - String parameterValue = request.getParameter(parameterName); - try { - - String[] parameterKey = parameterName.split("-"); - com.salesmanager.core.model.customer.attribute.CustomerOption customerOption = null; - com.salesmanager.core.model.customer.attribute.CustomerOptionValue customerOptionValue = null; - - - if(CUSTOMER_ID_PARAMETER.equals(parameterName)) { - continue; - } - - if(parameterKey.length>1) { - //parse key - value - String key = parameterKey[0]; - String value = parameterKey[1]; - //should be on - customerOption = customerOptionService.getById(new Long(key)); - customerOptionValue = customerOptionValueService.getById(new Long(value)); - - - - } else { - customerOption = customerOptionService.getById(new Long(parameterName)); - customerOptionValue = customerOptionValueService.getById(new Long(parameterValue)); - - } - - //get the attribute - //CustomerAttribute attribute = customerAttributeService.getByCustomerOptionId(store, customer.getId(), customerOption.getId()); - CustomerAttribute attribute = customerAttributesMap.get(customerOption.getId()); - if(attribute==null) { - attribute = new CustomerAttribute(); - attribute.setCustomer(customer); - attribute.setCustomerOption(customerOption); - } else { - customerAttributes.remove(attribute); - } - - if(customerOption.getCustomerOptionType().equals(CustomerOptionType.Text.name())) { - if(!StringUtils.isBlank(parameterValue)) { - attribute.setCustomerOptionValue(customerOptionValue); - attribute.setTextValue(parameterValue); - } else { - attribute.setTextValue(null); - } - } else { - attribute.setCustomerOptionValue(customerOptionValue); - } - - - if(attribute.getId()!=null && attribute.getId().longValue()>0) { - if(attribute.getCustomerOptionValue()==null){ - customerAttributeService.delete(attribute); - } else { - customerAttributeService.update(attribute); - } - } else { - customerAttributeService.save(attribute); - } - - - - } catch (Exception e) { - LOGGER.error("Cannot get parameter information " + parameterName,e); - } - - } - - //and now the remaining to be removed - for(CustomerAttribute attr : customerAttributes) { - customerAttributeService.delete(attr); - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - /** - * List of customers - * @param model - * @return - * @throws Exception - */ - @RequestMapping(value="/admin/customers/list.html", method=RequestMethod.GET) - public String displayCustomers(Model model,HttpServletRequest request) throws Exception { - - - this.setMenu(model, request); - - return "admin-customers"; - - - - } - - - - @SuppressWarnings("unchecked") - @RequestMapping(value="/admin/customers/page.html", method=RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageCustomers(HttpServletRequest request,HttpServletResponse response) { - - - AjaxPageableResponse resp = new AjaxPageableResponse(); - - //Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - try { - - - - //Map<String,Country> countriesMap = countryService.getCountriesMap(language); - - - int startRow = Integer.parseInt(request.getParameter("_startRow")); - int endRow = Integer.parseInt(request.getParameter("_endRow")); - String email = request.getParameter("email"); - String name = request.getParameter("name"); - String firstName = request.getParameter("firstName"); - String lastName = request.getParameter("lastName"); - String country = request.getParameter("country"); - - - CustomerCriteria criteria = new CustomerCriteria(); - criteria.setStartIndex(startRow); - criteria.setMaxCount(endRow); - - if(!StringUtils.isBlank(email)) { - criteria.setEmail(email); - } - - if(!StringUtils.isBlank(name)) { - criteria.setName(name); - } - - if(!StringUtils.isBlank(country)) { - criteria.setCountry(country); - } - - if(!StringUtils.isBlank(firstName)) { - criteria.setFirstName(firstName); - } - - if(!StringUtils.isBlank(lastName)) { - criteria.setLastName(lastName); - } - - - CustomerList customerList = customerService.getListByStore(store,criteria); - - if(customerList.getCustomers()!=null) { - - for(Customer customer : customerList.getCustomers()) { - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("id", customer.getId()); - entry.put("firstName", customer.getBilling().getFirstName()); - entry.put("lastName", customer.getBilling().getLastName()); - entry.put("email", customer.getEmailAddress()); - entry.put("country", customer.getBilling().getCountry().getIsoCode()); - resp.addDataEntry(entry); - - } - - } - - } catch (Exception e) { - LOGGER.error("Error while paging orders", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/resetPassword.html", method=RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> resetPassword(HttpServletRequest request,HttpServletResponse response) { - - String customerId = request.getParameter("customerId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - - try { - - Long id = Long.parseLong(customerId); - - Customer customer = customerService.getById(id); - - if(customer==null) { - resp.setErrorString("Customer does not exist"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(customer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setErrorString("Invalid customer id"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Language userLanguage = customer.getDefaultLanguage(); - - customerFacade.resetPassword(customer, store, userLanguage); - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("An exception occured while changing password",e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/setCredentials.html", method=RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> setCredentials(HttpServletRequest request,HttpServletResponse response) { - - String customerId = request.getParameter("customerId"); - String userName = request.getParameter("userName"); - String password = request.getParameter("password"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - - try { - - Long id = Long.parseLong(customerId); - - Customer customer = customerService.getById(id); - - if(customer==null) { - resp.setErrorString("Customer does not exist"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(customer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setErrorString("Invalid customer id"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)) { - resp.setErrorString("Invalid username or password"); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Language userLanguage = customer.getDefaultLanguage(); - - Locale customerLocale = LocaleUtils.getLocale(userLanguage); - - String encodedPassword = passwordEncoder.encode(password); - - customer.setPassword(encodedPassword); - customer.setNick(userName); - - customerService.saveOrUpdate(customer); - - //send email - -/* try { - - //creation of a user, send an email - String[] storeEmail = {store.getStoreEmailAddress()}; - - - Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, customerLocale); - templateTokens.put(EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", customerLocale)); - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, customer.getBilling().getFirstName()); - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_LASTNAME, customer.getBilling().getLastName()); - templateTokens.put(EmailConstants.EMAIL_RESET_PASSWORD_TXT, messages.getMessage("email.customer.resetpassword.text", customerLocale)); - templateTokens.put(EmailConstants.EMAIL_CONTACT_OWNER, messages.getMessage("email.contactowner", storeEmail, customerLocale)); - templateTokens.put(EmailConstants.EMAIL_PASSWORD_LABEL, messages.getMessage("label.generic.password",customerLocale)); - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_PASSWORD, password); - - - Email email = new Email(); - email.setFrom(store.getStorename()); - email.setFromEmail(store.getStoreEmailAddress()); - email.setSubject(messages.getMessage("label.generic.changepassword",customerLocale)); - email.setTo(customer.getEmailAddress()); - email.setTemplateName(RESET_PASSWORD_TPL); - email.setTemplateTokens(templateTokens); - - - - emailService.sendHtmlEmail(store, email); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Cannot send email to user",e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - }*/ - - - - - } catch (Exception e) { - LOGGER.error("An exception occured while changing password",e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("customer", "customer"); - activeMenus.put("customer-list", "customer-list"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("customer"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - - - // - - } - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/customers/CustomerOptionsController.java+0 −337 removed@@ -1,337 +0,0 @@ -package com.salesmanager.shop.admin.controller.customers; - -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.customer.attribute.CustomerOption; -import com.salesmanager.core.model.customer.attribute.CustomerOptionDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class CustomerOptionsController { - - @Inject - private LanguageService languageService; - - @Inject - private CustomerOptionService customerOptionService; - - @Inject - private LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomerOptionsController.class); - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/list.html", method=RequestMethod.GET) - public String displayOptions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - return ControllerConstants.Tiles.Customer.optionsList; - - - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/edit.html", method=RequestMethod.GET) - public String displayOptionEdit(@RequestParam("id") long id, HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(id,request,response,model,locale); - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/create.html", method=RequestMethod.GET) - public String displayOptionCreate(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(null,request,response,model,locale); - } - - private String displayOption(Long optionId, HttpServletRequest request, HttpServletResponse response,Model model,Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = store.getLanguages(); - - Set<CustomerOptionDescription> descriptions = new HashSet<CustomerOptionDescription>(); - - CustomerOption option = new CustomerOption(); - - if(optionId!=null && optionId!=0) {//edit mode - - - option = customerOptionService.getById(optionId); - - - if(option==null) { - return "redirect:/admin/customers/options/list.html"; - } - - if(option.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/customers/options/list.html"; - } - - Set<CustomerOptionDescription> optionDescriptions = option.getDescriptions(); - - - - for(Language l : languages) { - - CustomerOptionDescription optionDescription = null; - - if(optionDescriptions!=null) { - - for(CustomerOptionDescription description : optionDescriptions) { - - String code = description.getLanguage().getCode(); - if(code.equals(l.getCode())) { - optionDescription = description; - } - } - - } - - if(optionDescription==null) { - optionDescription = new CustomerOptionDescription(); - optionDescription.setLanguage(l); - } - descriptions.add(optionDescription); - } - - } else { - for(Language l : languages) { - CustomerOptionDescription desc = new CustomerOptionDescription(); - desc.setLanguage(l); - descriptions.add(desc); - } - } - - - option.setDescriptions(descriptions); - model.addAttribute("option", option); - return ControllerConstants.Tiles.Customer.optionDetails; - - - } - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/save.html", method=RequestMethod.POST) - public String saveOption(@Valid @ModelAttribute("option") CustomerOption option, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomerOption dbEntity = null; - - if(option.getId() != null && option.getId() >0) { //edit entry - - //get from DB - dbEntity = customerOptionService.getById(option.getId()); - - if(dbEntity==null) { - return "redirect:/admin/options/options.html"; - } - } - - //validate if it contains an existing code - CustomerOption byCode = customerOptionService.getByCode(store, option.getCode()); - if(byCode!=null && option.getId()==null) { - ObjectError error = new ObjectError("code",messages.getMessage("message.code.exist", locale)); - result.addError(error); - } - - - Map<String,Language> langs = languageService.getLanguagesMap(); - - - List<CustomerOptionDescription> descriptions = option.getDescriptionsList(); - - if(descriptions!=null) { - - for(CustomerOptionDescription description : descriptions) { - - if(StringUtils.isBlank(description.getName())) { - ObjectError error = new ObjectError("name",messages.getMessage("message.name.required", locale)); - result.addError(error); - } else { - - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - description.setLanguage(l); - description.setCustomerOption(option); - - } - - } - - } - - option.setDescriptions(new HashSet<CustomerOptionDescription>(descriptions)); - option.setMerchantStore(store); - - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Customer.optionDetails; - } - - - - - customerOptionService.saveOrUpdate(option); - - - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Customer.optionDetails; - } - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOptions(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<CustomerOption> options = null; - - - - options = customerOptionService.listByStore(store, language); - - - - - - for(CustomerOption option : options) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("id", option.getId()); - - CustomerOptionDescription description = option.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - entry.put("type", option.getCustomerOptionType()); - entry.put("active", option.isActive()); - entry.put("public", option.isPublicOption()); - resp.addDataEntry(entry); - - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging options", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("customer", "customer"); - activeMenus.put("customer-options", "customer-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("customer"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteOption(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(sid); - - CustomerOption entity = customerOptionService.getById(id); - - if(entity==null || entity.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - customerOptionService.delete(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting option", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/customers/CustomerOptionsSetController.java+0 −368 removed@@ -1,368 +0,0 @@ -package com.salesmanager.shop.admin.controller.customers; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionSetService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionValueService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.customer.attribute.*; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -@Controller -public class CustomerOptionsSetController { - - @Inject - private LanguageService languageService; - - @Inject - private CustomerOptionSetService customerOptionSetService; - - @Inject - private CustomerOptionService customerOptionService; - - @Inject - private CustomerOptionValueService customerOptionValueService; - - @Inject - private LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomerOptionsSetController.class); - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/optionsset/list.html", method=RequestMethod.GET) - public String displayOptions(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - Language language = languageService.toLanguage(locale); - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //get options - List<CustomerOption> options = customerOptionService.listByStore(store, language); - - - //get values - List<CustomerOptionValue> optionsValues = customerOptionValueService.listByStore(store, language); - - - CustomerOptionSet optionSet = new CustomerOptionSet(); - - model.addAttribute("optionSet", optionSet); - model.addAttribute("options", options); - model.addAttribute("optionsValues", optionsValues); - return ControllerConstants.Tiles.Customer.optionsSet; - - - } - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/optionsset/save.html", method=RequestMethod.POST) - public String saveOptionSet(@Valid @ModelAttribute("optionSet") CustomerOptionSet optionSet, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - Language language = languageService.toLanguage(locale); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - /** reference objects **/ - - //get options - List<CustomerOption> options = customerOptionService.listByStore(store, language); - - - //get values - List<CustomerOptionValue> optionsValues = customerOptionValueService.listByStore(store, language); - - - model.addAttribute("options", options); - model.addAttribute("optionsValues", optionsValues); - - if(optionSet.getCustomerOption()==null || optionSet.getCustomerOptionValue()==null) { - model.addAttribute("errorMessageAssociation",messages.getMessage("message.optionset.noassociation", locale)); - ObjectError error = new ObjectError("customerOptionValue.id",messages.getMessage("message.optionset.noassociation", locale)); - result.addError(error); - return ControllerConstants.Tiles.Customer.optionsSet; - } - - //see if association already exist - CustomerOption option = null; - - //get from DB - //option = customerOptionService.getById(optionSet.getPk().getCustomerOption().getId()); - option = customerOptionService.getById(optionSet.getCustomerOption().getId()); - - if(option==null) { - return "redirect:/admin/customers/optionsset/list.html"; - } - - //CustomerOptionValue optionValue = customerOptionValueService.getById(optionSet.getPk().getCustomerOptionValue().getId()); - CustomerOptionValue optionValue = customerOptionValueService.getById(optionSet.getCustomerOptionValue().getId()); - - if(optionValue==null) { - return "redirect:/admin/customers/optionsset/list.html"; - } - - - List<CustomerOptionSet> optionsSet = customerOptionSetService.listByStore(store, language); - - if(optionsSet!=null && optionsSet.size()>0) { - - for(CustomerOptionSet optSet : optionsSet) { - - //CustomerOption opt = optSet.getPk().getCustomerOption(); - CustomerOption opt = optSet.getCustomerOption(); - //CustomerOptionValue optValue = optSet.getPk().getCustomerOptionValue(); - CustomerOptionValue optValue = optSet.getCustomerOptionValue(); - - //if(opt.getId().longValue()==optionSet.getPk().getCustomerOption().getId().longValue() - if(opt.getId().longValue()==optionSet.getCustomerOption().getId().longValue() - //&& optValue.getId().longValue() == optionSet.getPk().getCustomerOptionValue().getId().longValue()) { - && optValue.getId().longValue() == optionSet.getCustomerOptionValue().getId().longValue()) { - model.addAttribute("errorMessageAssociation",messages.getMessage("message.optionset.optionassociationexists", locale)); - ObjectError error = new ObjectError("customerOptionValue.id",messages.getMessage("message.optionset.optionassociationexists", locale)); - result.addError(error); - break; - } - } - } - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Customer.optionsSet; - } - - - //optionSet.getPk().setCustomerOption(option); - optionSet.setCustomerOption(option); - //optionSet.getPk().setCustomerOptionValue(optionValue); - optionSet.setCustomerOptionValue(optionValue); - customerOptionSetService.create(optionSet); - - - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Customer.optionsSet; - } - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/optionsset/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOptionsSet(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - //List<CustomerOption> options = null; - - List<CustomerOptionSet> optionSet = customerOptionSetService.listByStore(store, language); - //for(CustomerOption option : options) { - - - //Set<CustomerOptionSet> optionSet = option.getCustomerOptions(); - - if(optionSet!=null && optionSet.size()>0) { - - for(CustomerOptionSet optSet : optionSet) { - - //CustomerOption customerOption = optSet.getPk().getCustomerOption(); - CustomerOption customerOption = optSet.getCustomerOption(); - //CustomerOptionValue customerOptionValue = optSet.getPk().getCustomerOptionValue(); - CustomerOptionValue customerOptionValue = optSet.getCustomerOptionValue(); - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - - - entry.put("id", optSet.getId()); - - CustomerOptionDescription description = customerOption.getDescriptionsSettoList().get(0); - CustomerOptionValueDescription valueDescription = customerOptionValue.getDescriptionsSettoList().get(0); - - entry.put("optionCode", customerOption.getCode()); - entry.put("optionName", description.getName()); - entry.put("optionValueCode", customerOptionValue.getCode()); - entry.put("optionValueName", valueDescription.getName()); - entry.put("order", customerOptionValue.getSortOrder()); - resp.addDataEntry(entry); - - } - - } - - - //} - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging options", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("customer", "customer"); - activeMenus.put("customer-options", "customer-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("customer"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/optionsset/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteOptionSet(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - - - try { - - - - Long optionSetId = Long.parseLong(sid); - - - CustomerOptionSet entity = customerOptionSetService.getById(optionSetId); - //if(entity==null || entity.getPk().getCustomerOption().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - if(entity==null || entity.getCustomerOption().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - customerOptionSetService.delete(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting option", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/optionsset/update.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> updateOrder(HttpServletRequest request, HttpServletResponse response) { - String values = request.getParameter("_oldValues"); - String order = request.getParameter("order"); - - AjaxResponse resp = new AjaxResponse(); - - try { - - /** - * Values - */ - ObjectMapper mapper = new ObjectMapper(); - @SuppressWarnings("rawtypes") - Map conf = mapper.readValue(values, Map.class); - - String sid = (String)conf.get("id"); - - Long optionId = Long.parseLong(sid); - - CustomerOptionSet entity = customerOptionSetService.getById(optionId); - - - if(entity!=null) { - - entity.setSortOrder(Integer.parseInt(order)); - customerOptionSetService.update(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while paging shipping countries", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/customers/CustomerOptionsValueController.java+0 −345 removed@@ -1,345 +0,0 @@ -package com.salesmanager.shop.admin.controller.customers; - -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionValueService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.customer.attribute.CustomerOptionValue; -import com.salesmanager.core.model.customer.attribute.CustomerOptionValueDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class CustomerOptionsValueController { - - @Inject - LanguageService languageService; - - - @Inject - private CustomerOptionValueService customerOptionValueService; - - @Inject - LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomerOptionsValueController.class); - - /** - * Displays the list of customer options values - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/list.html", method=RequestMethod.GET) - public String displayOptionValues(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - return ControllerConstants.Tiles.Customer.optionsValuesList; - - - - } - - /** - * Display an option value in edit mode - * @param id - * @param request - * @param response - * @param model - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/edit.html", method=RequestMethod.GET) - public String displayOptionValueEdit(@RequestParam("id") long id, HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(id,request,response,model,locale); - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/create.html", method=RequestMethod.GET) - public String displayOptionValueCreate(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(null,request,response,model,locale); - } - - private String displayOption(Long id, HttpServletRequest request, HttpServletResponse response,Model model,Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = store.getLanguages(); - - Set<CustomerOptionValueDescription> descriptions = new HashSet<CustomerOptionValueDescription>(); - CustomerOptionValue option = new CustomerOptionValue(); - - if(id!=null && id!=0) {//edit mode - - - option = customerOptionValueService.getById(id); - - - if(option==null) { - return "redirect:/admin/customers/options/values/list.html"; - } - - if(option.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/customers/options/values/list.html"; - } - - Set<CustomerOptionValueDescription> optionDescriptions = option.getDescriptions(); - - for(Language l : languages) { - - CustomerOptionValueDescription optionDescription = null; - - if(optionDescriptions!=null) { - for(CustomerOptionValueDescription description : optionDescriptions) { - String code = description.getLanguage().getCode(); - if(code.equals(l.getCode())) { - optionDescription = description; - } - } - } - - if(optionDescription==null) { - optionDescription = new CustomerOptionValueDescription(); - optionDescription.setLanguage(l); - } - - descriptions.add(optionDescription); - } - - } else { - - for(Language l : languages) { - CustomerOptionValueDescription desc = new CustomerOptionValueDescription(); - desc.setLanguage(l); - descriptions.add(desc); - } - - option.setDescriptions(descriptions); - } - - - - model.addAttribute("optionValue", option); - return ControllerConstants.Tiles.Customer.optionsValueDetails; - - - } - - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/save.html", method=RequestMethod.POST) - public String saveOption(@Valid @ModelAttribute("optionValue") CustomerOptionValue optionValue, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomerOptionValue dbEntity = null; - - if(optionValue.getId() != null && optionValue.getId() >0) { //edit entry - - //get from DB - dbEntity = customerOptionValueService.getById(optionValue.getId()); - - if(dbEntity==null) { - return "redirect:/admin/customers/options/values/list.html"; - } - - if(dbEntity.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/customers/options/values/list.html"; - } - } - - //validate if it contains an existing code - CustomerOptionValue byCode = customerOptionValueService.getByCode(store, optionValue.getCode()); - if(byCode!=null && optionValue.getId()==null) { - ObjectError error = new ObjectError("code",messages.getMessage("message.code.exist", locale)); - result.addError(error); - } - - - Map<String,Language> langs = languageService.getLanguagesMap(); - - - List<CustomerOptionValueDescription> descriptions = optionValue.getDescriptionsList(); - if(descriptions!=null && descriptions.size()>0) { - - Set<CustomerOptionValueDescription> descs = new HashSet<CustomerOptionValueDescription>(); - optionValue.setDescriptions(descs); - for(CustomerOptionValueDescription description : descriptions) { - - if(StringUtils.isBlank(description.getName())) { - ObjectError error = new ObjectError("name",messages.getMessage("message.name.required", locale)); - result.addError(error); - } else { - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - description.setLanguage(l); - description.setCustomerOptionValue(optionValue); - descs.add(description); - } - } - - } else { - - ObjectError error = new ObjectError("name",messages.getMessage("message.name.required", locale)); - result.addError(error); - - } - - - optionValue.setMerchantStore(store); - - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Customer.optionsValueDetails; - } - - - customerOptionValueService.saveOrUpdate(optionValue); - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Customer.optionsValueDetails; - } - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOptions(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<CustomerOptionValue> options = null; - - - options = customerOptionValueService.listByStore(store, language); - - for(CustomerOptionValue option : options) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("id", option.getId()); - entry.put("code", option.getCode()); - CustomerOptionValueDescription description = option.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - resp.addDataEntry(entry); - - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging options", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('CUSTOMER')") - @RequestMapping(value="/admin/customers/options/values/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteOptionValue(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(sid); - - CustomerOptionValue entity = customerOptionValueService.getById(id); - - if(entity==null || entity.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } else { - customerOptionValueService.delete(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting option", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("customer", "customer"); - activeMenus.put("customer-options", "customer-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("customer"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/merchant/MerchantStoreController.java+0 −487 removed@@ -1,487 +0,0 @@ -package com.salesmanager.shop.admin.controller.merchant; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.salesmanager.core.business.modules.email.Email; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.currency.CurrencyService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.services.user.UserService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.currency.Currency; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.reference.zone.Zone; -import com.salesmanager.core.model.user.User; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.reference.Size; -import com.salesmanager.shop.admin.model.reference.Weight; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.constants.EmailConstants; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.EmailUtils; -import com.salesmanager.shop.utils.FilePathUtils; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.LocaleUtils; -import com.salesmanager.shop.utils.UserUtils; - -@Controller -public class MerchantStoreController { - - private static final Logger LOGGER = LoggerFactory.getLogger(MerchantStoreController.class); - - @Inject - private MerchantStoreService merchantStoreService; - - @Inject - private CountryService countryService; - - @Inject - private ZoneService zoneService; - - @Inject - private LanguageService languageService; - - @Inject - private CurrencyService currencyService; - - @Inject - private UserService userService; - - @Inject - private LabelUtils messages; - - @Inject - private EmailService emailService; - - @Inject - private EmailUtils emailUtils; - - @Inject - private FilePathUtils filePathUtils; - - private final static String NEW_STORE_TMPL = "email_template_new_store.ftl"; - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/store/list.html", method = RequestMethod.GET) - public String displayStores(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) - throws Exception { - - setMenu(model, request); - return ControllerConstants.Tiles.Store.stores; - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/store/paging.html", method = RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageStores(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - try { - - List<MerchantStore> stores = merchantStoreService.findAllStoreCodeNameEmail(); - - for (MerchantStore store : stores) { - - if (!store.getCode().equals(MerchantStore.DEFAULT_STORE)) { - Map<String, String> entry = new HashMap<String, String>(); - entry.put("storeId", String.valueOf(store.getId())); - entry.put("code", store.getCode()); - entry.put("name", store.getStorename()); - entry.put("email", store.getStoreEmailAddress()); - resp.addDataEntry(entry); - } - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - - final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK); - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value = "/admin/store/storeCreate.html", method = RequestMethod.GET) - public String displayMerchantStoreCreate(Model model, HttpServletRequest request, HttpServletResponse response, - Locale locale) throws Exception { - - setMenu(model, request); - - MerchantStore store = new MerchantStore(); - - MerchantStore sessionStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE); - store.setCurrency(sessionStore.getCurrency()); - store.setCountry(sessionStore.getCountry()); - store.setZone(sessionStore.getZone()); - store.setStorestateprovince(sessionStore.getStorestateprovince()); - store.setLanguages(sessionStore.getLanguages()); - store.setDomainName(sessionStore.getDomainName()); - - return displayMerchantStore(store, model, request, response, locale); - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value = "/admin/store/store.html", method = RequestMethod.GET) - public String displayMerchantStore(Model model, HttpServletRequest request, HttpServletResponse response, - Locale locale) throws Exception { - - setMenu(model, request); - MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE); - return displayMerchantStore(store, model, request, response, locale); - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value = "/admin/store/editStore.html", method = RequestMethod.GET) - public String displayMerchantStore(@ModelAttribute("id") Integer id, Model model, HttpServletRequest request, - HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model, request); - MerchantStore store = merchantStoreService.getById(id); - return displayMerchantStore(store, model, request, response, locale); - } - - private String displayMerchantStore(MerchantStore store, Model model, HttpServletRequest request, - HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model, request); - Language language = (Language) request.getAttribute("LANGUAGE"); - List<Language> languages = languageService.getLanguages(); - List<Currency> currencies = currencyService.list(); - if (CollectionUtils.isNotEmpty(currencies)) { - Collections.sort(currencies, new Comparator<Currency>() { - @Override - public int compare(final Currency object1, final Currency object2) { - return object1.getName().compareTo(object2.getName()); - } - }); - } - Date dt = store.getInBusinessSince(); - if (dt != null) { - store.setDateBusinessSince(DateUtil.formatDate(dt)); - } else { - store.setDateBusinessSince(DateUtil.formatDate(new Date())); - } - - // get countries - List<Country> countries = countryService.getCountries(language); - - List<Weight> weights = new ArrayList<Weight>(); - weights.add(new Weight("LB", messages.getMessage("label.generic.weightunit.LB", locale))); - weights.add(new Weight("KG", messages.getMessage("label.generic.weightunit.KG", locale))); - - List<Size> sizes = new ArrayList<Size>(); - sizes.add(new Size("CM", messages.getMessage("label.generic.sizeunit.CM", locale))); - sizes.add(new Size("IN", messages.getMessage("label.generic.sizeunit.IN", locale))); - - // display menu - - model.addAttribute("countries", countries); - model.addAttribute("languages", languages); - model.addAttribute("currencies", currencies); - - model.addAttribute("weights", weights); - model.addAttribute("sizes", sizes); - model.addAttribute("store", store); - - return "admin-store"; - - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value = "/admin/store/save.html", method = RequestMethod.POST) - public String saveMerchantStore(@Valid @ModelAttribute("store") MerchantStore store, BindingResult result, - Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model, request); - MerchantStore sessionStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE); - - if (store.getId() != null) { - if (store.getId().intValue() != sessionStore.getId().intValue()) { - return "redirect:/admin/store/store.html"; - } - } - - Date date = new Date(); - if (!StringUtils.isBlank(store.getDateBusinessSince())) { - try { - date = DateUtil.getDate(store.getDateBusinessSince()); - store.setInBusinessSince(date); - } catch (Exception e) { - ObjectError error = new ObjectError("dateBusinessSince", - messages.getMessage("message.invalid.date", locale)); - result.addError(error); - } - } - - List<Currency> currencies = currencyService.list(); - - Language language = (Language) request.getAttribute("LANGUAGE"); - List<Language> languages = languageService.getLanguages(); - - // get countries - List<Country> countries = countryService.getCountries(language); - - List<Weight> weights = new ArrayList<Weight>(); - weights.add(new Weight("LB", messages.getMessage("label.generic.weightunit.LB", locale))); - weights.add(new Weight("KG", messages.getMessage("label.generic.weightunit.KG", locale))); - - List<Size> sizes = new ArrayList<Size>(); - sizes.add(new Size("CM", messages.getMessage("label.generic.sizeunit.CM", locale))); - sizes.add(new Size("IN", messages.getMessage("label.generic.sizeunit.IN", locale))); - - model.addAttribute("weights", weights); - model.addAttribute("sizes", sizes); - - model.addAttribute("countries", countries); - model.addAttribute("languages", languages); - model.addAttribute("currencies", currencies); - - Country c = store.getCountry(); - List<Zone> zonesList = zoneService.getZones(c, language); - - if ((zonesList == null || zonesList.size() == 0) && StringUtils.isBlank(store.getStorestateprovince())) { - - ObjectError error = new ObjectError("zone.code", messages.getMessage("merchant.zone.invalid", locale)); - result.addError(error); - - } - - if (result.hasErrors()) { - return "admin-store"; - } - - // get country - Country country = store.getCountry(); - country = countryService.getByCode(country.getIsoCode()); - Zone zone = store.getZone(); - if (zone != null) { - zone = zoneService.getByCode(zone.getCode()); - } - Currency currency = store.getCurrency(); - currency = currencyService.getById(currency.getId()); - - List<Language> supportedLanguages = store.getLanguages(); - List<Language> supportedLanguagesList = new ArrayList<Language>(); - Map<String, Language> languagesMap = languageService.getLanguagesMap(); - for (Language lang : supportedLanguages) { - - Language l = languagesMap.get(lang.getCode()); - if (l != null) { - supportedLanguagesList.add(l); - } - - } - - Language defaultLanguage = store.getDefaultLanguage(); - defaultLanguage = languageService.getById(defaultLanguage.getId()); - if (defaultLanguage != null) { - store.setDefaultLanguage(defaultLanguage); - } - - Locale storeLocale = LocaleUtils.getLocale(defaultLanguage); - - store.setStoreTemplate(sessionStore.getStoreTemplate()); - store.setCountry(country); - store.setZone(zone); - store.setCurrency(currency); - store.setDefaultLanguage(defaultLanguage); - store.setLanguages(supportedLanguagesList); - store.setLanguages(supportedLanguagesList); - - merchantStoreService.saveOrUpdate(store); - - if (!store.getCode().equals(sessionStore.getCode())) {// create store - // send email - - try { - - Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(request.getContextPath(), store, - messages, storeLocale); - templateTokens.put(EmailConstants.EMAIL_NEW_STORE_TEXT, - messages.getMessage("email.newstore.text", storeLocale)); - templateTokens.put(EmailConstants.EMAIL_STORE_NAME, - messages.getMessage("email.newstore.name", new String[] { store.getStorename() }, storeLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_STORE_INFO_LABEL, - messages.getMessage("email.newstore.info", storeLocale)); - - templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, - messages.getMessage("label.adminurl", storeLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_URL, filePathUtils.buildAdminUri(store, request)); - - Email email = new Email(); - email.setFrom(store.getStorename()); - email.setFromEmail(store.getStoreEmailAddress()); - email.setSubject(messages.getMessage("email.newstore.title", storeLocale)); - email.setTo(store.getStoreEmailAddress()); - email.setTemplateName(NEW_STORE_TMPL); - email.setTemplateTokens(templateTokens); - - emailService.sendHtmlEmail(store, email); - - } catch (Exception e) { - LOGGER.error("Cannot send email to user", e); - } - - } - - sessionStore = merchantStoreService.getByCode(sessionStore.getCode()); - - // update session store - request.getSession().setAttribute(Constants.ADMIN_STORE, sessionStore); - - model.addAttribute("success", "success"); - model.addAttribute("store", store); - - return "admin-store"; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value = "/admin/store/checkStoreCode.html", method = RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkStoreCode(HttpServletRequest request, HttpServletResponse response, - Locale locale) { - String code = request.getParameter("code"); - - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - if (StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - return new ResponseEntity<String>(resp.toJSONString(), httpHeaders, HttpStatus.OK); - } - - MerchantStore store = merchantStoreService.getByCode(code); - - if (store != null) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - return new ResponseEntity<String>(resp.toJSONString(), httpHeaders, HttpStatus.OK); - } - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while getting user", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - - return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK); - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/store/remove.html", method = RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeMerchantStore(HttpServletRequest request, Locale locale) - throws Exception { - - String sMerchantStoreId = request.getParameter("storeId"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - Integer storeId = Integer.parseInt(sMerchantStoreId); - MerchantStore store = merchantStoreService.getById(storeId); - - User user = userService.getByUserName(request.getRemoteUser()); - - /** - * In order to remove a Store the logged in ser must be SUPERADMIN - */ - - // check if the user removed has group SUPERADMIN - boolean isSuperAdmin = false; - if (UserUtils.userInGroup(user, Constants.GROUP_SUPERADMIN)) { - isSuperAdmin = true; - } - - if (!isSuperAdmin) { - resp.setStatusMessage(messages.getMessage("message.security.caanotremovesuperadmin", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK); - } - - merchantStoreService.delete(store); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while deleting product price", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - - return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK); - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("store", "store"); - activeMenus.put("storeDetails", "storeDetails"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("store"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/merchant/StoreBrandingController.java+0 −208 removed@@ -1,208 +0,0 @@ -package com.salesmanager.shop.admin.controller.merchant; - - -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.currency.CurrencyService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.content.FileContentType; -import com.salesmanager.core.model.content.InputContentFile; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - -@Controller -public class StoreBrandingController { - - private static final Logger LOGGER = LoggerFactory.getLogger(StoreBrandingController.class); - - - @Inject - MerchantStoreService merchantStoreService; - - @Inject - CountryService countryService; - - @Inject - ZoneService zoneService; - - @Inject - LanguageService languageService; - - @Inject - CurrencyService currencyService; - - @Inject - private ContentService contentService; - - - @Resource(name="templates") - List<String> templates; - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/storeBranding.html", method=RequestMethod.GET) - public String displayStoreBranding(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //display templates - model.addAttribute("templates", templates); - - model.addAttribute("store", store); - - - - return "admin-store-branding"; - } - - /** - * https://spring.io/guides/gs/uploading-files/ - * @param contentImages - * @param result - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/saveBranding.html", method=RequestMethod.POST) - public String saveStoreBranding(@RequestParam("file") MultipartFile file, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - model.addAttribute("templates", templates); - - - model.addAttribute("store", store); - - if(file!=null) { - - String imageName = file.getOriginalFilename(); - InputStream inputStream = file.getInputStream(); - String mimeType = file.getContentType(); - - InputContentFile cmsContentImage = new InputContentFile(); - cmsContentImage.setFileName(imageName); - cmsContentImage.setMimeType(mimeType); - cmsContentImage.setFile( inputStream ); - contentService.addLogo(store.getCode(), cmsContentImage); - - //Update store - store.setStoreLogo(imageName); - merchantStoreService.update(store); - request.getSession().setAttribute(Constants.ADMIN_STORE, store); - - } else { - model.addAttribute("error","error"); - return "admin-store-branding"; - } - - model.addAttribute("success","success"); - return "admin-store-branding"; - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/saveTemplate.html", method=RequestMethod.POST) - public String saveTemplate(@ModelAttribute(value="store") final MerchantStore store, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore sessionstore = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - sessionstore.setStoreTemplate(store.getStoreTemplate()); - - merchantStoreService.saveOrUpdate(sessionstore); - - request.setAttribute(Constants.ADMIN_STORE, sessionstore); - - //display templates - model.addAttribute("templates", templates); - - model.addAttribute("success","success"); - model.addAttribute("store", sessionstore); - - return "admin-store-branding"; - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/removeImage.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeImage(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - try { - - - - contentService.removeFile(store.getCode(), FileContentType.LOGO, store.getStoreLogo()); - - store.setStoreLogo(null); - merchantStoreService.update(store); - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("store", "store"); - activeMenus.put("storeBranding", "storeBranding"); - - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("store"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/merchant/StoreLandingController.java+0 −238 removed@@ -1,238 +0,0 @@ -package com.salesmanager.shop.admin.controller.merchant; - - -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.model.content.Content; -import com.salesmanager.core.model.content.ContentDescription; -import com.salesmanager.core.model.content.ContentType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.merchant.StoreLanding; -import com.salesmanager.shop.admin.model.merchant.StoreLandingDescription; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Controller -public class StoreLandingController { - - @Inject - MerchantStoreService merchantStoreService; - - @Inject - LanguageService languageService; - - @Inject - ContentService contentService; - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/storeLanding.html", method=RequestMethod.GET) - public String displayStoreLanding(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = store.getLanguages(); - - Content content = contentService.getByCode("LANDING_PAGE", store); - StoreLanding landing = new StoreLanding(); - - List<StoreLandingDescription> descriptions = new ArrayList<StoreLandingDescription>(); - - - for(Language l : languages) { - - StoreLandingDescription landingDescription = null; - if(content!=null) { - for(ContentDescription desc : content.getDescriptions()) { - if(desc.getLanguage().getCode().equals(l.getCode())) { - landingDescription = new StoreLandingDescription(); - landingDescription.setDescription(desc.getMetatagDescription()); - landingDescription.setHomePageContent(desc.getDescription()); - landingDescription.setKeywords(desc.getMetatagKeywords()); - landingDescription.setTitle(desc.getName());//name is a not empty - landingDescription.setLanguage(desc.getLanguage()); - break; - } - } - } - - if(landingDescription==null) { - landingDescription = new StoreLandingDescription(); - landingDescription.setLanguage(l); - } - - - - descriptions.add(landingDescription); - } - - landing.setDescriptions(descriptions); - - - model.addAttribute("store", store); - model.addAttribute("storeLanding", landing); - - - return "admin-store-landing"; - } - - @PreAuthorize("hasRole('STORE')") - @RequestMapping(value="/admin/store/saveLanding.html", method=RequestMethod.POST) - public String saveStoreLanding(@Valid @ModelAttribute("storeLanding") StoreLanding storeLanding, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - if (result.hasErrors()) { - return "admin-store-landing"; - } - - //get original store - Content content = contentService.getByCode("LANDING_PAGE", store); - - if(content==null) { - content = new Content(); - content.setVisible(true); - content.setContentType(ContentType.SECTION); - content.setCode("LANDING_PAGE"); - content.setMerchantStore(store); - } - - - //List<Language> languages = store.getLanguages(); - - Map<String,Language> langs = languageService.getLanguagesMap(); - - - -/* for(Language l : languages) { - - StoreLandingDescription landingDescription = null; - for(ContentDescription desc : content.getDescriptions()) { - if(desc.getLanguage().getCode().equals(l.getCode())) { - landingDescription = new StoreLandingDescription(); - landingDescription.setDescription(desc.getMetatagDescription()); - landingDescription.setHomePageContent(desc.getDescription()); - landingDescription.setKeywords(desc.getMetatagKeywords()); - landingDescription.setTitle(desc.getName());//name is a not empty - landingDescription.setLanguage(desc.getLanguage()); - } - } - - - if(landingDescription==null) { - landingDescription = new StoreLandingDescription(); - landingDescription.setLanguage(l); - } - - - - descriptions.add(landingDescription); - } - - landing.setDescriptions(descriptions);*/ - - - - - - List<StoreLandingDescription> descriptions = storeLanding.getDescriptions(); - List<ContentDescription> contentDescriptions = new ArrayList<ContentDescription>(); - if(descriptions!=null) { - - for(StoreLandingDescription description : descriptions) { - - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - - ContentDescription contentDescription = null; - if(content.getDescriptions()!=null && content.getDescriptions().size()>0) { - - for(ContentDescription desc : content.getDescriptions()) { - - if(desc.getLanguage().getCode().equals(l.getCode())) { - contentDescription = desc; - desc.setMetatagDescription(description.getDescription()); - desc.setName(description.getTitle()); - desc.setTitle(description.getTitle()); - desc.setDescription(description.getHomePageContent()); - desc.setMetatagKeywords(description.getKeywords()); - - - } - - } - } - - if(contentDescription==null) { - - - contentDescription = new ContentDescription(); - contentDescription.setContent(content); - contentDescription.setLanguage(l); - contentDescription.setMetatagDescription(description.getDescription()); - contentDescription.setName(description.getTitle()); - contentDescription.setDescription(description.getHomePageContent()); - contentDescription.setMetatagKeywords(description.getKeywords()); - - } - - contentDescriptions.add(contentDescription); - - - - } - - content.setDescriptions(contentDescriptions); - - } - - - - contentService.saveOrUpdate(content); - - model.addAttribute("success","success"); - - return "admin-store-landing"; - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("store", "store"); - activeMenus.put("storeLanding", "storeLanding"); - - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("store"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/orders/OrderActionsControler.java+0 −601 removed@@ -1,601 +0,0 @@ -package com.salesmanager.shop.admin.controller.orders; - -import com.salesmanager.core.business.services.catalog.product.PricingService; -import com.salesmanager.core.business.services.customer.CustomerService; -import com.salesmanager.core.business.services.order.OrderService; -import com.salesmanager.core.business.services.payments.PaymentService; -import com.salesmanager.core.business.services.payments.TransactionService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.customer.Customer; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.order.Order; -import com.salesmanager.core.model.order.orderstatus.OrderStatusHistory; -import com.salesmanager.core.model.payments.Transaction; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.modules.integration.IntegrationException; -import com.salesmanager.shop.admin.model.orders.Refund; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.EmailTemplatesUtils; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.LocaleUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayOutputStream; -import java.math.BigDecimal; -import java.util.*; - -/** - * Manage order details - * @author Carl Samson - */ -@Controller -public class OrderActionsControler { - -private static final Logger LOGGER = LoggerFactory.getLogger(OrderActionsControler.class); - - @Inject - private LabelUtils messages; - - @Inject - private OrderService orderService; - - @Inject - CountryService countryService; - - @Inject - ZoneService zoneService; - - @Inject - PaymentService paymentService; - - @Inject - CustomerService customerService; - - @Inject - PricingService pricingService; - - @Inject - TransactionService transactionService; - - @Inject - EmailService emailService; - - @Inject - EmailTemplatesUtils emailTemplatesUtils; - - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/captureOrder.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> captureOrder(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - String sId = request.getParameter("id"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - Long id = Long.parseLong(sId); - - Order order = orderService.getById(id); - - if(order==null) { - - LOGGER.error("Order {0} does not exists", id); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(order.getMerchant().getId().intValue()!=store.getId().intValue()) { - - LOGGER.error("Merchant store does not have order {0}",id); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Customer customer = customerService.getById(order.getCustomerId()); - - if(customer==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.notexist.customer", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - paymentService.processCapturePayment(order, customer, store); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (IntegrationException e) { - LOGGER.error("Error while processing capture", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString(messages.getMessage(e.getMessageCode(),locale)); - } catch (Exception e) { - LOGGER.error("Error while getting order", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/refundOrder.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> refundOrder(@RequestBody Refund refund, HttpServletRequest request, HttpServletResponse response, Locale locale) { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - BigDecimal submitedAmount = null; - - try { - - Order order = orderService.getById(refund.getOrderId()); - - if(order==null) { - - LOGGER.error("Order {0} does not exists", refund.getOrderId()); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(order.getMerchant().getId().intValue()!=store.getId().intValue()) { - - LOGGER.error("Merchant store does not have order {0}",refund.getOrderId()); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - //parse amount - try { - submitedAmount = new BigDecimal(refund.getAmount()); - if(submitedAmount.doubleValue()==0) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.invalid.amount", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - } catch (Exception e) { - LOGGER.equals("invalid refundAmount " + refund.getAmount()); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - BigDecimal orderTotal = order.getTotal(); - if(submitedAmount.doubleValue()>orderTotal.doubleValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.invalid.amount", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(submitedAmount.doubleValue()<=0) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.invalid.amount", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Customer customer = customerService.getById(order.getCustomerId()); - - if(customer==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.notexist.customer", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - paymentService.processRefund(order, customer, store, submitedAmount); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - } catch (IntegrationException e) { - LOGGER.error("Error while processing refund", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString(messages.getMessage(e.getMessageCode(),locale)); - } catch (Exception e) { - LOGGER.error("Error while processing refund", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/printInvoice.html", method=RequestMethod.GET) - public void printInvoice(HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - String sId = request.getParameter("id"); - - try { - - Long id = Long.parseLong(sId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Order order = orderService.getOrder(id, store); - - if(order.getMerchant().getId().intValue()!=store.getId().intValue()) { - throw new Exception("Invalid order"); - } - - - Language lang = store.getDefaultLanguage(); - - - - ByteArrayOutputStream stream = orderService.generateInvoice(store, order, lang); - StringBuilder attachment = new StringBuilder(); - //attachment.append("attachment; filename="); - attachment.append(order.getId()); - attachment.append(".pdf"); - - response.setHeader("Content-disposition", "attachment;filename=" + attachment.toString()); - - //Set the mime type for the response - response.setContentType("application/pdf"); - - - response.getOutputStream().write(stream.toByteArray()); - - response.flushBuffer(); - - - } catch(Exception e) { - LOGGER.error("Error while printing a report",e); - } - - - } - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/listTransactions.html", method=RequestMethod.GET) - public @ResponseBody ResponseEntity<String> listTransactions(HttpServletRequest request, HttpServletResponse response) throws Exception { - - String sId = request.getParameter("id"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(sId==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - try { - - Long id = Long.parseLong(sId); - - - Order dbOrder = orderService.getOrder(id, store); - - if(dbOrder==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - if(dbOrder.getMerchant().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - List<Transaction> transactions = transactionService.listTransactions(dbOrder); - - if(transactions!=null) { - - for(Transaction transaction : transactions) { - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("transactionId", transaction.getId()); - entry.put("transactionDate", DateUtil.formatLongDate(transaction.getTransactionDate())); - entry.put("transactionType", transaction.getTransactionType().name()); - entry.put("paymentType", transaction.getPaymentType().name()); - entry.put("transactionAmount", pricingService.getStringAmount(transaction.getAmount(), store)); - entry.put("transactionDetails", transaction.getTransactionDetails()); - resp.addDataEntry(entry); - } - - - } - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch(Exception e) { - LOGGER.error("Cannot get transactions for order id " + sId, e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/sendInvoice.html", method=RequestMethod.GET) - public @ResponseBody ResponseEntity<String> sendInvoice(HttpServletRequest request, HttpServletResponse response) throws Exception { - - String sId = request.getParameter("id"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(sId==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - try { - - Long id = Long.parseLong(sId); - - - Order dbOrder = orderService.getOrder(id, store); - - if(dbOrder==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - if(dbOrder.getMerchant().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - //get customer - Customer customer = customerService.getById(dbOrder.getCustomerId()); - - if(customer==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Customer does not exist"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Locale customerLocale = LocaleUtils.getLocale(customer.getDefaultLanguage()); - - emailTemplatesUtils.sendOrderEmail(customer.getEmailAddress(), customer, dbOrder, customerLocale, customer.getDefaultLanguage(), store, request.getContextPath()); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch(Exception e) { - LOGGER.error("Cannot get transactions for order id " + sId, e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/updateStatus.html", method=RequestMethod.GET) - public @ResponseBody ResponseEntity<String> updateStatus(HttpServletRequest request, HttpServletResponse response) throws Exception { - - String sId = request.getParameter("id"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(sId==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - try { - - Long id = Long.parseLong(sId); - - - Order dbOrder = orderService.getById(id); - - if(dbOrder==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - if(dbOrder.getMerchant().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - //get customer - Customer customer = customerService.getById(dbOrder.getCustomerId()); - - if(customer==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Customer does not exist"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Locale customerLocale = LocaleUtils.getLocale(customer.getDefaultLanguage()); - - - Set<OrderStatusHistory> orderStatus = dbOrder.getOrderHistory(); - OrderStatusHistory lastHistory = null; - if(orderStatus!=null) { - int count = 1; - for(OrderStatusHistory history : orderStatus) { - if(count==orderStatus.size()) { - lastHistory = history; - break; - } - count++; - } - } - - if(lastHistory==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("No history"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - emailTemplatesUtils.sendUpdateOrderStatusEmail(customer, dbOrder, lastHistory, store, customerLocale, request.getContextPath()); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch(Exception e) { - LOGGER.error("Cannot get transactions for order id " + sId, e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString(e.getMessage()); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/sendDownloadEmail.html", method=RequestMethod.GET) - public @ResponseBody ResponseEntity<String> sendDownloadEmail(HttpServletRequest request, HttpServletResponse response) throws Exception { - - String sId = request.getParameter("id"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(sId==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - try { - - Long id = Long.parseLong(sId); - - - Order dbOrder = orderService.getById(id); - - if(dbOrder==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - if(dbOrder.getMerchant().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - //get customer - Customer customer = customerService.getById(dbOrder.getCustomerId()); - - if(customer==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Customer does not exist"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Locale customerLocale = LocaleUtils.getLocale(customer.getDefaultLanguage()); - - - emailTemplatesUtils.sendOrderDownloadEmail(customer, dbOrder, store, customerLocale, request.getContextPath()); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch(Exception e) { - LOGGER.error("Cannot get transactions for order id " + sId, e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString(e.getMessage()); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/orders/OrderControler.java+0 −532 removed@@ -1,532 +0,0 @@ -package com.salesmanager.shop.admin.controller.orders; - -import com.salesmanager.core.business.modules.email.Email; -import com.salesmanager.core.business.services.catalog.product.PricingService; -import com.salesmanager.core.business.services.customer.CustomerService; -import com.salesmanager.core.business.services.order.OrderService; -import com.salesmanager.core.business.services.order.orderproduct.OrderProductDownloadService; -import com.salesmanager.core.business.services.order.orderstatushistory.OrderStatusHistoryService; -import com.salesmanager.core.business.services.payments.PaymentService; -import com.salesmanager.core.business.services.payments.TransactionService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.utils.CoreConfiguration; -import com.salesmanager.core.model.customer.Customer; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.order.Order; -import com.salesmanager.core.model.order.OrderTotal; -import com.salesmanager.core.model.order.orderproduct.OrderProduct; -import com.salesmanager.core.model.order.orderproduct.OrderProductDownload; -import com.salesmanager.core.model.order.orderstatus.OrderStatusHistory; -import com.salesmanager.core.model.payments.PaymentType; -import com.salesmanager.core.model.payments.Transaction; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.reference.zone.Zone; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.constants.EmailConstants; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.EmailUtils; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.LocaleUtils; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; -import java.util.regex.Pattern; - -/** - * Manage order details - * @author Carl Samson - * - */ -@Controller -public class OrderControler { - -private static final Logger LOGGER = LoggerFactory.getLogger(OrderControler.class); - - @Inject - private LabelUtils messages; - - @Inject - private OrderService orderService; - - @Inject - CountryService countryService; - - @Inject - ZoneService zoneService; - - @Inject - PaymentService paymentService; - - @Inject - CustomerService customerService; - - @Inject - PricingService pricingService; - - @Inject - TransactionService transactionService; - - @Inject - EmailService emailService; - - @Inject - private EmailUtils emailUtils; - - @Inject - OrderProductDownloadService orderProdctDownloadService; - - @Inject - private OrderStatusHistoryService orderStatusHistoryService; - - @Inject - private CoreConfiguration coreConfiguration; - - private final static String ORDER_STATUS_TMPL = "email_template_order_status.ftl"; - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/editOrder.html", method=RequestMethod.GET) - public String displayOrderEdit(@RequestParam("id") long orderId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - return displayOrder(orderId,model,request,response); - - } - - @PreAuthorize("hasRole('ORDER')") - private String displayOrder(Long orderId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - //display menu - setMenu(model,request); - - com.salesmanager.shop.admin.model.orders.Order order = new com.salesmanager.shop.admin.model.orders.Order(); - Language language = (Language)request.getAttribute("LANGUAGE"); - List<Country> countries = countryService.getCountries(language); - if(orderId!=null && orderId!=0) { //edit mode - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - Set<OrderProduct> orderProducts = null; - Set<OrderTotal> orderTotal = null; - Set<OrderStatusHistory> orderHistory = null; - - Order dbOrder = orderService.getById(orderId); - - if(dbOrder==null) { - return "redirect:/admin/orders/list.html"; - } - - - if(dbOrder.getMerchant().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/orders/list.html"; - } - - - order.setId( orderId ); - - if( dbOrder.getDatePurchased() !=null ){ - order.setDatePurchased(DateUtil.formatDate(dbOrder.getDatePurchased())); - } - - Long customerId = dbOrder.getCustomerId(); - - if(customerId!=null && customerId>0) { - - try { - - Customer customer = customerService.getById(customerId); - if(customer!=null) { - model.addAttribute("customer",customer); - } - - - } catch(Exception e) { - LOGGER.error("Error while getting customer for customerId " + customerId, e); - } - - } - - order.setOrder( dbOrder ); - order.setBilling( dbOrder.getBilling() ); - order.setDelivery(dbOrder.getDelivery() ); - - - orderProducts = dbOrder.getOrderProducts(); - orderTotal = dbOrder.getOrderTotal(); - orderHistory = dbOrder.getOrderHistory(); - - //get capturable - if(dbOrder.getPaymentType().name() != PaymentType.MONEYORDER.name()) { - Transaction capturableTransaction = transactionService.getCapturableTransaction(dbOrder); - if(capturableTransaction!=null) { - model.addAttribute("capturableTransaction",capturableTransaction); - } - } - - - //get refundable - if(dbOrder.getPaymentType().name() != PaymentType.MONEYORDER.name()) { - Transaction refundableTransaction = transactionService.getRefundableTransaction(dbOrder); - if(refundableTransaction!=null) { - model.addAttribute("capturableTransaction",null);//remove capturable - model.addAttribute("refundableTransaction",refundableTransaction); - } - } - - - List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(order.getId()); - if(CollectionUtils.isNotEmpty(orderProductDownloads)) { - model.addAttribute("downloads",orderProductDownloads); - } - - } - - model.addAttribute("countries", countries); - model.addAttribute("order",order); - return ControllerConstants.Tiles.Order.ordersEdit; - } - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/save.html", method=RequestMethod.POST) - public String saveOrder(@Valid @ModelAttribute("order") com.salesmanager.shop.admin.model.orders.Order entityOrder, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - boolean statusOrCommentsChanged = false; - OrderStatusHistory orderStatusHistory = new OrderStatusHistory(); - String email_regEx = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b"; - Pattern pattern = Pattern.compile(email_regEx); - - Language language = (Language)request.getAttribute("LANGUAGE"); - List<Country> countries = countryService.getCountries(language); - model.addAttribute("countries", countries); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //set the id if fails - entityOrder.setId(entityOrder.getOrder().getId()); - - model.addAttribute("order", entityOrder); - - Set<OrderProduct> orderProducts = new HashSet<OrderProduct>(); - Set<OrderTotal> orderTotal = new HashSet<OrderTotal>(); - Set<OrderStatusHistory> orderHistory = new HashSet<OrderStatusHistory>(); - - Date date = new Date(); - if(!StringUtils.isBlank(entityOrder.getDatePurchased() ) ){ - try { - date = DateUtil.getDate(entityOrder.getDatePurchased()); - } catch (Exception e) { - ObjectError error = new ObjectError("datePurchased",messages.getMessage("message.invalid.date", locale)); - result.addError(error); - } - - } else{ - date = null; - } - - - if(!StringUtils.isBlank(entityOrder.getOrder().getCustomerEmailAddress() ) ){ - java.util.regex.Matcher matcher = pattern.matcher(entityOrder.getOrder().getCustomerEmailAddress()); - - if(!matcher.find()) { - ObjectError error = new ObjectError("customerEmailAddress",messages.getMessage("Email.order.customerEmailAddress", locale)); - result.addError(error); - } - }else{ - ObjectError error = new ObjectError("customerEmailAddress",messages.getMessage("NotEmpty.order.customerEmailAddress", locale)); - result.addError(error); - } - - - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getFirstName() ) ){ - ObjectError error = new ObjectError("billingFirstName", messages.getMessage("NotEmpty.order.billingFirstName", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getFirstName() ) ){ - ObjectError error = new ObjectError("billingLastName", messages.getMessage("NotEmpty.order.billingLastName", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getAddress() ) ){ - ObjectError error = new ObjectError("billingAddress", messages.getMessage("NotEmpty.order.billingStreetAddress", locale)); - result.addError(error); - } - - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getCity() ) ){ - ObjectError error = new ObjectError("billingCity",messages.getMessage("NotEmpty.order.billingCity", locale)); - result.addError(error); - } - - if( entityOrder.getOrder().getBilling().getZone()==null){ - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getState())){ - ObjectError error = new ObjectError("billingState",messages.getMessage("NotEmpty.order.billingState", locale)); - result.addError(error); - } - } - - if( StringUtils.isBlank(entityOrder.getOrder().getBilling().getPostalCode() ) ){ - ObjectError error = new ObjectError("billingPostalCode", messages.getMessage("NotEmpty.order.billingPostCode", locale)); - result.addError(error); - } - - com.salesmanager.core.model.order.Order newOrder = orderService.getById(entityOrder.getOrder().getId() ); - - //If there was a status changed by Admin, we notify the customer - if(BooleanUtils.toBoolean(coreConfiguration.getProperty("MAIL_SEND_ORDER_UPDATES")) - && (newOrder.getStatus() != null && !newOrder.getStatus().equals(entityOrder.getOrder().getStatus()))) { - statusOrCommentsChanged = true; - addStatusChangedHistory(entityOrder, locale, orderStatusHistory, newOrder); - } - //get capturable - if(newOrder.getPaymentType().name() != PaymentType.MONEYORDER.name()) { - Transaction capturableTransaction = transactionService.getCapturableTransaction(newOrder); - if(capturableTransaction!=null) { - model.addAttribute("capturableTransaction",capturableTransaction); - } - } - - - //get refundable - if(newOrder.getPaymentType().name() != PaymentType.MONEYORDER.name()) { - Transaction refundableTransaction = transactionService.getRefundableTransaction(newOrder); - if(refundableTransaction!=null) { - model.addAttribute("capturableTransaction",null);//remove capturable - model.addAttribute("refundableTransaction",refundableTransaction); - } - } - - - if (result.hasErrors()) { - // somehow we lose data, so reset Order detail info. - entityOrder.getOrder().setOrderProducts( orderProducts); - entityOrder.getOrder().setOrderTotal(orderTotal); - entityOrder.getOrder().setOrderHistory(orderHistory); - - return ControllerConstants.Tiles.Order.ordersEdit; - /* "admin-orders-edit"; */ - } - - - - - - Country deliveryCountry = countryService.getByCode( entityOrder.getOrder().getDelivery().getCountry().getIsoCode()); - Country billingCountry = countryService.getByCode( entityOrder.getOrder().getBilling().getCountry().getIsoCode()) ; - Zone billingZone = null; - Zone deliveryZone = null; - if(entityOrder.getOrder().getBilling().getZone()!=null) { - billingZone = zoneService.getByCode(entityOrder.getOrder().getBilling().getZone().getCode()); - } - - if(entityOrder.getOrder().getDelivery().getZone()!=null) { - deliveryZone = zoneService.getByCode(entityOrder.getOrder().getDelivery().getZone().getCode()); - } - - newOrder.setCustomerEmailAddress(entityOrder.getOrder().getCustomerEmailAddress() ); - newOrder.setStatus(entityOrder.getOrder().getStatus() ); - - newOrder.setDatePurchased(date); - newOrder.setLastModified( new Date() ); - - if(!StringUtils.isBlank(entityOrder.getOrderHistoryComment() ) ) { - orderStatusHistory.setComments( entityOrder.getOrderHistoryComment() ); - orderStatusHistory.setCustomerNotified(1); - orderStatusHistory.setStatus(entityOrder.getOrder().getStatus()); - orderStatusHistory.setDateAdded(new Date() ); - orderStatusHistory.setOrder(newOrder); - newOrder.getOrderHistory().add( orderStatusHistory ); - entityOrder.setOrderHistoryComment( "" ); - statusOrCommentsChanged = true; - } - - newOrder.setDelivery( entityOrder.getOrder().getDelivery() ); - newOrder.setBilling( entityOrder.getOrder().getBilling() ); - newOrder.setCustomerAgreement(entityOrder.getOrder().getCustomerAgreement()); - - newOrder.getDelivery().setCountry(deliveryCountry ); - newOrder.getBilling().setCountry(billingCountry ); - - if(billingZone!=null) { - newOrder.getBilling().setZone(billingZone); - } - - if(deliveryZone!=null) { - newOrder.getDelivery().setZone(deliveryZone); - } - - orderService.saveOrUpdate(newOrder); - entityOrder.setOrder(newOrder); - entityOrder.setBilling(newOrder.getBilling()); - entityOrder.setDelivery(newOrder.getDelivery()); - model.addAttribute("order", entityOrder); - - Long customerId = newOrder.getCustomerId(); - - if(customerId!=null && customerId>0) { - - try { - - Customer customer = customerService.getById(customerId); - if(customer!=null) { - model.addAttribute("customer",customer); - } - - - } catch(Exception e) { - LOGGER.error("Error while getting customer for customerId " + customerId, e); - } - - } - - List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(newOrder.getId()); - if(CollectionUtils.isNotEmpty(orderProductDownloads)) { - model.addAttribute("downloads",orderProductDownloads); - } - - - /** - * send email if admin posted orderHistoryComment - * - * **/ - - if(statusOrCommentsChanged) { - - try { - - Customer customer = customerService.getById(newOrder.getCustomerId()); - Language lang = store.getDefaultLanguage(); - if(customer!=null) { - lang = customer.getDefaultLanguage(); - } - - Locale customerLocale = LocaleUtils.getLocale(lang); - - StringBuilder customerName = new StringBuilder(); - customerName.append(newOrder.getBilling().getFirstName()).append(" ").append(newOrder.getBilling().getLastName()); - - - Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, customerLocale); - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_NAME, customerName.toString()); - templateTokens.put(EmailConstants.EMAIL_TEXT_ORDER_NUMBER, messages.getMessage("email.order.confirmation", new String[]{String.valueOf(newOrder.getId())}, customerLocale)); - templateTokens.put(EmailConstants.EMAIL_TEXT_DATE_ORDERED, messages.getMessage("email.order.ordered", new String[]{entityOrder.getDatePurchased()}, customerLocale)); - templateTokens.put(EmailConstants.EMAIL_TEXT_STATUS_COMMENTS, messages.getMessage("email.order.comments", new String[]{entityOrder.getOrderHistoryComment()}, customerLocale)); - templateTokens.put(EmailConstants.EMAIL_TEXT_DATE_UPDATED, messages.getMessage("email.order.updated", new String[]{DateUtil.formatDate(new Date())}, customerLocale)); - - - if(BooleanUtils.toBoolean(coreConfiguration.getProperty("MAIL_SEND_ORDER_UPDATES"))) { - //This allows to send every order status update or comments from admin to the customer - addStatusUpdatedInfo(entityOrder, customer, customerLocale, templateTokens); - } - - - Email email = new Email(); - email.setFrom(store.getStorename()); - email.setFromEmail(store.getStoreEmailAddress()); - email.setSubject(messages.getMessage("email.order.status.title",new String[]{String.valueOf(newOrder.getId())},customerLocale)); - email.setTo(entityOrder.getOrder().getCustomerEmailAddress()); - email.setTemplateName(ORDER_STATUS_TMPL); - email.setTemplateTokens(templateTokens); - - - - emailService.sendHtmlEmail(store, email); - - } catch (Exception e) { - LOGGER.error("Cannot send email to customer",e); - } - - } - - model.addAttribute("success","success"); - - - return ControllerConstants.Tiles.Order.ordersEdit; - /* "admin-orders-edit"; */ - } - - private void addStatusUpdatedInfo(com.salesmanager.shop.admin.model.orders.Order entityOrder, Customer customer, Locale customerLocale, Map<String, String> templateTokens) { - OrderStatusHistory lastHistory = getOrderStatusHistory(entityOrder, customerLocale); - String hi = messages.getMessage("label.generic.hi", customerLocale); - if (StringUtils.isNotEmpty(lastHistory.getComments())) { - templateTokens.put(EmailConstants.EMAIL_TEXT_STATUS_COMMENTS, messages.getMessage("email.order.comments", new String[]{lastHistory.getComments()}, customerLocale)); - } - String[] statusMessageText = {String.valueOf(entityOrder.getOrder().getId()), DateUtil.formatDate(entityOrder.getOrder().getDatePurchased())}; - String status = messages.getMessage("label.order." + entityOrder.getOrder().getStatus().name(), customerLocale, entityOrder.getOrder().getStatus().name()); - String[] statusMessage = {DateUtil.formatDate(lastHistory.getDateAdded()), status}; - if (customer != null) { - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, customer.getBilling().getFirstName()); - templateTokens.put(EmailConstants.EMAIL_CUSTOMER_LASTNAME, customer.getBilling().getLastName()); - } - templateTokens.put(EmailConstants.LABEL_HI, hi); - templateTokens.put(EmailConstants.EMAIL_ORDER_STATUS_TEXT, messages.getMessage("email.order.statustext", statusMessageText, customerLocale)); - templateTokens.put(EmailConstants.EMAIL_ORDER_STATUS, messages.getMessage("email.order.status", statusMessage, customerLocale)); - } - - private OrderStatusHistory getOrderStatusHistory(com.salesmanager.shop.admin.model.orders.Order entityOrder, Locale customerLocale) { - OrderStatusHistory lastHistory = null; - List<OrderStatusHistory> lastHistories = orderStatusHistoryService.findByOrder(entityOrder.getOrder()); - if(CollectionUtils.isEmpty(lastHistories)) { - lastHistory = new OrderStatusHistory(); - lastHistory.setComments(messages.getMessage("label.order.PROCESSING", customerLocale)); - lastHistory.setDateAdded(new Date()); - } else { - lastHistory = lastHistories.get(0); - } - return lastHistory; - } - - private void addStatusChangedHistory(com.salesmanager.shop.admin.model.orders.Order entityOrder, Locale locale, - OrderStatusHistory orderStatusHistory, Order newOrder) { - orderStatusHistory.setComments( messages.getMessage("email.order.status.changed", - new String[] {newOrder.getStatus().name(), entityOrder.getOrder().getStatus().name()}, locale)); - orderStatusHistory.setCustomerNotified(1); - orderStatusHistory.setStatus(entityOrder.getOrder().getStatus()); - orderStatusHistory.setDateAdded(new Date() ); - orderStatusHistory.setOrder(newOrder); - newOrder.getOrderHistory().add(orderStatusHistory); - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("order", "order"); - activeMenus.put("order-list", "order-list"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - model.addAttribute("activeMenus",activeMenus); - - Menu currentMenu = (Menu)menus.get("order"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/orders/OrdersController.java+0 −183 removed@@ -1,183 +0,0 @@ -package com.salesmanager.shop.admin.controller.orders; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.salesmanager.core.business.services.order.OrderService; -import com.salesmanager.core.business.services.system.ModuleConfigurationService; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.common.CriteriaOrderBy; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.order.Order; -import com.salesmanager.core.model.order.OrderCriteria; -import com.salesmanager.core.model.order.OrderList; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.system.IntegrationModule; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - - -/** - * Manage order list - * Manage search order - * @author csamson - * - */ -@Controller -@JsonAutoDetect(getterVisibility=com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE) -public class OrdersController { - - @Inject - OrderService orderService; - - @Inject - LabelUtils messages; - - @Inject - private ProductPriceUtils priceUtil; - - @Inject - protected ModuleConfigurationService moduleConfigurationService; - - private static final Logger LOGGER = LoggerFactory.getLogger(OrderControler.class); - - - @PreAuthorize("hasRole('ORDER')") - @RequestMapping(value="/admin/orders/list.html", method=RequestMethod.GET) - public String displayOrders(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - //the list of orders is from page method - - return ControllerConstants.Tiles.Order.orders; - - - } - - - @PreAuthorize("hasRole('ORDER')") - @SuppressWarnings({ "unchecked", "unused"}) - @RequestMapping(value="/admin/orders/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOrders(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - - AjaxPageableResponse resp = new AjaxPageableResponse(); - - try { - - int startRow = Integer.parseInt(request.getParameter("_startRow")); - int endRow = Integer.parseInt(request.getParameter("_endRow")); - String paymentModule = request.getParameter("paymentModule"); - String customerName = request.getParameter("customer"); - - OrderCriteria criteria = new OrderCriteria(); - criteria.setOrderBy(CriteriaOrderBy.DESC); - criteria.setStartIndex(startRow); - criteria.setMaxCount(endRow); - if(!StringUtils.isBlank(paymentModule)) { - criteria.setPaymentMethod(paymentModule); - } - - if(!StringUtils.isBlank(customerName)) { - criteria.setCustomerName(customerName); - } - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - List<IntegrationModule> paymentModules = moduleConfigurationService.getIntegrationModules( "PAYMENT" ); - - - OrderList orderList = orderService.listByStore(store, criteria); - - if(orderList.getOrders()!=null) { - - for(Order order : orderList.getOrders()) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("orderId", order.getId()); - entry.put("customer", order.getBilling().getFirstName() + " " + order.getBilling().getLastName()); - entry.put("amount", priceUtil.getAdminFormatedAmountWithCurrency(store,order.getTotal()));//todo format total - entry.put("date", DateUtil.formatDate(order.getDatePurchased())); - entry.put("status", order.getStatus().name()); - - - if ( paymentModules!= null && paymentModules.size() > 0 ) - { - for ( int index = 0; index < paymentModules.size(); index++ ) - { - if ( paymentModules.get(index).getCode().equalsIgnoreCase( order.getPaymentModuleCode() ) ) - { - paymentModule = paymentModules.get(index).getCode(); - break; - } - } - - } - - entry.put("paymentModule", paymentModule ); - resp.addDataEntry(entry); - - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging orders", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("order", "order"); - activeMenus.put("order-list", "order-list"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("order"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/payments/PaymentsController.java+0 −169 removed@@ -1,169 +0,0 @@ -package com.salesmanager.shop.admin.controller.payments; - -import com.salesmanager.core.business.modules.integration.IntegrationException; -import com.salesmanager.core.business.services.payments.PaymentService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.payments.TransactionType; -import com.salesmanager.core.model.system.IntegrationConfiguration; -import com.salesmanager.core.model.system.IntegrationModule; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - -@Controller -public class PaymentsController { - - - @Inject - private PaymentService paymentService; - - @Inject - LabelUtils messages; - - - @RequestMapping(value="/admin/payments/paymentMethods.html", method=RequestMethod.GET) - public String getPaymentMethods(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - //set menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get payment methods - List<IntegrationModule> modules = paymentService.getPaymentMethods(store); - - //get configured payment modules - Map<String,IntegrationConfiguration> configuredModules = paymentService.getPaymentModulesConfigured(store); - - - - model.addAttribute("modules", modules); - model.addAttribute("configuredModules", configuredModules); - - return ControllerConstants.Tiles.Payment.paymentMethods; - - } - - @PreAuthorize("hasRole('PAYMENT')") - @RequestMapping(value="/admin/payments/paymentMethod.html", method=RequestMethod.GET) - public String displayPaymentMethod(@RequestParam("code") String code, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //get configured shipping modules - IntegrationConfiguration configuration = paymentService.getPaymentConfiguration(code, store); - if(configuration==null) { - configuration = new IntegrationConfiguration(); - configuration.setEnvironment(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - Map<String,String> keys = new HashMap<String,String>(); - keys.put("transaction", TransactionType.AUTHORIZECAPTURE.name()); - - configuration.setIntegrationKeys(keys); - - } - - configuration.setModuleCode(code); - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.TEST_ENVIRONMENT); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - model.addAttribute("configuration", configuration); - model.addAttribute("environments", environments); - return ControllerConstants.Tiles.Payment.paymentMethod; - - - } - - @PreAuthorize("hasRole('PAYMENT')") - @RequestMapping(value="/admin/payments/savePaymentMethod.html", method=RequestMethod.POST) - public String savePaymentMethod(@ModelAttribute("configuration") IntegrationConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.TEST_ENVIRONMENT); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - model.addAttribute("environments", environments); - model.addAttribute("configuration", configuration); - - try { - paymentService.savePaymentModuleConfiguration(configuration, store); - } catch (Exception e) { - if(e instanceof com.salesmanager.core.business.modules.integration.IntegrationException) { - if(((IntegrationException)e).getErrorCode()==IntegrationException.ERROR_VALIDATION_SAVE) { - - List<String> errorCodes = ((IntegrationException)e).getErrorFields(); - for(String errorCode : errorCodes) { - model.addAttribute(errorCode,messages.getMessage("message.fielderror", locale)); - } - model.addAttribute("validationError","validationError"); - return ControllerConstants.Tiles.Payment.paymentMethod; - } - } else { - throw new Exception(e); - } - } - - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Payment.paymentMethod; - - - } - - @RequestMapping(value="/admin/payments/deletePaymentMethod.html", method=RequestMethod.POST) - public String deletePaymentMethod(@RequestParam("code") String code, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - paymentService.removePaymentModuleConfiguration(code, store); - - return "redirect:/admin/payments/paymentMethods.html"; - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("payment", "payment"); - activeMenus.put("payment-methods", "payment-methods"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("payment"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/CustomProductGroupsController.java+0 −466 removed@@ -1,466 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.relationship.ProductRelationshipService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationship; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - - -@Controller -public class CustomProductGroupsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomProductGroupsController.class); - - @Inject - CategoryService categoryService; - - @Inject - ProductService productService; - - @Inject - ProductRelationshipService productRelationshipService; - - @Inject - LabelUtils messages; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/groups/list.html", method=RequestMethod.GET) - public String displayProductGroups(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - ProductRelationship group = new ProductRelationship(); - - - model.addAttribute("group", group); - - return ControllerConstants.Tiles.Product.customGroups; - - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/groups/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageCustomGroups(HttpServletRequest request, HttpServletResponse response) { - - - AjaxResponse resp = new AjaxResponse(); - - try { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - List<ProductRelationship> relationships = productRelationshipService.getGroups(store); - - for(ProductRelationship relationship : relationships) { - - if(!"FEATURED_ITEM".equals(relationship.getCode())) {//do not add featured items - - Map entry = new HashMap(); - entry.put("code", relationship.getCode()); - entry.put("active", relationship.isActive()); - - resp.addDataEntry(entry); - - } - - } - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/groups/save.html", method=RequestMethod.POST) - public String saveCustomProductGroup(@ModelAttribute("group") ProductRelationship group, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //check if group already exist - - - if(StringUtils.isBlank(group.getCode())) { - FieldError fieldError = new FieldError("group","code",group.getCode(),false,null,null,messages.getMessage("message.group.required",locale)); - result.addError(fieldError); - return ControllerConstants.Tiles.Product.customGroups; - } - - //String msg = messages.getMessage("message.group.alerady.exists",locale); - //String[] messages = {msg}; - - String[] messages = {"message.group.alerady.exists"}; - - List<ProductRelationship> groups = productRelationshipService.getGroups(store); - for(ProductRelationship grp : groups) { - if(grp.getCode().equalsIgnoreCase(group.getCode())) { - String[] args = {group.getCode()}; - FieldError fieldError = new FieldError("group","code",group.getCode(),false,messages,args,null); - result.addError(fieldError); - } - } - - if(result.hasErrors()) { - return ControllerConstants.Tiles.Product.customGroups; - } - - group.setActive(true); - group.setStore(store); - - productRelationshipService.addGroup(store,group.getCode()); - - - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Product.customGroups; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/groups/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeCustomProductGroup(HttpServletRequest request, HttpServletResponse response) { - - String groupCode = request.getParameter("code"); - - AjaxResponse resp = new AjaxResponse(); - - - try { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - productRelationshipService.deleteGroup(store, groupCode); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while deleting a group", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/groups/update.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> activateProductGroup(HttpServletRequest request, HttpServletResponse response) { - String values = request.getParameter("_oldValues"); - String active = request.getParameter("active"); - - - AjaxResponse resp = new AjaxResponse(); - - try { - - ObjectMapper mapper = new ObjectMapper(); - @SuppressWarnings("rawtypes") - Map conf = mapper.readValue(values, Map.class); - String groupCode = (String)conf.get("code"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get groups - List<ProductRelationship> groups = productRelationshipService.getGroups(store); - - for(ProductRelationship relation : groups) { - if(relation.getCode().equals(groupCode)) { - if("true".equals(active)) { - relation.setActive(true); - } else { - relation.setActive(false); - } - productRelationshipService.saveOrUpdate(relation); - } - } - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while updateing groups", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/group/edit.html", method=RequestMethod.GET) - public String displayCustomProductGroup(@RequestParam("id") String groupCode, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Category> categories = categoryService.listByStore(store,language);//for categories - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("group", groupCode); - model.addAttribute("categories", readableCategories); - return ControllerConstants.Tiles.Product.customGroupsDetails; - - } - - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/group/details/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProducts(HttpServletRequest request, HttpServletResponse response) { - - String code = request.getParameter("code"); - AjaxResponse resp = new AjaxResponse(); - - try { - - - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - List<ProductRelationship> relationships = productRelationshipService.getByGroup(store, code, language); - - for(ProductRelationship relationship : relationships) { - - Product product = relationship.getRelatedProduct(); - Map entry = new HashMap(); - entry.put("relationshipId", relationship.getId()); - entry.put("productId", product.getId()); - - ProductDescription description = product.getDescriptions().iterator().next(); - Set<ProductDescription> descriptions = product.getDescriptions(); - for(ProductDescription desc : descriptions) { - if(desc.getLanguage().getId().intValue()==language.getId().intValue()) { - description = desc; - } - } - - entry.put("name", description.getName()); - entry.put("sku", product.getSku()); - entry.put("available", product.isAvailable()); - resp.addDataEntry(entry); - - } - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/group/details/addItem.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> addItem(HttpServletRequest request, HttpServletResponse response) { - - String code = request.getParameter("code"); - String productId = request.getParameter("productId"); - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - Long lProductId = Long.parseLong(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lProductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - ProductRelationship relationship = new ProductRelationship(); - relationship.setActive(true); - relationship.setCode(code); - relationship.setStore(store); - relationship.setRelatedProduct(product); - - productRelationshipService.saveOrUpdate(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/group/details/removeItem.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeItem(HttpServletRequest request, HttpServletResponse response) { - - String code = request.getParameter("code"); - String productId = request.getParameter("productId"); - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - Long lproductId = Long.parseLong(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lproductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - ProductRelationship relationship = null; - List<ProductRelationship> relationships = productRelationshipService.getByGroup(store, code); - - for(ProductRelationship r : relationships) { - if(r.getRelatedProduct().getId().longValue()==lproductId.longValue()) { - relationship = r; - break; - } - } - - if(relationship==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(relationship.getStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - productRelationshipService.delete(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products-group", "catalogue-products-group"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/DigitalProductController.java+0 −184 removed@@ -1,184 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.file.DigitalProductService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.file.DigitalProduct; -import com.salesmanager.core.model.content.FileContentType; -import com.salesmanager.core.model.content.InputContentFile; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.digital.ProductFiles; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.io.ByteArrayInputStream; -import java.util.*; - -@Controller -public class DigitalProductController { - - private static final Logger LOGGER = LoggerFactory.getLogger(DigitalProductController.class); - - @Inject - private ProductService productService; - - @Inject - private DigitalProductService digitalProductService; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value={"/admin/products/digitalProduct.html"}, method=RequestMethod.GET) - public String getDigitalProduct(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productId); - - if(product==null || product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - model.addAttribute("product", product); - - DigitalProduct digitalProduct = digitalProductService.getByProduct(store, product); - - model.addAttribute("digitalProduct", digitalProduct); - return ControllerConstants.Tiles.Product.digitalProduct; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/saveDigitalProduct.html", method=RequestMethod.POST) - public String saveFile(@ModelAttribute(value="productFiles") @Valid final ProductFiles productFiles, final BindingResult bindingResult,final Model model, final HttpServletRequest request) throws Exception{ - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productFiles.getProduct().getId()); - DigitalProduct digitalProduct = new DigitalProduct(); - if(product==null || product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - digitalProduct.setProduct(product); - model.addAttribute("product", product); - model.addAttribute("digitalProduct", digitalProduct); - - if (bindingResult.hasErrors()) { - LOGGER.info( "Found {} Validation errors", bindingResult.getErrorCount()); - return ControllerConstants.Tiles.Product.digitalProduct; - } - - - final List<InputContentFile> contentFilesList=new ArrayList<InputContentFile>(); - if(CollectionUtils.isNotEmpty( productFiles.getFile() )){ - LOGGER.info("Saving {} product files for merchant {}",productFiles.getFile().size(),store.getId()); - for(final MultipartFile multipartFile:productFiles.getFile()){ - if(!multipartFile.isEmpty()){ - ByteArrayInputStream inputStream = new ByteArrayInputStream( multipartFile.getBytes() ); - InputContentFile cmsContentImage = new InputContentFile(); - cmsContentImage.setFileName(multipartFile.getOriginalFilename() ); - cmsContentImage.setFileContentType( FileContentType.PRODUCT_DIGITAL ); - cmsContentImage.setFile( inputStream ); - contentFilesList.add( cmsContentImage); - } - } - - if(CollectionUtils.isNotEmpty( contentFilesList )){ - - digitalProduct.setProductFileName(contentFilesList.get(0).getFileName()); - digitalProductService.addProductFile(product, digitalProduct, contentFilesList.get(0)); - - //refresh digital product - digitalProduct = digitalProductService.getByProduct(store, product); - - } - } - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Product.digitalProduct; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/removeDigitalProduct.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeFile(@RequestParam("fileId") long fileId, HttpServletRequest request, HttpServletResponse response, Locale locale) { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - DigitalProduct digitalProduct = digitalProductService.getById(fileId); - - //validate store - if(digitalProduct==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Product product = digitalProduct.getProduct(); - if(product.getMerchantStore().getId().intValue()!= store.getId().intValue()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - digitalProductService.delete(digitalProduct); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/FeaturedItemsController.java+0 −275 removed@@ -1,275 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.relationship.ProductRelationshipService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationship; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationshipType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -@Controller -public class FeaturedItemsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(FeaturedItemsController.class); - - @Inject - CategoryService categoryService; - - @Inject - ProductService productService; - - @Inject - ProductRelationshipService productRelationshipService; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/featured/list.html", method=RequestMethod.GET) - public String displayFeaturedItems(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Category> categories = categoryService.listByStore(store,language); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("categories", readableCategories); - return "admin-catalogue-featured"; - - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/featured/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProducts(HttpServletRequest request, HttpServletResponse response) { - - - AjaxResponse resp = new AjaxResponse(); - - try { - - - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - List<ProductRelationship> relationships = productRelationshipService.getByType(store, ProductRelationshipType.FEATURED_ITEM, language); - - for(ProductRelationship relationship : relationships) { - - Product product = relationship.getRelatedProduct(); - Map entry = new HashMap(); - entry.put("relationshipId", relationship.getId()); - entry.put("productId", product.getId()); - - ProductDescription description = product.getDescriptions().iterator().next(); - Set<ProductDescription> descriptions = product.getDescriptions(); - for(ProductDescription desc : descriptions) { - if(desc.getLanguage().getId().intValue()==language.getId().intValue()) { - description = desc; - } - } - - entry.put("name", description.getName()); - entry.put("sku", product.getSku()); - entry.put("available", product.isAvailable()); - resp.addDataEntry(entry); - - } - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/featured/addItem.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> addItem(HttpServletRequest request, HttpServletResponse response) { - - String productId = request.getParameter("productId"); - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - - Long lProductId = Long.parseLong(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lProductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - ProductRelationship relationship = new ProductRelationship(); - relationship.setActive(true); - relationship.setCode(ProductRelationshipType.FEATURED_ITEM.name()); - relationship.setStore(store); - relationship.setRelatedProduct(product); - - productRelationshipService.saveOrUpdate(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/featured/removeItem.html&removeEntity=FEATURED", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeItem(HttpServletRequest request, HttpServletResponse response) { - - String productId = request.getParameter("productId"); - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - Long lproductId = Long.parseLong(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lproductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - ProductRelationship relationship = null; - List<ProductRelationship> relationships = productRelationshipService.getByType(store, ProductRelationshipType.FEATURED_ITEM); - - for(ProductRelationship r : relationships) { - if(r.getRelatedProduct().getId().longValue()==lproductId.longValue()) { - relationship = r; - } - } - - if(relationship==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(relationship.getStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - productRelationshipService.delete(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products-group", "catalogue-products-group"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ManufacturerController.java+0 −501 removed@@ -1,501 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.manufacturer.ManufacturerService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.CoreConfiguration; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer; -import com.salesmanager.core.model.catalog.product.manufacturer.ManufacturerDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.controller.customers.CustomerController; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.imageio.ImageIO; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.awt.image.BufferedImage; -import java.util.*; - -@Controller -public class ManufacturerController { - - @Inject - private LanguageService languageService; - - @Inject - private ManufacturerService manufacturerService; - - @Inject - LabelUtils messages; - - @Inject - private CoreConfiguration configuration; - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class); - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/list.html", method=RequestMethod.GET) - public String getManufacturers(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - - return ControllerConstants.Tiles.Product.manufacturerList; - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/create.html", method=RequestMethod.GET) - public String createManufacturer( Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - return displayManufacturer(null,model,request,response); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/edit.html", method=RequestMethod.GET) - public String editManufacturer(@RequestParam("id") long manufacturerId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - return displayManufacturer(manufacturerId,model,request,response); - } - - private String displayManufacturer(Long manufacturerId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - //display menu - setMenu(model,request); - - //List<Language> languages = languageService.getLanguages(); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - List<Language> languages = store.getLanguages(); - - - com.salesmanager.shop.admin.model.catalog.Manufacturer manufacturer = new com.salesmanager.shop.admin.model.catalog.Manufacturer(); - List<ManufacturerDescription> descriptions = new ArrayList<ManufacturerDescription>(); - - - if( manufacturerId!=null && manufacturerId.longValue()!=0) { //edit mode - - Manufacturer dbManufacturer = new Manufacturer(); - dbManufacturer = manufacturerService.getById( manufacturerId ); - - if(dbManufacturer==null) { - return ControllerConstants.Tiles.Product.manufacturerList; - } - - if(dbManufacturer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return ControllerConstants.Tiles.Product.manufacturerList; - } - - Set<ManufacturerDescription> manufacturerDescriptions = dbManufacturer.getDescriptions(); - - - for(Language l : languages) { - - ManufacturerDescription manufDescription = null; - if(manufacturerDescriptions!=null) { - - for(ManufacturerDescription desc : manufacturerDescriptions) { - String code = desc.getLanguage().getCode(); - if(code.equals(l.getCode())) { - manufDescription = desc; - } - - } - - } - - if(manufDescription==null) { - manufDescription = new ManufacturerDescription(); - manufDescription.setLanguage(l); - } - - manufacturer.getDescriptions().add(manufDescription); - - } - - manufacturer.setManufacturer( dbManufacturer ); - - manufacturer.setCode(dbManufacturer.getCode()); - manufacturer.setOrder( dbManufacturer.getOrder() ); - - } else { // Create mode - - Manufacturer manufacturerTmp = new Manufacturer(); - manufacturer.setManufacturer( manufacturerTmp ); - - for(Language l : languages) {// for each store language - - ManufacturerDescription manufacturerDesc = new ManufacturerDescription(); - manufacturerDesc.setLanguage(l); - descriptions.add( manufacturerDesc ); - manufacturer.setDescriptions(descriptions); - - } - } - - model.addAttribute("languages",languages); - model.addAttribute("manufacturer", manufacturer); - - return ControllerConstants.Tiles.Product.manufacturerDetails; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/save.html", method=RequestMethod.POST) - public String saveManufacturer( @Valid @ModelAttribute("manufacturer") com.salesmanager.shop.admin.model.catalog.Manufacturer manufacturer, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - //save or edit a manufacturer - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - List<Language> languages = languageService.getLanguages(); - - if(manufacturer.getDescriptions()!=null && manufacturer.getDescriptions().size()>0) { - - for(ManufacturerDescription description : manufacturer.getDescriptions()) { - - //validate Url Clicked -/* if ( description.getUrlClicked() != null && !description.getUrlClicked().toString().isEmpty()) { - try{ - Integer.parseInt( description.getUrlClicked().toString() ); - - } catch (Exception e) { - - ObjectError error = new ObjectError("descriptions[${counter.index}].urlClicked","URL Clicked must be a number"); - result.addError(error); - } - }*/ - } - } - - - //validate image - if(manufacturer.getImage()!=null && !manufacturer.getImage().isEmpty()) { - - try { - - String maxHeight = configuration.getProperty("PRODUCT_IMAGE_MAX_HEIGHT_SIZE"); - String maxWidth = configuration.getProperty("PRODUCT_IMAGE_MAX_WIDTH_SIZE"); - String maxSize = configuration.getProperty("PRODUCT_IMAGE_MAX_SIZE"); - - BufferedImage image = ImageIO.read(manufacturer.getImage().getInputStream()); - - if(!StringUtils.isBlank(maxHeight)) { - - int maxImageHeight = Integer.parseInt(maxHeight); - if(image.getHeight()>maxImageHeight) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.height", locale) + " {"+maxHeight+"}"); - result.addError(error); - } - } - - if(!StringUtils.isBlank(maxWidth)) { - - int maxImageWidth = Integer.parseInt(maxWidth); - if(image.getWidth()>maxImageWidth) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.width", locale) + " {"+maxWidth+"}"); - result.addError(error); - } - } - - if(!StringUtils.isBlank(maxSize)) { - - int maxImageSize = Integer.parseInt(maxSize); - if(manufacturer.getImage().getSize()>maxImageSize) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.size", locale) + " {"+maxSize+"}"); - result.addError(error); - } - } - - } catch (Exception e) { - LOGGER.error("Cannot validate manufacturer image", e); - } - - } - - if (result.hasErrors()) { - model.addAttribute("languages",languages); - return ControllerConstants.Tiles.Product.manufacturerDetails; - } - - Manufacturer newManufacturer = manufacturer.getManufacturer(); - - if ( manufacturer.getManufacturer().getId() !=null && manufacturer.getManufacturer().getId() > 0 ){ - - newManufacturer = manufacturerService.getById( manufacturer.getManufacturer().getId() ); - - if(newManufacturer.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return ControllerConstants.Tiles.Product.manufacturerList; - } - - } - -// for(ManufacturerImage image : manufacturer.getImages()) { -// if(image.isDefaultImage()) { -// manufacturer.setProductImage(image); -// } -// } - - Set<ManufacturerDescription> descriptions = new HashSet<ManufacturerDescription>(); - if(manufacturer.getDescriptions()!=null && manufacturer.getDescriptions().size()>0) { - - for(ManufacturerDescription desc : manufacturer.getDescriptions()) { - - desc.setManufacturer(newManufacturer); - descriptions.add(desc); - } - } - newManufacturer.setDescriptions(descriptions ); - newManufacturer.setOrder( manufacturer.getOrder() ); - newManufacturer.setMerchantStore(store); - newManufacturer.setCode(manufacturer.getCode()); - - -// if(manufacturer.getManufacturerImage()!=null && manufacturer.getManufacturerImage().getId() == null) { -// newManufacturer.setProductImage(null); -// } - - - - if(manufacturer.getImage()!=null && !manufacturer.getImage().isEmpty()) { -// -// String imageName = manufacturer.getImage().getOriginalFilename(); -// -// ManufacturerImage manufacturerImage = new ManufacturerImage(); -// manufacturerImage.setDefaultImage(true); -// manufacturerImage.setImage(manufacturer.getImage().getInputStream()); -// manufacturerImage.setManufacturerImage(imageName); -// -// List<ManufacturerImageDescription> imagesDescriptions = new ArrayList<ManufacturerImageDescription>(); -// -// for(Language l : languages) { -// -// ManufacturerImageDescription imageDescription = new ManufacturerImageDescription(); -// imageDescription.setName(imageName); -// imageDescription.setLanguage(l); -// imageDescription.setManufacturerImage(productImage); -// imagesDescriptions.add(imageDescription); -// -// } -// -// manufacturerImage.setDescriptions(imagesDescriptions); -// manufacturerImage.setProduct(newManufacturer); -// -// newManufacturer.getImages().add(manufacturerImage); -// -// manufacturerService.saveOrUpdate(newManufacturer); -// -// //manufacturer displayed -// manufacturer.setProductImage(manufacturerImage); - - - } else { - - manufacturerService.saveOrUpdate(newManufacturer); - } - - model.addAttribute("manufacturer", manufacturer); - model.addAttribute("languages",languages); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Product.manufacturerDetails; - - } - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageManufacturers(HttpServletRequest request, HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - try { - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Manufacturer> manufacturers = null; - manufacturers = manufacturerService.listByStore(store, language); - - - for(Manufacturer manufacturer : manufacturers) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("id", manufacturer.getId()); - - ManufacturerDescription description = manufacturer.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - entry.put("code", manufacturer.getCode()); - entry.put("order", manufacturer.getOrder()); - resp.addDataEntry(entry); - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging Manufacturers", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/manufacturer/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteManufacturer(HttpServletRequest request, HttpServletResponse response, Locale locale) { - Long sid = Long.valueOf(request.getParameter("id") ); - - - AjaxResponse resp = new AjaxResponse(); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try{ - Manufacturer delManufacturer = manufacturerService.getById( sid ); - if(delManufacturer==null || delManufacturer.getMerchantStore().getId().intValue() != store.getId().intValue()) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - int count = manufacturerService.getCountManufAttachedProducts( delManufacturer ).intValue(); - //IF already attached to products it can't be deleted - if ( count > 0 ){ - resp.setStatusMessage(messages.getMessage("message.product.association", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - manufacturerService.delete( delManufacturer ); - - resp.setStatusMessage(messages.getMessage("message.success", locale)); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - LOGGER.error("Cannot delete manufacturer.", e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/manufacturer/checkCode.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkCode(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String code = request.getParameter("code"); - String id = request.getParameter("id"); - - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - - if(StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - Manufacturer manufacturer = manufacturerService.getByCode(store, code); - - if(manufacturer!=null && StringUtils.isBlank(id)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - if(manufacturer!=null && !StringUtils.isBlank(id)) { - try { - Long lid = Long.parseLong(id); - - if(manufacturer.getCode().equals(code) && manufacturer.getId().longValue()==lid) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - } catch (Exception e) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - } - - - - - - - - - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while getting manufacturer", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("manufacturer-list", "manufacturer-list"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/OptionsController.java+0 −340 removed@@ -1,340 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.attribute.ProductOption; -import com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class OptionsController { - - @Inject - LanguageService languageService; - - @Inject - ProductOptionService productOptionService; - - @Inject - LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(OptionsController.class); - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/options.html", method=RequestMethod.GET) - public String displayOptions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - - - - return "catalogue-options-list"; - - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/editOption.html", method=RequestMethod.GET) - public String displayOptionEdit(@RequestParam("id") long optionId, HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(optionId,request,response,model,locale); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/createOption.html", method=RequestMethod.GET) - public String displayOption(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(null,request,response,model,locale); - } - - private String displayOption(Long optionId, HttpServletRequest request, HttpServletResponse response,Model model,Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = store.getLanguages(); - - Set<ProductOptionDescription> descriptions = new HashSet<ProductOptionDescription>(); - - ProductOption option = new ProductOption(); - - if(optionId!=null && optionId!=0) {//edit mode - - - option = productOptionService.getById(store, optionId); - - - if(option==null) { - return "redirect:/admin/options/options.html"; - } - - Set<ProductOptionDescription> optionDescriptions = option.getDescriptions(); - - - - for(Language l : languages) { - - ProductOptionDescription optionDescription = null; - - if(optionDescriptions!=null) { - - for(ProductOptionDescription description : optionDescriptions) { - - String code = description.getLanguage().getCode(); - if(code.equals(l.getCode())) { - optionDescription = description; - } - - } - - } - - if(optionDescription==null) { - optionDescription = new ProductOptionDescription(); - optionDescription.setLanguage(l); - } - - descriptions.add(optionDescription); - - } - - } else { - - for(Language l : languages) { - - ProductOptionDescription desc = new ProductOptionDescription(); - desc.setLanguage(l); - descriptions.add(desc); - - } - - } - - - option.setDescriptions(descriptions); - model.addAttribute("option", option); - return "catalogue-options-details"; - - - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/save.html", method=RequestMethod.POST) - public String saveOption(@Valid @ModelAttribute("option") ProductOption option, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - ProductOption dbEntity = null; - - if(option.getId() != null && option.getId() >0) { //edit entry - //get from DB - dbEntity = productOptionService.getById(option.getId()); - - if(dbEntity==null) { - return "redirect:/admin/options/options.html"; - } - } - - //validate if it contains an existing code - ProductOption byCode = productOptionService.getByCode(store, option.getCode()); - if(byCode!=null) { - ObjectError error = new ObjectError("code",messages.getMessage("message.code.exist", locale)); - result.addError(error); - } - - - Map<String,Language> langs = languageService.getLanguagesMap(); - - - List<ProductOptionDescription> descriptions = option.getDescriptionsList(); - - if(descriptions!=null) { - - for(ProductOptionDescription description : descriptions) { - - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - description.setLanguage(l); - description.setProductOption(option); - - } - - } - - option.setDescriptions(new HashSet<ProductOptionDescription>(descriptions)); - option.setMerchantStore(store); - - - if (result.hasErrors()) { - return "catalogue-options-details"; - } - - - - - productOptionService.saveOrUpdate(option); - - - - - model.addAttribute("success","success"); - return "catalogue-options-details"; - } - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOptions(HttpServletRequest request, HttpServletResponse response) { - - String optionName = request.getParameter("name"); - - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<ProductOption> options = null; - - if(!StringUtils.isBlank(optionName)) { - - options = productOptionService.getByName(store, optionName, language); - - } else { - - options = productOptionService.listByStore(store, language); - - } - - - - for(ProductOption option : options) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("optionId", option.getId()); - entry.put("display", option.isReadOnly()); - ProductOptionDescription description = option.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - entry.put("type", option.getProductOptionType());//TODO resolve with option type label - resp.addDataEntry(entry); - - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging options", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-options", "catalogue-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - @RequestMapping(value="/admin/options/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteOption(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("optionId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(sid); - - ProductOption entity = productOptionService.getById(id); - - if(entity==null || entity.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - productOptionService.delete(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting option", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/OptionsValueController.java+0 −436 removed@@ -1,436 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionValueService; -import com.salesmanager.core.business.services.content.ContentService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue; -import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription; -import com.salesmanager.core.model.content.FileContentType; -import com.salesmanager.core.model.content.InputContentFile; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.ImageFilePath; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -import java.io.InputStream; -import java.util.*; - -@Controller -public class OptionsValueController { - - @Inject - LanguageService languageService; - - - @Inject - ProductOptionValueService productOptionValueService; - - @Inject - LabelUtils messages; - - @Inject - private ContentService contentService; - - @Inject - @Qualifier("img") - private ImageFilePath imageUtils; - - private static final Logger LOGGER = LoggerFactory.getLogger(OptionsValueController.class); - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/optionvalues.html", method=RequestMethod.GET) - public String displayOptions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - //subsequent ajax call - - - return "catalogue-optionsvalues-list"; - - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/editOptionValue.html", method=RequestMethod.GET) - public String displayOptionEdit(@RequestParam("id") long optionId, HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(optionId,request,response,model,locale); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/createOptionValue.html", method=RequestMethod.GET) - public String displayOption(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) throws Exception { - return displayOption(null,request,response,model,locale); - } - - private String displayOption(Long optionId, HttpServletRequest request, HttpServletResponse response,Model model,Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Language> languages = store.getLanguages(); - - Set<ProductOptionValueDescription> descriptions = new HashSet<ProductOptionValueDescription>(); - - ProductOptionValue option = new ProductOptionValue(); - - if(optionId!=null && optionId!=0) {//edit mode - - - option = productOptionValueService.getById(store, optionId); - - if(option==null) { - return "redirect:/admin/options/optionvalues.html"; - } - - Set<ProductOptionValueDescription> optionDescriptions = option.getDescriptions(); - - - - for(Language l : languages) { - - ProductOptionValueDescription optionDescription = null; - - if(optionDescriptions!=null) { - - for(ProductOptionValueDescription description : optionDescriptions) { - - String code = description.getLanguage().getCode(); - if(code.equals(l.getCode())) { - optionDescription = description; - } - - } - - } - - if(optionDescription==null) { - optionDescription = new ProductOptionValueDescription(); - optionDescription.setLanguage(l); - } - - descriptions.add(optionDescription); - - } - - } else { - - for(Language l : languages) { - - ProductOptionValueDescription desc = new ProductOptionValueDescription(); - desc.setLanguage(l); - descriptions.add(desc); - - } - - option.setDescriptions(descriptions); - - } - - - - model.addAttribute("optionValue", option); - return "catalogue-optionsvalues-details"; - - - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/options/saveOptionValue.html", method=RequestMethod.POST) - public String saveOption(@Valid @ModelAttribute("optionValue") ProductOptionValue optionValue, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - ProductOptionValue dbEntity = null; - - if(optionValue.getId() != null && optionValue.getId() >0) { //edit entry - - //get from DB - dbEntity = productOptionValueService.getById(store,optionValue.getId()); - - if(dbEntity==null) { - return "redirect:/admin/options/optionsvalues.html"; - } - - - } else { - - //validate if it contains an existing code - ProductOptionValue byCode = productOptionValueService.getByCode(store, optionValue.getCode()); - if(byCode!=null) { - ObjectError error = new ObjectError("code",messages.getMessage("message.code.exist", locale)); - result.addError(error); - } - - } - - - - - Map<String,Language> langs = languageService.getLanguagesMap(); - - - List<ProductOptionValueDescription> descriptions = optionValue.getDescriptionsList(); - if(descriptions!=null && descriptions.size()>0) { - - Set<ProductOptionValueDescription> descs = new HashSet<ProductOptionValueDescription>(); - - //if(descs==null || descs.size()==0) { - - //} else { - - optionValue.setDescriptions(descs); - for(ProductOptionValueDescription description : descriptions) { - - if(StringUtils.isBlank(description.getName())) { - ObjectError error = new ObjectError("name",messages.getMessage("message.name.required", locale)); - result.addError(error); - } else { - - - String code = description.getLanguage().getCode(); - Language l = langs.get(code); - description.setLanguage(l); - description.setProductOptionValue(optionValue); - descs.add(description); - - } - - - } - - - } else { - - ObjectError error = new ObjectError("name",messages.getMessage("message.name.required", locale)); - result.addError(error); - - } - - - optionValue.setMerchantStore(store); - - - if (result.hasErrors()) { - return "catalogue-optionsvalues-details"; - } - - - if(optionValue.getImage()!=null && !optionValue.getImage().isEmpty()) { - - String imageName = optionValue.getImage().getOriginalFilename(); - InputStream inputStream = optionValue.getImage().getInputStream(); - InputContentFile cmsContentImage = new InputContentFile(); - cmsContentImage.setFileName(imageName); - cmsContentImage.setMimeType( optionValue.getImage().getContentType() ); - cmsContentImage.setFile( inputStream ); - contentService.addOptionImage(store.getCode(), cmsContentImage); - - optionValue.setProductOptionValueImage(imageName); - - } - - productOptionValueService.saveOrUpdate(optionValue); - - - - - model.addAttribute("success","success"); - return "catalogue-optionsvalues-details"; - } - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/optionsvalues/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageOptions(HttpServletRequest request, HttpServletResponse response) { - - String optionName = request.getParameter("name"); - - - AjaxResponse resp = new AjaxResponse(); - - - try { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<ProductOptionValue> options = null; - - if(!StringUtils.isBlank(optionName)) { - - //productOptionValueService.getByName(store, optionName, language); - - } else { - - options = productOptionValueService.listByStore(store, language); - - } - - - - for(ProductOptionValue option : options) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("optionValueId", option.getId()); - - ProductOptionValueDescription description = option.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - //entry.put("image", new StringBuilder().append(store.getCode()).append("/").append(FileContentType.PROPERTY.name()).append("/").append(option.getProductOptionValueImage()).toString()); - entry.put("image", imageUtils.buildProductPropertyImageUtils(store, option.getProductOptionValueImage())); - resp.addDataEntry(entry); - - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - - - } catch (Exception e) { - LOGGER.error("Error while paging options", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/optionsvalues/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteOptionValue(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("optionValueId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(sid); - - ProductOptionValue entity = productOptionValueService.getById(store, id); - - if(entity==null || entity.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - productOptionValueService.delete(entity); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting option", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/optionsvalues/removeImage.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeImage(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String optionValueId = request.getParameter("optionId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(optionValueId); - - ProductOptionValue optionValue = productOptionValueService.getById(store, id); - - contentService.removeFile(store.getCode(), FileContentType.PROPERTY, optionValue.getProductOptionValueImage()); - - store.setStoreLogo(null); - optionValue.setProductOptionValueImage(null); - productOptionValueService.update(optionValue); - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-options", "catalogue-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductAttributeController.java+0 −530 removed@@ -1,530 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService; -import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionService; -import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionValueService; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.attribute.*; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.math.BigDecimal; -import java.util.*; - -@Controller -public class ProductAttributeController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductAttributeController.class); - - private final static String TEXT_OPTION = "text"; - - @Inject - private ProductAttributeService productAttributeService; - - @Inject - private ProductService productService; - - @Inject - private ProductPriceUtils priceUtil; - - @Inject - ProductOptionService productOptionService; - - @Inject - ProductOptionValueService productOptionValueService; - - @Inject - LabelUtils messages; - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/attributes/list.html", method=RequestMethod.GET) - public String displayProductAttributes(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - model.addAttribute("product",product); - return "admin-products-attributes"; - - } - - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/attributes/page.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageAttributes(HttpServletRequest request, HttpServletResponse response) { - - //String attribute = request.getParameter("attribute"); - String sProductId = request.getParameter("productId"); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - - product = productService.getById(productId); - - - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //List<ProductAttribute> attributes = productAttributeService.getByProductId(store, product, language); - - for(ProductAttribute attr : product.getAttributes()) { - - Map entry = new HashMap(); - entry.put("attributeId", attr.getId()); - - List<ProductOptionDescription> optionsDescriptions = attr.getProductOption().getDescriptionsSettoList(); - ProductOptionDescription optionDescription = attr.getProductOption().getDescriptionsSettoList().get(0); - for(ProductOptionDescription desc : optionsDescriptions) { - if(desc.getLanguage().getId().intValue()==language.getId().intValue()) { - optionDescription = desc; - } - } - - List<ProductOptionValueDescription> optionValuesDescriptions = attr.getProductOptionValue().getDescriptionsSettoList(); - ProductOptionValueDescription optionValueDescription = attr.getProductOptionValue().getDescriptionsSettoList().get(0); - for(ProductOptionValueDescription desc : optionValuesDescriptions) { - if(desc.getLanguage().getId().intValue()==language.getId().intValue()) { - optionValueDescription = desc; - } - } - entry.put("attribute", optionDescription.getName()); - entry.put("display", attr.getAttributeDisplayOnly()); - entry.put("value", optionValueDescription.getName()); - entry.put("order", attr.getProductOptionSortOrder()); - entry.put("price", priceUtil.getAdminFormatedAmountWithCurrency(store,attr.getProductAttributePrice())); - - resp.addDataEntry(entry); - - - - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/attributes/editAttribute.html", method=RequestMethod.GET) - public String displayAttributeEdit(@RequestParam("productId") Long productId, @RequestParam("id") Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayAttribute(productId, id,model,request,response); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/attribute/createAttribute.html", method=RequestMethod.GET) - public String displayAttributeCreate(@RequestParam("productId") Long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayAttribute(productId, null,model,request,response); - - } - - private String displayAttribute(Long productId, Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - //display menu - setMenu(model,request); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - //get product - Product product = productService.getById(productId); - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - List<Language> languages = store.getLanguages(); - - ProductAttribute attribute = null; - - //get Options - List<ProductOption> options = productOptionService.listByStore(store, language); - //get OptionsValues - List<ProductOptionValue> optionsValues = productOptionValueService.listByStoreNoReadOnly(store, language); - - if(id!=null && id.intValue()!=0) {//edit mode - - attribute = productAttributeService.getById(id); - attribute.setAttributePrice(priceUtil.getAdminFormatedAmount(store, attribute.getProductAttributePrice())); - attribute.setAttributeAdditionalWeight(String.valueOf(attribute.getProductAttributeWeight().intValue())); - attribute.setAttributeSortOrder(String.valueOf(attribute.getProductOptionSortOrder())); - - } else { - - attribute = new ProductAttribute(); - attribute.setProduct(product); - ProductOptionValue value = new ProductOptionValue(); - Set<ProductOptionValueDescription> descriptions = new HashSet<ProductOptionValueDescription>(); - for(Language l : languages) { - - ProductOptionValueDescription desc = new ProductOptionValueDescription(); - desc.setLanguage(l); - descriptions.add(desc); - - - } - - value.setDescriptions(descriptions); - attribute.setProductOptionValue(value); - } - - model.addAttribute("optionsValues",optionsValues); - model.addAttribute("options",options); - model.addAttribute("attribute",attribute); - model.addAttribute("product",product); - return "admin-products-attribute-details"; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/attributes/attribute/save.html", method=RequestMethod.POST) - public String saveAttribute(@Valid @ModelAttribute("attribute") ProductAttribute attribute, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - Product product = productService.getById(attribute.getProduct().getId()); - - model.addAttribute("product",product); - - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - - //get Options - List<ProductOption> options = productOptionService.listByStore(store, language); - //get OptionsValues - List<ProductOptionValue> optionsValues = productOptionValueService.listByStoreNoReadOnly(store, language); - - model.addAttribute("optionsValues",optionsValues); - model.addAttribute("options",options); - - ProductAttribute dbEntity = null; - - if(attribute.getId() != null && attribute.getId() >0) { //edit entry - - //get from DB - dbEntity = productAttributeService.getById(attribute.getId()); - - if(dbEntity==null) { - return "redirect:/admin/products/attributes/list.html"; - } - - if(dbEntity.getProductOption().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/attributes/list.html"; - } - } - - //validate price - BigDecimal submitedPrice = null; - try { - submitedPrice = priceUtil.getAmount(attribute.getAttributePrice()); - attribute.setProductAttributePrice(submitedPrice); - } catch (Exception e) { - ObjectError error = new ObjectError("attributePrice",messages.getMessage("NotEmpty.product.productPrice", locale)); - result.addError(error); - } - - //validate sort order - try { - Integer sortOrder = Integer.parseInt(attribute.getAttributeSortOrder()); - attribute.setProductOptionSortOrder(sortOrder); - } catch(Exception e) { - ObjectError error = new ObjectError("attributeSortOrder",messages.getMessage("message.number.invalid", locale)); - result.addError(error); - } - - //validate weight - try { - Integer weight = Integer.parseInt(attribute.getAttributeAdditionalWeight()); - attribute.setProductAttributeWeight(new BigDecimal(weight)); - } catch(Exception e) { - ObjectError error = new ObjectError("attributeAdditionalWeight",messages.getMessage("message.number.invalid", locale)); - result.addError(error); - } - - if(attribute.getProductOption()==null) { - ObjectError error = new ObjectError("productOption.id",messages.getMessage("message.productoption.required", locale)); - result.addError(error); - return "admin-products-attribute-details"; - } - - - //check type - ProductOption option = attribute.getProductOption(); - option = productOptionService.getById(option.getId()); - attribute.setProductOption(option); - - if(option.getProductOptionType().equals(TEXT_OPTION)) { - - if(dbEntity!=null && dbEntity.getProductOption().getProductOptionType().equals(TEXT_OPTION)) {//bcz it is overwrited by hidden product option value list - if(dbEntity.getProductOptionValue()!=null) { - ProductOptionValue optVal = dbEntity.getProductOptionValue(); - List<ProductOptionValueDescription> descriptions = attribute.getProductOptionValue().getDescriptionsList(); - Set<ProductOptionValueDescription> descriptionsSet = new HashSet<ProductOptionValueDescription>(); - for(ProductOptionValueDescription description : descriptions) { - description.setProductOptionValue(optVal); - description.setName(description.getDescription().length()<15 ? description.getDescription() : description.getDescription().substring(0,15)); - descriptionsSet.add(description); - } - optVal.setDescriptions(descriptionsSet); - optVal.setProductOptionDisplayOnly(true); - productOptionValueService.saveOrUpdate(optVal); - attribute.setProductOptionValue(optVal); - } - } else {//create a new value - - //create new option value - List<ProductOptionValueDescription> descriptions = attribute.getProductOptionValue().getDescriptionsList(); - Set<ProductOptionValueDescription> newDescriptions = new HashSet<ProductOptionValueDescription>(); - ProductOptionValue newValue = new ProductOptionValue(); - for(ProductOptionValueDescription description : descriptions) { - ProductOptionValueDescription optionValueDescription = new ProductOptionValueDescription(); - optionValueDescription.setAuditSection(description.getAuditSection()); - optionValueDescription.setLanguage(description.getLanguage()); - optionValueDescription.setName(description.getDescription().length()<15 ? description.getDescription() : description.getDescription().substring(0,15)); - optionValueDescription.setLanguage(description.getLanguage()); - optionValueDescription.setDescription(description.getDescription()); - optionValueDescription.setProductOptionValue(newValue); - newDescriptions.add(optionValueDescription); - } - - //code generation - String code = RandomStringUtils.randomAlphanumeric(10).toUpperCase(); - newValue.setCode(code); - newValue.setMerchantStore(store); - newValue.setProductOptionValueSortOrder(attribute.getProductOptionValue().getProductOptionValueSortOrder()); - newValue.setDescriptions(newDescriptions); - newValue.setProductOptionDisplayOnly(true); - productOptionValueService.save(newValue); - attribute.setProductOptionValue(newValue); - attribute.setAttributeDisplayOnly(true); - - } - - } - - - - if(attribute.getProductOptionValue().getId()==null) { - ObjectError error = new ObjectError("productOptionValue.id",messages.getMessage("message.productoptionvalue.required", locale)); - result.addError(error); - } - - model.addAttribute("attribute",attribute); - - - if (result.hasErrors()) { - return "admin-products-attribute-details"; - } - - productAttributeService.saveOrUpdate(attribute); - - model.addAttribute("success","success"); - return "admin-products-attribute-details"; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/attributes/attribute/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteProductPrice(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sAttributeid = request.getParameter("attributeId"); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - Long attributeId = Long.parseLong(sAttributeid); - ProductAttribute attribute = productAttributeService.getById(attributeId); - - - if(attribute==null || attribute.getProduct().getMerchantStore().getId().intValue()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - productAttributeService.delete(attribute); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting product price", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/attributes/getAttributeType.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkAttributeType(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - String sOptionId = request.getParameter("optionId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - Long prodoptionId; - ProductOption productOption = null; - - try { - prodoptionId = Long.parseLong(sOptionId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product Option id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - - productOption = productOptionService.getById(prodoptionId); - - if(productOption==null) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(productOption.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - Map entry = new HashMap(); - - - - entry.put("type", productOption.getProductOptionType()); - resp.addDataEntry(entry); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductController.java+0 −1055 removed@@ -1,1055 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.image.ProductImageService; -import com.salesmanager.core.business.services.catalog.product.manufacturer.ManufacturerService; -import com.salesmanager.core.business.services.catalog.product.type.ProductTypeService; -import com.salesmanager.core.business.services.tax.TaxClassService; -import com.salesmanager.core.business.utils.CoreConfiguration; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.category.CategoryDescription; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; -import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.catalog.product.image.ProductImage; -import com.salesmanager.core.model.catalog.product.image.ProductImageDescription; -import com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer; -import com.salesmanager.core.model.catalog.product.price.ProductPrice; -import com.salesmanager.core.model.catalog.product.price.ProductPriceDescription; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationship; -import com.salesmanager.core.model.catalog.product.type.ProductType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.tax.taxclass.TaxClass; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.imageio.ImageIO; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.awt.image.BufferedImage; -import java.math.BigDecimal; -import java.util.*; - -@Controller -public class ProductController { - - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class); - - - - @Inject - private ProductService productService; - - @Inject - private ManufacturerService manufacturerService; - - @Inject - private ProductTypeService productTypeService; - - @Inject - private ProductImageService productImageService; - - @Inject - private TaxClassService taxClassService; - - @Inject - private ProductPriceUtils priceUtil; - - @Inject - LabelUtils messages; - - @Inject - private CoreConfiguration configuration; - - @Inject - CategoryService categoryService; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/editProduct.html", method=RequestMethod.GET) - public String displayProductEdit(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayProduct(productId,model,request,response); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/viewEditProduct.html", method=RequestMethod.GET) - public String displayProductEdit(@RequestParam("sku") String sku, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - Language language = (Language)request.getAttribute("LANGUAGE"); - Product dbProduct = productService.getByCode(sku, language); - - long productId = -1;//non existent - if(dbProduct!=null) { - productId = dbProduct.getId(); - } - - return displayProduct(productId,model,request,response); - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/createProduct.html", method=RequestMethod.GET) - public String displayProductCreate(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return displayProduct(null,model,request,response); - - } - - - - private String displayProduct(Long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - //display menu - setMenu(model,request); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - - List<Manufacturer> manufacturers = manufacturerService.listByStore(store, language); - - List<ProductType> productTypes = productTypeService.list(); - - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - List<Language> languages = store.getLanguages(); - - - - com.salesmanager.shop.admin.model.catalog.Product product = new com.salesmanager.shop.admin.model.catalog.Product(); - List<ProductDescription> descriptions = new ArrayList<ProductDescription>(); - - if(productId!=null && productId!=0) {//edit mode - - - Product dbProduct = productService.getById(productId); - - if(dbProduct==null || dbProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - product.setProduct(dbProduct); - Set<ProductDescription> productDescriptions = dbProduct.getDescriptions(); - - for(Language l : languages) { - - ProductDescription productDesc = null; - for(ProductDescription desc : productDescriptions) { - - Language lang = desc.getLanguage(); - if(lang.getCode().equals(l.getCode())) { - productDesc = desc; - } - - } - - if(productDesc==null) { - productDesc = new ProductDescription(); - productDesc.setLanguage(l); - } - - descriptions.add(productDesc); - - } - - for(ProductImage image : dbProduct.getImages()) { - if(image.isDefaultImage()) { - product.setProductImage(image); - break; - } - - } - - - ProductAvailability productAvailability = null; - ProductPrice productPrice = null; - - Set<ProductAvailability> availabilities = dbProduct.getAvailabilities(); - if(availabilities!=null && availabilities.size()>0) { - - for(ProductAvailability availability : availabilities) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) { - productAvailability = availability; - Set<ProductPrice> prices = availability.getPrices(); - for(ProductPrice price : prices) { - if(price.isDefaultPrice()) { - productPrice = price; - product.setProductPrice(priceUtil.getAdminFormatedAmount(store, productPrice.getProductPriceAmount())); - } - } - } - } - } - - if(productAvailability==null) { - productAvailability = new ProductAvailability(); - } - - if(productPrice==null) { - productPrice = new ProductPrice(); - } - - product.setAvailability(productAvailability); - product.setPrice(productPrice); - product.setDescriptions(descriptions); - - - product.setDateAvailable(DateUtil.formatDate(dbProduct.getDateAvailable())); - - - } else { - - - for(Language l : languages) { - - ProductDescription desc = new ProductDescription(); - desc.setLanguage(l); - descriptions.add(desc); - - } - - Product prod = new Product(); - - prod.setAvailable(true); - - ProductAvailability productAvailability = new ProductAvailability(); - ProductPrice price = new ProductPrice(); - product.setPrice(price); - product.setAvailability(productAvailability); - product.setProduct(prod); - product.setDescriptions(descriptions); - product.setDateAvailable(DateUtil.formatDate(new Date())); - - - } - - - - - - model.addAttribute("product",product); - model.addAttribute("manufacturers", manufacturers); - model.addAttribute("productTypes", productTypes); - model.addAttribute("taxClasses", taxClasses); - return "admin-products-edit"; - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/save.html", method=RequestMethod.POST) - public String saveProduct(@Valid @ModelAttribute("product") com.salesmanager.shop.admin.model.catalog.Product product, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Manufacturer> manufacturers = manufacturerService.listByStore(store, language); - - List<ProductType> productTypes = productTypeService.list(); - - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - List<Language> languages = store.getLanguages(); - - model.addAttribute("manufacturers", manufacturers); - model.addAttribute("productTypes", productTypes); - model.addAttribute("taxClasses", taxClasses); - - boolean productAlreadyExists = false; - if (!StringUtils.isBlank(product.getProduct().getSku()) && (product.getProduct().getId() == null || product.getProduct().getId().longValue() == 0)) { - try { - Product productByCode = productService.getByCode(product.getProduct().getSku(),language); - productAlreadyExists = productByCode != null; - - if(productAlreadyExists) throw new Exception(); - } catch (Exception e) { - ObjectError error = new ObjectError("product.sku",messages.getMessage("message.sku.exists", locale)); - result.addError(error); - } - } - - //validate price - BigDecimal submitedPrice = null; - try { - submitedPrice = priceUtil.getAmount(product.getProductPrice()); - } catch (Exception e) { - ObjectError error = new ObjectError("productPrice",messages.getMessage("NotEmpty.product.productPrice", locale)); - result.addError(error); - } - Date date = new Date(); - if(!StringUtils.isBlank(product.getDateAvailable())) { - try { - date = DateUtil.getDate(product.getDateAvailable()); - product.getAvailability().setProductDateAvailable(date); - product.setDateAvailable(DateUtil.formatDate(date)); - } catch (Exception e) { - ObjectError error = new ObjectError("dateAvailable",messages.getMessage("message.invalid.date", locale)); - result.addError(error); - } - } - - - - //validate image - if(product.getImage()!=null && !product.getImage().isEmpty()) { - - try { - - String maxHeight = configuration.getProperty("PRODUCT_IMAGE_MAX_HEIGHT_SIZE"); - String maxWidth = configuration.getProperty("PRODUCT_IMAGE_MAX_WIDTH_SIZE"); - String maxSize = configuration.getProperty("PRODUCT_IMAGE_MAX_SIZE"); - - - BufferedImage image = ImageIO.read(product.getImage().getInputStream()); - - - if(!StringUtils.isBlank(maxHeight)) { - - int maxImageHeight = Integer.parseInt(maxHeight); - if(image.getHeight()>maxImageHeight) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.height", locale) + " {"+maxHeight+"}"); - result.addError(error); - } - - } - - if(!StringUtils.isBlank(maxWidth)) { - - int maxImageWidth = Integer.parseInt(maxWidth); - if(image.getWidth()>maxImageWidth) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.width", locale) + " {"+maxWidth+"}"); - result.addError(error); - } - - } - - if(!StringUtils.isBlank(maxSize)) { - - int maxImageSize = Integer.parseInt(maxSize); - if(product.getImage().getSize()>maxImageSize) { - ObjectError error = new ObjectError("image",messages.getMessage("message.image.size", locale) + " {"+maxSize+"}"); - result.addError(error); - } - - } - - - - } catch (Exception e) { - LOGGER.error("Cannot validate product image", e); - } - - } - - - - if (result.hasErrors()) { - return "admin-products-edit"; - } - - Product newProduct = product.getProduct(); - ProductAvailability newProductAvailability = null; - ProductPrice newProductPrice = null; - - Set<ProductPriceDescription> productPriceDescriptions = null; - - //get tax class - //TaxClass taxClass = newProduct.getTaxClass(); - //TaxClass dbTaxClass = taxClassService.getById(taxClass.getId()); - Set<ProductPrice> prices = new HashSet<ProductPrice>(); - Set<ProductAvailability> availabilities = new HashSet<ProductAvailability>(); - - if(product.getProduct().getId()!=null && product.getProduct().getId().longValue()>0) { - - - //get actual product - newProduct = productService.getById(product.getProduct().getId()); - if(newProduct!=null && newProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - //copy properties - newProduct.setSku(product.getProduct().getSku()); - newProduct.setRefSku(product.getProduct().getRefSku()); - newProduct.setAvailable(product.getProduct().isAvailable()); - newProduct.setDateAvailable(date); - newProduct.setManufacturer(product.getProduct().getManufacturer()); - newProduct.setType(product.getProduct().getType()); - newProduct.setProductHeight(product.getProduct().getProductHeight()); - newProduct.setProductLength(product.getProduct().getProductLength()); - newProduct.setProductWeight(product.getProduct().getProductWeight()); - newProduct.setProductWidth(product.getProduct().getProductWidth()); - newProduct.setProductVirtual(product.getProduct().isProductVirtual()); - newProduct.setProductShipeable(product.getProduct().isProductShipeable()); - newProduct.setTaxClass(product.getProduct().getTaxClass()); - newProduct.setSortOrder(product.getProduct().getSortOrder()); - - Set<ProductAvailability> avails = newProduct.getAvailabilities(); - if(avails !=null && avails.size()>0) { - - for(ProductAvailability availability : avails) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) { - - - newProductAvailability = availability; - Set<ProductPrice> productPrices = availability.getPrices(); - - for(ProductPrice price : productPrices) { - if(price.isDefaultPrice()) { - newProductPrice = price; - newProductPrice.setProductPriceAmount(submitedPrice); - productPriceDescriptions = price.getDescriptions(); - } else { - prices.add(price); - } - } - } else { - availabilities.add(availability); - } - } - } - - - for(ProductImage image : newProduct.getImages()) { - if(image.isDefaultImage()) { - product.setProductImage(image); - } - } - } - - if(newProductPrice==null) { - newProductPrice = new ProductPrice(); - newProductPrice.setDefaultPrice(true); - newProductPrice.setProductPriceAmount(submitedPrice); - } - - if(product.getProductImage()!=null && product.getProductImage().getId() == null) { - product.setProductImage(null); - } - - if(productPriceDescriptions==null) { - productPriceDescriptions = new HashSet<ProductPriceDescription>(); - for(ProductDescription description : product.getDescriptions()) { - ProductPriceDescription ppd = new ProductPriceDescription(); - ppd.setProductPrice(newProductPrice); - ppd.setLanguage(description.getLanguage()); - ppd.setName(ProductPriceDescription.DEFAULT_PRICE_DESCRIPTION); - productPriceDescriptions.add(ppd); - } - newProductPrice.setDescriptions(productPriceDescriptions); - } - - newProduct.setMerchantStore(store); - - if(newProductAvailability==null) { - newProductAvailability = new ProductAvailability(); - } - - - newProductAvailability.setProductQuantity(product.getAvailability().getProductQuantity()); - newProductAvailability.setProductQuantityOrderMin(product.getAvailability().getProductQuantityOrderMin()); - newProductAvailability.setProductQuantityOrderMax(product.getAvailability().getProductQuantityOrderMax()); - newProductAvailability.setProduct(newProduct); - newProductAvailability.setPrices(prices); - availabilities.add(newProductAvailability); - - newProductPrice.setProductAvailability(newProductAvailability); - prices.add(newProductPrice); - - newProduct.setAvailabilities(availabilities); - - Set<ProductDescription> descriptions = new HashSet<ProductDescription>(); - if(product.getDescriptions()!=null && product.getDescriptions().size()>0) { - - for(ProductDescription description : product.getDescriptions()) { - description.setProduct(newProduct); - descriptions.add(description); - - } - } - - newProduct.setDescriptions(descriptions); - product.setDateAvailable(DateUtil.formatDate(date)); - - - - if(product.getImage()!=null && !product.getImage().isEmpty()) { - - - - String imageName = product.getImage().getOriginalFilename(); - - - - ProductImage productImage = new ProductImage(); - productImage.setDefaultImage(true); - productImage.setImage(product.getImage().getInputStream()); - productImage.setProductImage(imageName); - - - List<ProductImageDescription> imagesDescriptions = new ArrayList<ProductImageDescription>(); - - for(Language l : languages) { - - ProductImageDescription imageDescription = new ProductImageDescription(); - imageDescription.setName(imageName); - imageDescription.setLanguage(l); - imageDescription.setProductImage(productImage); - imagesDescriptions.add(imageDescription); - - } - - productImage.setDescriptions(imagesDescriptions); - productImage.setProduct(newProduct); - - newProduct.getImages().add(productImage); - - //productService.saveOrUpdate(newProduct); - - //product displayed - product.setProductImage(productImage); - - - } //else { - - //productService.saveOrUpdate(newProduct); - - //} - - productService.create(newProduct); - model.addAttribute("success","success"); - - return "admin-products-edit"; - } - - - /** - * Creates a duplicate product with the same inner object graph - * Will ignore SKU, reviews and images - * @param id - * @param result - * @param model - * @param request - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/duplicate.html", method=RequestMethod.POST) - public String duplicateProduct(@ModelAttribute("productId") Long id, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Manufacturer> manufacturers = manufacturerService.listByStore(store, language); - List<ProductType> productTypes = productTypeService.list(); - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - model.addAttribute("manufacturers", manufacturers); - model.addAttribute("productTypes", productTypes); - model.addAttribute("taxClasses", taxClasses); - - Product dbProduct = productService.getById(id); - Product newProduct = new Product(); - - if(dbProduct==null || dbProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - //Make a copy of the product - com.salesmanager.shop.admin.model.catalog.Product product = new com.salesmanager.shop.admin.model.catalog.Product(); - - Set<ProductAvailability> availabilities = new HashSet<ProductAvailability>(); - //availability - price - for(ProductAvailability pAvailability : dbProduct.getAvailabilities()) { - - ProductAvailability availability = new ProductAvailability(); - availability.setProductDateAvailable(pAvailability.getProductDateAvailable()); - availability.setProductIsAlwaysFreeShipping(pAvailability.getProductIsAlwaysFreeShipping()); - availability.setProductQuantity(pAvailability.getProductQuantity()); - availability.setProductQuantityOrderMax(pAvailability.getProductQuantityOrderMax()); - availability.setProductQuantityOrderMin(pAvailability.getProductQuantityOrderMin()); - availability.setProductStatus(pAvailability.getProductStatus()); - availability.setRegion(pAvailability.getRegion()); - availability.setRegionVariant(pAvailability.getRegionVariant()); - availability.setProduct(newProduct); - - - - Set<ProductPrice> prices = pAvailability.getPrices(); - for(ProductPrice pPrice : prices) { - - ProductPrice price = new ProductPrice(); - price.setDefaultPrice(pPrice.isDefaultPrice()); - price.setProductPriceAmount(pPrice.getProductPriceAmount()); - price.setProductAvailability(availability); - price.setProductPriceSpecialAmount(pPrice.getProductPriceSpecialAmount()); - price.setProductPriceSpecialEndDate(pPrice.getProductPriceSpecialEndDate()); - price.setProductPriceSpecialStartDate(pPrice.getProductPriceSpecialStartDate()); - price.setProductPriceType(pPrice.getProductPriceType()); - - Set<ProductPriceDescription> priceDescriptions = new HashSet<ProductPriceDescription>(); - //price descriptions - for(ProductPriceDescription pPriceDescription : pPrice.getDescriptions()) { - - ProductPriceDescription productPriceDescription = new ProductPriceDescription(); - productPriceDescription.setAuditSection(pPriceDescription.getAuditSection()); - productPriceDescription.setDescription(pPriceDescription.getDescription()); - productPriceDescription.setName(pPriceDescription.getName()); - productPriceDescription.setLanguage(pPriceDescription.getLanguage()); - productPriceDescription.setProductPrice(price); - priceDescriptions.add(productPriceDescription); - - } - price.setDescriptions(priceDescriptions); - if(price.isDefaultPrice()) { - product.setPrice(price); - product.setProductPrice(priceUtil.getAdminFormatedAmount(store, price.getProductPriceAmount())); - } - - availability.getPrices().add(price); - } - - - - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) { - product.setAvailability(availability); - } - - availabilities.add(availability); - } - - newProduct.setAvailabilities(availabilities); - - - - //attributes - Set<ProductAttribute> attributes = new HashSet<ProductAttribute>(); - for(ProductAttribute pAttribute : dbProduct.getAttributes()) { - - ProductAttribute attribute = new ProductAttribute(); - attribute.setAttributeDefault(pAttribute.getAttributeDefault()); - attribute.setAttributeDiscounted(pAttribute.getAttributeDiscounted()); - attribute.setAttributeDisplayOnly(pAttribute.getAttributeDisplayOnly()); - attribute.setAttributeRequired(pAttribute.getAttributeRequired()); - attribute.setProductAttributePrice(pAttribute.getProductAttributePrice()); - attribute.setProductAttributeIsFree(pAttribute.getProductAttributeIsFree()); - attribute.setProductAttributeWeight(pAttribute.getProductAttributeWeight()); - attribute.setProductOption(pAttribute.getProductOption()); - attribute.setProductOptionSortOrder(pAttribute.getProductOptionSortOrder()); - attribute.setProductOptionValue(pAttribute.getProductOptionValue()); - attribute.setProduct(newProduct); - attributes.add(attribute); - - } - newProduct.setAttributes(attributes); - - //relationships - Set<ProductRelationship> relationships = new HashSet<ProductRelationship>(); - for(ProductRelationship pRelationship : dbProduct.getRelationships()) { - - ProductRelationship relationship = new ProductRelationship(); - relationship.setActive(pRelationship.isActive()); - relationship.setCode(pRelationship.getCode()); - relationship.setRelatedProduct(pRelationship.getRelatedProduct()); - relationship.setStore(store); - relationship.setProduct(newProduct); - relationships.add(relationship); - - } - - newProduct.setRelationships(relationships); - - //product description - Set<ProductDescription> descsset = new HashSet<ProductDescription>(); - List<ProductDescription> desclist = new ArrayList<ProductDescription>(); - Set<ProductDescription> descriptions = dbProduct.getDescriptions(); - for(ProductDescription pDescription : descriptions) { - - ProductDescription description = new ProductDescription(); - description.setAuditSection(pDescription.getAuditSection()); - description.setName(pDescription.getName()); - description.setDescription(pDescription.getDescription()); - description.setLanguage(pDescription.getLanguage()); - description.setMetatagDescription(pDescription.getMetatagDescription()); - description.setMetatagKeywords(pDescription.getMetatagKeywords()); - description.setMetatagTitle(pDescription.getMetatagTitle()); - description.setProduct(newProduct); - descsset.add(description); - desclist.add(description); - } - newProduct.setDescriptions(descsset); - product.setDescriptions(desclist); - - //product - newProduct.setAuditSection(dbProduct.getAuditSection()); - newProduct.setAvailable(dbProduct.isAvailable()); - - - - //copy - // newProduct.setCategories(dbProduct.getCategories()); - newProduct.setDateAvailable(dbProduct.getDateAvailable()); - newProduct.setManufacturer(dbProduct.getManufacturer()); - newProduct.setMerchantStore(store); - newProduct.setProductHeight(dbProduct.getProductHeight()); - newProduct.setProductIsFree(dbProduct.getProductIsFree()); - newProduct.setProductLength(dbProduct.getProductLength()); - newProduct.setProductOrdered(dbProduct.getProductOrdered()); - newProduct.setProductWeight(dbProduct.getProductWeight()); - newProduct.setProductWidth(dbProduct.getProductWidth()); - newProduct.setSortOrder(dbProduct.getSortOrder()); - newProduct.setTaxClass(dbProduct.getTaxClass()); - newProduct.setType(dbProduct.getType()); - newProduct.setSku(UUID.randomUUID().toString().replace("-","")); - newProduct.setProductVirtual(dbProduct.isProductVirtual()); - newProduct.setProductShipeable(dbProduct.isProductShipeable()); - - productService.update(newProduct); - - Set<Category> categories = dbProduct.getCategories(); - for(Category category : categories) { - Category categoryCopy = categoryService.getById(category.getId(), store.getId()); - newProduct.getCategories().add(categoryCopy); - productService.update(newProduct); - } - - product.setProduct(newProduct); - model.addAttribute("product", product); - model.addAttribute("success","success"); - - return "redirect:/admin/products/editProduct.html?id=" + newProduct.getId(); - } - - - /** - * Removes a product image based on the productimage id - * @param request - * @param response - * @param locale - * @return - */ - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/removeImage.html") - public @ResponseBody ResponseEntity<String> removeImage(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String iid = request.getParameter("imageId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(iid); - ProductImage productImage = productImageService.getById(id); - if(productImage==null || productImage.getProduct().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - productImageService.removeProductImage(productImage); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - /** - * List all categories and let the merchant associate the product to a category - * @param productId - * @param model - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/displayProductToCategories.html", method=RequestMethod.GET) - public String displayAddProductToCategories(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - - //get the product and validate it belongs to the current merchant - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - - //get parent categories - List<Category> categories = categoryService.listByStore(store,language); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("product", product); - model.addAttribute("categories", readableCategories); - return "catalogue-product-categories"; - - } - - /** - * List all categories associated to a Product - * @param request - * @param response - * @return - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/product-categories/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProductCategories(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - product = productService.getById(productId); - - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - - Set<Category> categories = product.getCategories(); - - - for(Category category : categories) { - Map entry = new HashMap(); - entry.put("categoryId", category.getId()); - - Set<CategoryDescription> descriptions = category.getDescriptions(); - String categoryName = category.getDescriptions().iterator().next().getName(); - for(CategoryDescription description : descriptions){ - if(description.getLanguage().getCode().equals(language.getCode())) { - categoryName = description.getName(); - } - } - entry.put("name", categoryName); - resp.addDataEntry(entry); - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/product-categories/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteProductFromCategory(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sCategoryid = request.getParameter("categoryId"); - String sProductId = request.getParameter("productId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - Long categoryId = Long.parseLong(sCategoryid); - Long productId = Long.parseLong(sProductId); - - Category category = categoryService.getById(categoryId, store.getId()); - Product product = productService.getById(productId); - - if(category==null || category.getMerchantStore().getId()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product==null || product.getMerchantStore().getId()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - product.getCategories().remove(category); - productService.update(product); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting category", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/addProductToCategories.html", method=RequestMethod.POST) - public String addProductToCategory(@RequestParam("productId") long productId, @RequestParam("id") long categoryId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - - //get the product and validate it belongs to the current merchant - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - - //get parent categories - List<Category> categories = categoryService.listByStore(store,language); - - Category category = categoryService.getById(categoryId, store.getId(), language.getId()); - - if(category==null) { - return "redirect:/admin/products/products.html"; - } - - if(category.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - product.getCategories().add(category); - - productService.update(product); - - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("product", product); - model.addAttribute("categories", readableCategories); - - return "catalogue-product-categories"; - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - } -} \ No newline at end of file
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductImagesController.java+0 −502 removed@@ -1,502 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.image.ProductImageService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.image.ProductImage; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.content.ProductImages; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.ImageFilePath; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class ProductImagesController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductImagesController.class); - - - - @Inject - private ProductService productService; - - - @Inject - private ProductImageService productImageService; - - @Inject - private LabelUtils messages; - - @Inject - @Qualifier("img") - private ImageFilePath imageUtils; - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/list.html", method=RequestMethod.GET) - public String displayProductImages(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - model.addAttribute("product",product); - return ControllerConstants.Tiles.Product.productImages; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/url/list.html", method=RequestMethod.GET) - public String displayProductImagesUrl(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - Map< String, String > mediaTypes = new HashMap<String, String>(); - mediaTypes.put("0", "IMAGE"); - mediaTypes.put("1", "VIDEO"); - - ProductImage productImage = new ProductImage(); - - model.addAttribute("productImage", productImage); - model.addAttribute("product",product); - model.addAttribute("mediaTypes",mediaTypes); - return ControllerConstants.Tiles.Product.productImagesUrl; - - } - - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/page.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProductImages(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - - product = productService.getById(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Merchant id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Set<ProductImage> images = product.getImages(); - - if(images!=null) { - - for(ProductImage image : images) { - - String imagePath = imageUtils.buildProductImageUtils(store, product, image.getProductImage()); - - Map entry = new HashMap(); - //entry.put("picture", new StringBuilder().append(request.getContextPath()).append(imagePath).toString()); - entry.put("picture", imagePath); - entry.put("name", image.getProductImage()); - entry.put("id",image.getId()); - entry.put("defaultImageCheckmark", image.isDefaultImage() ? "/resources/img/admin/checkmark_checked.png" : "/resources/img/admin/checkmark_unchecked.png"); - - resp.addDataEntry(entry); - - } - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/url/page.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProductImagesUrl(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - - product = productService.getById(productId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Merchant id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Set<ProductImage> images = product.getImages(); - - if(images!=null) { - - for(ProductImage image : images) { - - if(!StringUtils.isBlank(image.getProductImageUrl())) { - - Map entry = new HashMap(); - entry.put("image", image.getProductImageUrl()); - entry.put("url", image.getProductImageUrl()); - entry.put("default", image.isDefaultImage()); - entry.put("id",image.getId()); - - resp.addDataEntry(entry); - - } - } - - } - - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/save.html", method=RequestMethod.POST) - public String saveProductImages(@ModelAttribute(value="productImages") @Valid final ProductImages productImages, final BindingResult bindingResult,final Model model, final HttpServletRequest request,Locale locale) throws Exception{ - - - this.setMenu(model, request); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productImages.getProductId()); - model.addAttribute("product",product); - if(product==null) { - FieldError error = new FieldError("productImages","image",messages.getMessage("message.error", locale)); - bindingResult.addError(error); - return ControllerConstants.Tiles.Product.productImages; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - FieldError error = new FieldError("productImages","image",messages.getMessage("message.error", locale)); - bindingResult.addError(error); - } - - if (bindingResult.hasErrors()) { - LOGGER.info( "Found {} Validation errors", bindingResult.getErrorCount()); - return ControllerConstants.Tiles.Product.productImages; - - } - - final List<ProductImage> contentImagesList=new ArrayList<ProductImage>(); - if(CollectionUtils.isNotEmpty( productImages.getFile() )){ - LOGGER.info("Saving {} content images for merchant {}",productImages.getFile().size(),store.getId()); - for(final MultipartFile multipartFile:productImages.getFile()){ - if(!multipartFile.isEmpty()){ - ProductImage productImage = new ProductImage(); - - productImage.setImage(multipartFile.getInputStream()); - productImage.setProductImage(multipartFile.getOriginalFilename() ); - productImage.setProduct(product); - productImage.setDefaultImage(false);//default image is uploaded in the product details - - contentImagesList.add( productImage); - } - } - - if(CollectionUtils.isNotEmpty( contentImagesList )){ - productImageService.addProductImages(product, contentImagesList); - } - - } - - - //reload - product = productService.getById(productImages.getProductId()); - model.addAttribute("product",product); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Product.productImages; - } - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/url/save.html", method=RequestMethod.POST) - public String saveProductImagesUrl(@ModelAttribute(value="productImage") @Valid final ProductImage productImage, final BindingResult bindingResult,final Model model, final HttpServletRequest request,Locale locale) throws Exception{ - - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Map< String, String > mediaTypes = new HashMap<String, String>(); - mediaTypes.put("0", "IMAGE"); - mediaTypes.put("1", "VIDEO"); - - model.addAttribute("productImage", productImage); - model.addAttribute("mediaTypes",mediaTypes); - - Product product = productService.getById(productImage.getId()); - model.addAttribute("product",product); - if(product==null) { - FieldError error = new FieldError("productImages","image",messages.getMessage("message.error", locale)); - bindingResult.addError(error); - return ControllerConstants.Tiles.Product.productImagesUrl; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - FieldError error = new FieldError("productImages","image",messages.getMessage("message.error", locale)); - bindingResult.addError(error); - } - - model.addAttribute("product",product); - - if (bindingResult.hasErrors()) { - LOGGER.info( "Found {} Validation errors", bindingResult.getErrorCount()); - return ControllerConstants.Tiles.Product.productImagesUrl; - } - - productImage.setProduct(product); - productImage.setId(null); - - productImageService.saveOrUpdate(productImage); - model.addAttribute("product",product); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Product.productImagesUrl; - } - - - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteImage(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sImageId = request.getParameter("id"); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - - Long imageId = Long.parseLong(sImageId); - - - ProductImage productImage = productImageService.getById(imageId); - if(productImage==null) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(productImage.getProduct().getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - productImageService.removeProductImage(productImage); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting product price", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/images/defaultImage.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> setDefaultImage(final HttpServletRequest request, - final HttpServletResponse response, - final Locale locale) { - final String sImageId = request.getParameter("id"); - final MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - final AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - final Long imageId = Long.parseLong(sImageId); - final ProductImage productImage = productImageService.getById(imageId); - - if (productImage == null) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if (productImage.getProduct().getMerchantStore().getId().intValue() != store.getId().intValue()) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - productImage.setDefaultImage(true); - productImageService.saveOrUpdate(productImage); - - final Set<ProductImage> images = productService.getById(productImage.getProduct().getId()).getImages(); - for (final ProductImage image : images) { - if (image.getId() != productImage.getId()) { - image.setDefaultImage(false); - productImageService.saveOrUpdate(image); - } - } - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - } catch (final Exception e) { - LOGGER.error("Error while set default image", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductKeywordsController.java+0 −343 removed@@ -1,343 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.catalog.Keyword; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.*; - -@Controller -public class ProductKeywordsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductKeywordsController.class); - - @Inject - private ProductService productService; - - @Inject - LabelUtils messages; - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value={"/admin/products/product/keywords.html"}, method=RequestMethod.GET) - public String displayKeywords(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(productId); - - if(product==null || product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - model.addAttribute("store", store); - model.addAttribute("product", product); - model.addAttribute("productKeyword", new Keyword()); - - return ControllerConstants.Tiles.Product.productKeywords; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/addKeyword.html", method=RequestMethod.POST) - public String addKeyword(@Valid @ModelAttribute("productKeyword") Keyword keyword, final BindingResult bindingResult,final Model model, final HttpServletRequest request, Locale locale) throws Exception{ - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - Product product = productService.getById(keyword.getProductId()); - - model.addAttribute("store", store); - model.addAttribute("product", product); - model.addAttribute("productKeyword", new Keyword()); - - if(product==null || product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - Set<ProductDescription> descriptions = product.getDescriptions(); - ProductDescription productDescription = null; - for(ProductDescription description : descriptions) { - - if(description.getLanguage().getCode().equals(keyword.getLanguageCode())) { - productDescription = description; - break; - } - - } - - if(productDescription==null) { - FieldError error = new FieldError("keyword","keyword",messages.getMessage("message.product.language", locale)); - bindingResult.addError(error); - return ControllerConstants.Tiles.Product.productKeywords; - } - - - String keywords = productDescription.getMetatagKeywords(); - List<String> keyWordsList = null; - if(!StringUtils.isBlank(keywords)) { - String[] splits = keywords.split(","); - keyWordsList = new ArrayList(Arrays.asList(splits)); - } - - if(keyWordsList==null) { - keyWordsList = new ArrayList<String>(); - } - keyWordsList.add(keyword.getKeyword()); - - StringBuilder kwString = new StringBuilder(); - for(String s : keyWordsList) { - kwString.append(s).append(","); - } - - productDescription.setMetatagKeywords(kwString.toString()); - Set<ProductDescription> updatedDescriptions = new HashSet<ProductDescription>(); - for(ProductDescription description : descriptions) { - - if(!description.getLanguage().getCode().equals(keyword.getLanguageCode())) { - updatedDescriptions.add(description); - } - } - - updatedDescriptions.add(productDescription); - product.setDescriptions(updatedDescriptions); - - productService.update(product); - model.addAttribute("success","success"); - - - return ControllerConstants.Tiles.Product.productKeywords; - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/removeKeyword.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeKeyword(@RequestParam("id") long productId, HttpServletRequest request, HttpServletResponse response, Locale locale) { - - - String code = request.getParameter("code"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - //parse code i,lang (0,en) - String ids[] = code.split(","); - - String languageCode = ids[1]; - - int index = Integer.parseInt(ids[0]); - - Product product = productService.getById(productId); - - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Set<ProductDescription> descriptions = product.getDescriptions(); - Set<ProductDescription> editedDescriptions = new HashSet<ProductDescription>(); - for(ProductDescription description : descriptions) { - - Language lang = description.getLanguage(); - if(!lang.getCode().equals(languageCode)){ - editedDescriptions.add(description); - continue; - } - - List<String> keyWordsList = new ArrayList<String>(); - - - String keywords = description.getMetatagKeywords(); - if(!StringUtils.isBlank(keywords)) { - String splitKeywords[] = keywords.split(","); - for(int i = 0; i < splitKeywords.length; i++) { - - if(i!=index) { - keyWordsList.add(splitKeywords[i]); - } - - - } - } - - - - - StringBuilder kwString = new StringBuilder(); - for(String s : keyWordsList) { - kwString.append(s).append(","); - } - - description.setMetatagKeywords(kwString.toString()); - editedDescriptions.add(description); - - } - - product.setDescriptions(editedDescriptions); - productService.update(product); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/product/keywords/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageKeywords(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("id"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - product = productService.getById(productId); - - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @SuppressWarnings("rawtypes") - - - Set<ProductDescription> descriptions = product.getDescriptions(); - - for(ProductDescription description : descriptions) { - - - Language lang = description.getLanguage(); - - - String keywords = description.getMetatagKeywords(); - if(!StringUtils.isBlank(keywords)) { - - String splitKeywords[] = keywords.split(","); - for(int i = 0; i < splitKeywords.length; i++) { - Map entry = new HashMap(); - entry.put("language", lang.getCode()); - String keyword = splitKeywords[i]; - StringBuilder code = new StringBuilder(); - code.append(i).append(",").append(lang.getCode()); - - entry.put("code", code.toString()); - entry.put("keyword", keyword); - resp.addDataEntry(entry); - - - } - - } - - } - - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductPriceController.java+0 −505 removed@@ -1,505 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.price.ProductPriceService; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; -import com.salesmanager.core.model.catalog.product.price.ProductPrice; -import com.salesmanager.core.model.catalog.product.price.ProductPriceDescription; -import com.salesmanager.core.model.catalog.product.price.ProductPriceType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.DateUtil; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.math.BigDecimal; -import java.util.*; - -@Controller -public class ProductPriceController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductPriceController.class); - - @Inject - private ProductService productService; - - @Inject - private ProductPriceService productPriceService; - - @Inject - private ProductPriceUtils priceUtil; - - @Inject - LabelUtils messages; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/prices.html", method=RequestMethod.GET) - public String getProductPrices(@RequestParam("id") long productId,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get the product and validate it belongs to the current merchant - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - ProductAvailability productAvailability = null; - for(ProductAvailability availability : product.getAvailabilities()) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) { - productAvailability = availability; - } - } - - model.addAttribute("product",product); - model.addAttribute("availability",productAvailability); - - return ControllerConstants.Tiles.Product.productPrices; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/prices/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pagePrices(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - product = productService.getById(productId); - - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - ProductAvailability defaultAvailability = null; - - Set<ProductAvailability> availabilities = product.getAvailabilities(); - - //get default availability - for(ProductAvailability availability : availabilities) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) { - defaultAvailability = availability; - break; - } - } - - if(defaultAvailability==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Set<ProductPrice> prices = defaultAvailability.getPrices(); - - - for(ProductPrice price : prices) { - Map entry = new HashMap(); - entry.put("priceId", price.getId()); - - - String priceName = ""; - Set<ProductPriceDescription> descriptions = price.getDescriptions(); - if(descriptions!=null) { - for(ProductPriceDescription description : descriptions) { - if(description.getLanguage().getCode().equals(language.getCode())) { - priceName = description.getName(); - } - } - } - - - entry.put("name", priceName); - entry.put("price", priceUtil.getAdminFormatedAmountWithCurrency(store,price.getProductPriceAmount())); - entry.put("specialPrice", priceUtil.getAdminFormatedAmountWithCurrency(store,price.getProductPriceSpecialAmount())); - - String discount = ""; - if(priceUtil.hasDiscount(price)) { - discount = priceUtil.getAdminFormatedAmountWithCurrency(store,price.getProductPriceAmount()); - } - entry.put("special", discount); - - resp.addDataEntry(entry); - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/price/edit.html", method=RequestMethod.GET) - public String editProductPrice(@RequestParam("id") long productPriceId, @RequestParam("productId") long productId,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - - setMenu(model,request); - return displayProductPrice(product, productPriceId, model, request, response); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/price/create.html", method=RequestMethod.GET) - public String displayCreateProductPrice(@RequestParam("productId") long productId,@RequestParam("availabilityId") long avilabilityId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Product product = productService.getById(productId); - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - setMenu(model,request); - return displayProductPrice(product, null, model, request, response); - - - - } - - private String displayProductPrice(Product product, Long productPriceId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - com.salesmanager.shop.admin.model.catalog.ProductPrice pprice = new com.salesmanager.shop.admin.model.catalog.ProductPrice(); - - ProductPrice productPrice = null; - ProductAvailability productAvailability = null; - - if(productPriceId!=null) { - - Set<ProductAvailability> availabilities = product.getAvailabilities(); - - //get default availability - for(ProductAvailability availability : availabilities) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) {//TODO to be updated when multiple regions is implemented - productAvailability = availability; - Set<ProductPrice> prices = availability.getPrices(); - for(ProductPrice price : prices) { - if(price.getId().longValue()==productPriceId.longValue()) { - productPrice = price; - if(price.getProductPriceSpecialStartDate()!=null) { - pprice.setProductPriceSpecialStartDate(DateUtil.formatDate(price.getProductPriceSpecialStartDate())); - } - if(price.getProductPriceSpecialEndDate()!=null) { - pprice.setProductPriceSpecialEndDate(DateUtil.formatDate(price.getProductPriceSpecialEndDate())); - } - pprice.setPriceText(priceUtil.getAdminFormatedAmount(store, price.getProductPriceAmount())); - if(price.getProductPriceSpecialAmount()!=null) { - pprice.setSpecialPriceText(priceUtil.getAdminFormatedAmount(store, price.getProductPriceSpecialAmount())); - } - break; - } - } - } - } - - } - - if(productPrice==null) { - productPrice = new ProductPrice(); - productPrice.setProductPriceType(ProductPriceType.ONE_TIME); - } - - //descriptions - List<Language> languages = store.getLanguages(); - - Set<ProductPriceDescription> productPriceDescriptions = productPrice.getDescriptions(); - List<ProductPriceDescription> descriptions = new ArrayList<ProductPriceDescription>(); - for(Language l : languages) { - ProductPriceDescription productPriceDesc = null; - for(ProductPriceDescription desc : productPriceDescriptions) { - Language lang = desc.getLanguage(); - if(lang.getCode().equals(l.getCode())) { - productPriceDesc = desc; - } - } - - if(productPriceDesc==null) { - productPriceDesc = new ProductPriceDescription(); - productPriceDesc.setLanguage(l); - productPriceDescriptions.add(productPriceDesc); - } - descriptions.add(productPriceDesc); - } - - - if(productAvailability==null) { - Set<ProductAvailability> availabilities = product.getAvailabilities(); - for(ProductAvailability availability : availabilities) { - if(availability.getRegion().equals(com.salesmanager.core.business.constants.Constants.ALL_REGIONS)) {//TODO to be updated when multiple regions is implemented - productAvailability = availability; - break; - } - } - } - - pprice.setDescriptions(descriptions); - pprice.setProductAvailability(productAvailability); - pprice.setPrice(productPrice); - pprice.setProduct(product); - - - model.addAttribute("product",product); - //model.addAttribute("descriptions",descriptions); - model.addAttribute("price",pprice); - //model.addAttribute("availability",productAvailability); - - return ControllerConstants.Tiles.Product.productPrice; - } - - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/price/save.html", method=RequestMethod.POST) - public String saveProductPrice(@Valid @ModelAttribute("price") com.salesmanager.shop.admin.model.catalog.ProductPrice price, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - //dates after save - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = price.getProduct(); - Product dbProduct = productService.getById(product.getId()); - if(store.getId().intValue()!=dbProduct.getMerchantStore().getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - model.addAttribute("product",dbProduct); - - //validate price - BigDecimal submitedPrice = null; - try { - submitedPrice = priceUtil.getAmount(price.getPriceText()); - } catch (Exception e) { - ObjectError error = new ObjectError("productPrice",messages.getMessage("NotEmpty.product.productPrice", locale)); - result.addError(error); - } - - //validate discount price - BigDecimal submitedDiscountPrice = null; - - if(!StringUtils.isBlank(price.getSpecialPriceText())) { - try { - submitedDiscountPrice = priceUtil.getAmount(price.getSpecialPriceText()); - } catch (Exception e) { - ObjectError error = new ObjectError("productSpecialPrice",messages.getMessage("NotEmpty.product.productPrice", locale)); - result.addError(error); - } - } - - //validate start date - if(!StringUtils.isBlank(price.getProductPriceSpecialStartDate())) { - try { - Date startDate = DateUtil.getDate(price.getProductPriceSpecialStartDate()); - price.getPrice().setProductPriceSpecialStartDate(startDate); - } catch (Exception e) { - ObjectError error = new ObjectError("productPriceSpecialStartDate",messages.getMessage("message.invalid.date", locale)); - result.addError(error); - } - } - - if(!StringUtils.isBlank(price.getProductPriceSpecialEndDate())) { - try { - Date endDate = DateUtil.getDate(price.getProductPriceSpecialEndDate()); - price.getPrice().setProductPriceSpecialEndDate(endDate); - } catch (Exception e) { - ObjectError error = new ObjectError("productPriceSpecialEndDate",messages.getMessage("message.invalid.date", locale)); - result.addError(error); - } - } - - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Product.productPrice; - } - - - price.getPrice().setProductPriceAmount(submitedPrice); - if(!StringUtils.isBlank(price.getSpecialPriceText())) { - price.getPrice().setProductPriceSpecialAmount(submitedDiscountPrice); - } - - ProductAvailability productAvailability = null; - - Set<ProductAvailability> availabilities = dbProduct.getAvailabilities(); - for(ProductAvailability availability : availabilities) { - - if(availability.getId().longValue()==price.getProductAvailability().getId().longValue()) { - productAvailability = availability; - break; - } - - - } - - - - - Set<ProductPriceDescription> descriptions = new HashSet<ProductPriceDescription>(); - if(price.getDescriptions()!=null && price.getDescriptions().size()>0) { - - for(ProductPriceDescription description : price.getDescriptions()) { - description.setProductPrice(price.getPrice()); - descriptions.add(description); - description.setProductPrice(price.getPrice()); - } - } - - price.getPrice().setDescriptions(descriptions); - price.getPrice().setProductAvailability(productAvailability); - - productPriceService.saveOrUpdate(price.getPrice()); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Product.productPrice; - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/price/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteProductPrice(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sPriceid = request.getParameter("priceId"); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - Long priceId = Long.parseLong(sPriceid); - ProductPrice price = productPriceService.getById(priceId); - - - if(price==null || price.getProductAvailability().getProduct().getMerchantStore().getId().intValue()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - productPriceService.delete(price); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting product price", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductReviewController.java+0 −229 removed@@ -1,229 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.review.ProductReviewService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.review.ProductReview; -import com.salesmanager.core.model.catalog.product.review.ProductReviewDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - -@Controller -public class ProductReviewController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductReviewController.class); - - @Inject - private ProductService productService; - - @Inject - private ProductReviewService productReviewService; - - @Inject - LabelUtils messages; - - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/reviews.html", method=RequestMethod.GET) - public String displayProductReviews(@RequestParam("id") long productId,Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model, request); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Product product = productService.getProductWithOnlyMerchantStoreById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - - model.addAttribute("product", product); - - return ControllerConstants.Tiles.Product.productReviews; - - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/reviews/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProductReviews(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - Long productId; - Product product = null; - - try { - productId = Long.parseLong(sProductId); - } catch (Exception e) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - try { - - product = productService.getProductWithOnlyMerchantStoreById(productId); - - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - Language language = (Language)request.getAttribute("LANGUAGE"); - - - List<ProductReview> reviews = productReviewService.getByProduct(product); - - - - for(ProductReview review : reviews) { - Map entry = new HashMap(); - entry.put("reviewId", review.getId()); - entry.put("rating", review.getReviewRating().intValue()); - Set<ProductReviewDescription> descriptions = review.getDescriptions(); - String reviewDesc= ""; - if(!CollectionUtils.isEmpty(descriptions)) { - reviewDesc = descriptions.iterator().next().getDescription(); - } - //for(ProductReviewDescription description : descriptions){ - // if(description.getLanguage().getCode().equals(language.getCode())) { - // reviewDesc = description.getDescription(); - // } - //} - entry.put("description", reviewDesc); - resp.addDataEntry(entry); - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/reviews/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteProductReview(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sReviewid = request.getParameter("reviewId"); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - Long reviewId = Long.parseLong(sReviewid); - - - ProductReview review = productReviewService.getById(reviewId); - - - if(review==null || review.getProduct().getMerchantStore().getId().intValue()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - productReviewService.delete(review); - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting review", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/ProductsController.java+0 −263 removed@@ -1,263 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.ProductCriteria; -import com.salesmanager.core.model.catalog.product.ProductList; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - -@Controller -public class ProductsController { - - @Inject - CategoryService categoryService; - - @Inject - ProductService productService; - - @Inject - LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(ProductsController.class); - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/products.html", method=RequestMethod.GET) - public String displayProducts(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - List<Category> categories = categoryService.listByStore(store, language); - - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - model.addAttribute("categories", readableCategories); - - return "admin-products"; - - } - - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageProducts(HttpServletRequest request, HttpServletResponse response) { - - //TODO what if ROOT - - String categoryId = request.getParameter("categoryId"); - String sku = request.getParameter("sku"); - String available = request.getParameter("available"); - String searchTerm = request.getParameter("searchTerm"); - String name = request.getParameter("name"); - - AjaxPageableResponse resp = new AjaxPageableResponse(); - - try { - - - int startRow = Integer.parseInt(request.getParameter("_startRow")); - int endRow = Integer.parseInt(request.getParameter("_endRow")); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - ProductCriteria criteria = new ProductCriteria(); - - criteria.setStartIndex(startRow); - criteria.setMaxCount(endRow); - - - if(!StringUtils.isBlank(categoryId) && !categoryId.equals("-1")) { - - //get other filters - Long lcategoryId = 0L; - try { - lcategoryId = Long.parseLong(categoryId); - } catch (Exception e) { - LOGGER.error("Product page cannot parse categoryId " + categoryId ); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,HttpStatus.BAD_REQUEST); - } - - - - if(lcategoryId>0) { - - Category category = categoryService.getById(lcategoryId, store.getId()); - - if(category==null || category.getMerchantStore().getId()!=store.getId()) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,HttpStatus.BAD_REQUEST); - } - - //get all sub categories - StringBuilder lineage = new StringBuilder(); - lineage.append(category.getLineage()).append(category.getId()).append("/"); - - List<Category> categories = categoryService.getListByLineage(store, lineage.toString()); - - List<Long> categoryIds = new ArrayList<Long>(); - - for(Category cat : categories) { - categoryIds.add(cat.getId()); - } - categoryIds.add(category.getId()); - criteria.setCategoryIds(categoryIds); - - } - - - - - } - - if(!StringUtils.isBlank(sku)) { - criteria.setCode(sku); - } - - if(!StringUtils.isBlank(name)) { - criteria.setProductName(name); - } - - if(!StringUtils.isBlank(available)) { - if(available.equals("true")) { - criteria.setAvailable(new Boolean(true)); - } else { - criteria.setAvailable(new Boolean(false)); - } - } - - ProductList productList = productService.listByStore(store, language, criteria); - resp.setEndRow(Math.toIntExact(productList.getTotalCount())); - resp.setStartRow(startRow); - List<Product> plist = productList.getProducts(); - - if(plist!=null) { - - for(Product product : plist) { - - Map entry = new HashMap(); - entry.put("productId", product.getId()); - - ProductDescription description = product.getDescriptions().iterator().next(); - - entry.put("name", description.getName()); - entry.put("sku", product.getSku()); - entry.put("available", product.isAvailable()); - resp.addDataEntry(entry); - - - - } - - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/products/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteProduct(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String sid = request.getParameter("productId"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - - - try { - - Long id = Long.parseLong(sid); - - Product product = productService.getById(id); - - if(product==null || product.getMerchantStore().getId()!=store.getId()) { - - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - - } else { - - productService.delete(product); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } - - - } catch (Exception e) { - LOGGER.error("Error while deleting product", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/products/RelatedItemsController.java+0 −334 removed@@ -1,334 +0,0 @@ -package com.salesmanager.shop.admin.controller.products; - -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.relationship.ProductRelationshipService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.category.Category; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationship; -import com.salesmanager.core.model.catalog.product.relationship.ProductRelationshipType; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.CategoryUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -@Controller -public class RelatedItemsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(RelatedItemsController.class); - - @Inject - CategoryService categoryService; - - @Inject - ProductService productService; - - @Inject - ProductRelationshipService productRelationshipService; - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/related/list.html", method=RequestMethod.GET) - public String displayRelatedItems(@RequestParam("id") long productId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - setMenu(model,request); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get the product and validate it belongs to the current merchant - Product product = productService.getById(productId); - - if(product==null) { - return "redirect:/admin/products/products.html"; - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - return "redirect:/admin/products/products.html"; - } - - - List<Category> categories = categoryService.listByStore(store,language); - List<com.salesmanager.shop.admin.model.catalog.Category> readableCategories = CategoryUtils.readableCategoryListConverter(categories, language); - - - model.addAttribute("categories", readableCategories); - model.addAttribute("product", product); - return ControllerConstants.Tiles.Product.relatedItems; - - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/related/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageRelatedItems(HttpServletRequest request, HttpServletResponse response) { - - String sProductId = request.getParameter("productId"); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - - Long productId = Long.parseLong(sProductId); - Product product = productService.getById(productId); - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - if(product==null || product.getMerchantStore().getId().intValue()!= store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Product id is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - List<ProductRelationship> relationships = productRelationshipService.getByType(store, product, ProductRelationshipType.RELATED_ITEM, language); - - for(ProductRelationship relationship : relationships) { - - Product relatedProduct = relationship.getRelatedProduct(); - Map entry = new HashMap(); - entry.put("relationshipId", relationship.getId()); - entry.put("productId", relatedProduct.getId()); - - ProductDescription description = relatedProduct.getDescriptions().iterator().next(); - Set<ProductDescription> descriptions = relatedProduct.getDescriptions(); - for(ProductDescription desc : descriptions) { - if(desc.getLanguage().getId().intValue()==language.getId().intValue()) { - description = desc; - } - } - - - entry.put("name", description.getName()); - entry.put("sku", relatedProduct.getSku()); - entry.put("available", relatedProduct.isAvailable()); - resp.addDataEntry(entry); - - } - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/related/addItem.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> addItem(HttpServletRequest request, HttpServletResponse response) { - - String productId = request.getParameter("productId"); - String baseProductId = request.getParameter("baseProductId"); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - Long lProductId = Long.parseLong(productId); - Long lBaseProductId = Long.parseLong(baseProductId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lProductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Product baseProduct = productService.getById(lBaseProductId); - - if(baseProduct==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(baseProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - ProductRelationship relationship = new ProductRelationship(); - relationship.setActive(true); - relationship.setProduct(baseProduct); - relationship.setCode(ProductRelationshipType.RELATED_ITEM.name()); - relationship.setStore(store); - relationship.setRelatedProduct(product); - - productRelationshipService.saveOrUpdate(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('PRODUCTS')") - @RequestMapping(value="/admin/catalogue/related/removeItem.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeItem(HttpServletRequest request, HttpServletResponse response) { - - String productId = request.getParameter("productId"); - String baseProductId = request.getParameter("baseProductId"); - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - Long lproductId = Long.parseLong(productId); - Long lBaseProductId = Long.parseLong(baseProductId); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Product product = productService.getById(lproductId); - - if(product==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(product.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Product baseProduct = productService.getById(lBaseProductId); - - if(baseProduct==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(baseProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - ProductRelationship relationship = null; - List<ProductRelationship> relationships = productRelationshipService.getByType(store, baseProduct, ProductRelationshipType.RELATED_ITEM); - - for(ProductRelationship r : relationships) { - if(r.getRelatedProduct().getId().longValue()==lproductId.longValue()) { - relationship = r; - break; - } - } - - if(relationship==null) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(relationship.getStore().getId().intValue()!=store.getId().intValue()) { - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - productRelationshipService.delete(relationship); - - - resp.setStatus(AjaxPageableResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("catalogue", "catalogue"); - activeMenus.put("catalogue-products", "catalogue-products"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("catalogue"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/CustomShippingMethodsController.java+0 −772 removed@@ -1,772 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.shipping.ShippingService; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.shipping.ShippingConfiguration; -import com.salesmanager.core.model.shipping.ShippingType; -import com.salesmanager.core.model.system.IntegrationConfiguration; -import com.salesmanager.core.modules.integration.IntegrationException; -import com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuoteWeightItem; -import com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesConfiguration; -import com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesRegion; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.MerchantUtils; -import org.apache.commons.beanutils.BeanComparator; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.math.BigDecimal; -import java.util.*; - -@Controller -public class CustomShippingMethodsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomShippingMethodsController.class); - - - public final static String WEIGHT_BASED_SHIPPING_METHOD = "weightBased"; - - @Inject - private ShippingService shippingService; - - @Inject - private CountryService countryService; - - @Inject - private ProductPriceUtils priceUtil; - - @Inject - LabelUtils messages; - - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased.html", method=RequestMethod.GET) - public String getWeightBasedShippingMethod(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - - populateModel(model, request, response); - - return ControllerConstants.Tiles.Shipping.shippingMethod; - - - } - - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/addCustomRegion.html", method=RequestMethod.POST) - public String addCustomRegion(@ModelAttribute("region") String region, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - populateModel(model, request, response); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - - if(StringUtils.isBlank(region)) { - model.addAttribute("errorMessage",messages.getMessage("message.region.null", locale)); - ObjectError error = new ObjectError("region",messages.getMessage("message.region.null", locale)); - result.addError(error); - } - - - for(CustomShippingQuotesRegion customRegion : regions) { - if(customRegion.getCustomRegionName().equals(region)) { - model.addAttribute("errorMessage",messages.getMessage("message.region.null", locale)); - ObjectError error = new ObjectError("region",messages.getMessage("message.region.exists", locale)); - result.addError(error); - break; - } - } - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Shipping.shippingMethod; - } - - - CustomShippingQuotesRegion quoteRegion = new CustomShippingQuotesRegion(); - quoteRegion.setCustomRegionName(region); - - customConfiguration.getRegions().add(quoteRegion); - shippingService.saveCustomShippingConfiguration(this.WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - - model.addAttribute("customConfiguration", customConfiguration); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Shipping.shippingMethod; - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/addCountryToRegion.html", method=RequestMethod.POST) - public String addCountryToCustomRegion(@ModelAttribute("customRegion") CustomShippingQuotesRegion customRegion, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - populateModel(model, request, response); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - - - if(StringUtils.isBlank(customRegion.getCustomRegionName())) { - model.addAttribute("errorMessageAssociation",messages.getMessage("message.region.null", locale)); - ObjectError error = new ObjectError("region",messages.getMessage("message.region.exists", locale)); - result.addError(error); - } - - - for(CustomShippingQuotesRegion region : regions) { - if(region.getCustomRegionName().equals(customRegion.getCustomRegionName())) { - List<String> countries = region.getCountries(); - if(countries!=null) { - for(String countryCode : countries) { - if(countryCode.equals(customRegion.getCountries().get(0))) { - model.addAttribute("errorMessageAssociation",messages.getMessage("message.region.exists", locale)); - ObjectError error = new ObjectError("region",messages.getMessage("message.region.exists", locale)); - result.addError(error); - break; - } - } - - countries.add(customRegion.getCountries().get(0)); - - } else { - List<String> countriesList = new ArrayList<String>(); - countriesList.add(customRegion.getCountries().get(0)); - region.setCountries(countriesList); - } - } - } - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Shipping.shippingMethod; - } - - - shippingService.saveCustomShippingConfiguration(this.WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - model.addAttribute("customConfiguration", customConfiguration); - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Shipping.shippingMethod; - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/saveweightBasedShippingMethod.html", method=RequestMethod.POST) - public String saveShippingMethod(@ModelAttribute("configuration") CustomShippingQuotesConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - populateModel(model, request, response); - - String moduleCode = configuration.getModuleCode(); - LOGGER.debug("Saving module code " + moduleCode); - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.TEST_ENVIRONMENT); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - model.addAttribute("environments", environments); - model.addAttribute("configuration", configuration); - - try { - - - CustomShippingQuotesConfiguration dbConfig = (CustomShippingQuotesConfiguration) shippingService.getCustomShippingConfiguration(this.WEIGHT_BASED_SHIPPING_METHOD, store); - - - shippingService.saveShippingQuoteModuleConfiguration(configuration, store); - if(dbConfig!=null) { - dbConfig.setActive(configuration.isActive()); - shippingService.saveCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, dbConfig, store); - } else { - shippingService.saveCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, configuration, store); - } - - - - - } catch (Exception e) { - if(e instanceof IntegrationException) { - if(((IntegrationException)e).getErrorCode()==IntegrationException.ERROR_VALIDATION_SAVE) { - - List<String> errorCodes = ((IntegrationException)e).getErrorFields(); - for(String errorCode : errorCodes) { - model.addAttribute(errorCode,messages.getMessage("message.fielderror", locale)); - } - return ControllerConstants.Tiles.Shipping.shippingMethod; - } - } else { - throw new Exception(e); - } - } - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingMethod; - - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased/removeCountry.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deleteCountry(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String country = request.getParameter("regionCode"); - - AjaxResponse resp = new AjaxResponse(); - - - try { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - if(customConfiguration!=null) { - - List<CustomShippingQuotesRegion> quotes = customConfiguration.getRegions(); - for (CustomShippingQuotesRegion quote : quotes) { - List<String> countries = quote.getCountries(); - List<String> newCountries = new ArrayList<String>(); - if(countries!=null) { - for(String cntry : countries) { - if(!cntry.equals(country)) { - newCountries.add(cntry); - } - } - } - quote.setCountries(newCountries); - } - - } - - shippingService.saveCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while paging custom weight based", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased/removePrice.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> deletePrice(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String weight = request.getParameter("weight"); - String region = request.getParameter("region"); - int maxWeight = 0; - try { - maxWeight = Integer.parseInt(weight); - } catch (Exception e) { - LOGGER.error("Weight (integer) malformed " + weight); - } - - AjaxResponse resp = new AjaxResponse(); - - - try { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - if(customConfiguration!=null) { - - List<CustomShippingQuotesRegion> quotes = customConfiguration.getRegions(); - - for (CustomShippingQuotesRegion quote : quotes) { - - - if(quote.getCustomRegionName().equals(region)) { - List<CustomShippingQuoteWeightItem> quoteItems = quote.getQuoteItems(); - - if(quoteItems!=null) { - List<CustomShippingQuoteWeightItem> newQuoteItems = new ArrayList<CustomShippingQuoteWeightItem>(); - for(CustomShippingQuoteWeightItem q : quoteItems) { - if(maxWeight!=q.getMaximumWeight()) { - newQuoteItems.add(q); - } - } - quote.setQuoteItems(newQuoteItems); - break; - } - } - - } - - } - - shippingService.saveCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while paging custom weight based", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/deleteWeightBasedShippingMethod.html", method=RequestMethod.POST) - public String deleteShippingMethod(BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - shippingService.removeCustomShippingQuoteModuleConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - - return ControllerConstants.Tiles.Shipping.shippingMethods; - - } - - /** - * Check if a region code already exist with the same name - * @param request - * @param response - * @param locale - * @return - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/checkRegionCode.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkRegionCode(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String code = request.getParameter("code"); - - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - try { - - if(StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - if(customConfiguration!=null) { - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - for(CustomShippingQuotesRegion region : regions) { - - if(code.equals(region.getCustomRegionName())) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - } - } - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while getting user", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value = "/admin/shipping/weightBased/page.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageCustomShipping(HttpServletRequest request, - HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - Language language = (Language)request.getAttribute("LANGUAGE"); - try { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - Map<String,Country> countriesMap = countryService.getCountriesMap(language); - - if(customConfiguration!=null) { - List<CustomShippingQuotesRegion> quotes = customConfiguration.getRegions(); - for (CustomShippingQuotesRegion quote : quotes) { - List<String> countries = quote.getCountries(); - if(countries!=null) { - for(String country : countries) { - Map<String,String> entry = new HashMap<String,String> (); - entry.put("regionCode", country); - entry.put("region", quote.getCustomRegionName()); - entry.put("country", countriesMap.get(country).getName()); - resp.addDataEntry(entry); - } - } - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging custom weight based", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - /** - * Edit custom region - * @param region - * @param model - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased/edit.html", method=RequestMethod.GET) - public String editCustomShipping(@ModelAttribute("customRegionName") String region, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model,request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - CustomShippingQuotesRegion aRegion = null; - - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - for(CustomShippingQuotesRegion customRegion : regions) { - if(customRegion.getCustomRegionName().equals(region)) { - aRegion = customRegion; - break; - } - } - - if(aRegion==null) { - return "redirect:/admin/shipping/shippingMethods.html"; - } - - model.addAttribute("customRegion", aRegion); - - - return ControllerConstants.Tiles.Shipping.customShippingWeightBased; - } - - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value = "/admin/shipping/weightBasedDetails/page.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageCustomShippingDetails(HttpServletRequest request, - HttpServletResponse response) { - - String region = request.getParameter("region"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - if(StringUtils.isBlank(region)){ - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorString("Region is not valid"); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - try { - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - List<CustomShippingQuotesRegion> quotes = customConfiguration.getRegions(); - for (CustomShippingQuotesRegion quote : quotes) { - - if(quote.getCustomRegionName().equals(region)) { - - List<CustomShippingQuoteWeightItem> quoteItems = quote.getQuoteItems(); - if(quoteItems!=null) { - for(CustomShippingQuoteWeightItem quoteItem : quoteItems) { - Map<String,String> entry = new HashMap<String,String> (); - entry.put("price", priceUtil.getAdminFormatedAmountWithCurrency(store,quoteItem.getPrice())); - entry.put("weight", String.valueOf(quoteItem.getMaximumWeight())); - resp.addDataEntry(entry); - } - } - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased/addPrice.html", method=RequestMethod.POST) - public String addPrice(@ModelAttribute("region") String customRegion, @ModelAttribute("customQuote") CustomShippingQuoteWeightItem customQuote, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - - try { - BigDecimal price = MerchantUtils.getBigDecimal(customQuote.getPriceText()); - customQuote.setPrice(price); - } catch(Exception e) { - ObjectError error = new ObjectError("priceText",messages.getMessage("message.invalid.price", locale)); - result.addError(error); - } - - - int weight = customQuote.getMaximumWeight(); - if(weight<=0) { - ObjectError error = new ObjectError("maximumWeight",messages.getMessage("message.maximumWeight.invalid", locale)); - result.addError(error); - } - - - - for(CustomShippingQuotesRegion customReg : regions) { - if(customReg.getCustomRegionName().equals(customRegion)) { - model.addAttribute("customRegion", customReg); - break; - } - } - - - if(StringUtils.isBlank(customQuote.getPriceText())) { - ObjectError error = new ObjectError("priceText",messages.getMessage("message.invalid.price", locale)); - result.addError(error); - } - - CustomShippingQuotesRegion currentRegion = null; - - - for(CustomShippingQuotesRegion region : regions) { - if(region.getCustomRegionName().equals(customRegion)) { - currentRegion = region; - List<CustomShippingQuoteWeightItem> quotes = region.getQuoteItems(); - if(quotes!=null) { - for(CustomShippingQuoteWeightItem quote : quotes) { - - if(quote.getMaximumWeight()==customQuote.getMaximumWeight()){ - ObjectError error = new ObjectError("maximumWeight",messages.getMessage("label.message.maximumWeight.exist", locale)); - result.addError(error); - break; - } - } - quotes.add(customQuote); - } else { - quotes = new ArrayList<CustomShippingQuoteWeightItem>(); - quotes.add(customQuote); - region.setQuoteItems(quotes); - } - } - } - - model.addAttribute("customConfiguration", customConfiguration); - - if (result.hasErrors()) { - return ControllerConstants.Tiles.Shipping.customShippingWeightBased; - } - - //order weights - if(currentRegion!=null) { - List<CustomShippingQuoteWeightItem> quotes = currentRegion.getQuoteItems(); - if(quotes!=null) { - - - BeanComparator beanComparator = new BeanComparator("maximumWeight"); - Collections.sort(quotes, beanComparator); - - - } - } - - - shippingService.saveCustomShippingConfiguration(this.WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - - model.addAttribute("success","success"); - - return ControllerConstants.Tiles.Shipping.customShippingWeightBased; - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased/deleteRegion.html", method=RequestMethod.POST) - public String deleteRegion(@ModelAttribute("customRegionName") String region, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions(); - - List<CustomShippingQuotesRegion> newRegions = new ArrayList<CustomShippingQuotesRegion>(); - for(CustomShippingQuotesRegion reg : regions) { - - if(!reg.getCustomRegionName().equals(region)) { - newRegions.add(reg); - } - } - - customConfiguration.setRegions(newRegions); - shippingService.saveCustomShippingConfiguration(this.WEIGHT_BASED_SHIPPING_METHOD, customConfiguration, store); - populateModel(model, request, response); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingMethod; - } - - - - - - private void populateModel(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL); - } - - - //get configured shipping modules - Map<String,IntegrationConfiguration> configuredModules = shippingService.getShippingModulesConfigured(store); - IntegrationConfiguration configuration = new IntegrationConfiguration(); - if(configuredModules!=null) { - for(String key : configuredModules.keySet()) { - if(key.equals(WEIGHT_BASED_SHIPPING_METHOD)) { - configuration = configuredModules.get(key); - break; - } - } - } - configuration.setModuleCode(WEIGHT_BASED_SHIPPING_METHOD); - - //get custom information - CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)shippingService.getCustomShippingConfiguration(WEIGHT_BASED_SHIPPING_METHOD, store); - - if(customConfiguration==null) { - customConfiguration = new CustomShippingQuotesConfiguration(); - customConfiguration.setModuleCode(this.WEIGHT_BASED_SHIPPING_METHOD); - } - - - //get supported countries - //List<String> includedCountries = shippingService.getSupportedCountries(store); - List<Country> shipToCountries = shippingService.getShipToCountryList(store, language); -/* List<Country> shippingCountries = new ArrayList<Country>(); - Map<String,Country> countries = countryService.getCountriesMap(language); - if(shippingConfiguration.getShippingType().name().equals(ShippingType.INTERNATIONAL.name())){ - - for(String key : countries.keySet()) { - Country country = (Country)countries.get(key); - if(includedCountries.contains(key)) { - shippingCountries.add(country); - } - } - } else {//if national only store country - if(!includedCountries.contains(store.getCountry().getIsoCode())) { - shippingCountries.add((Country)countries.get(store.getCountry().getIsoCode())); - } - }*/ - - CustomShippingQuotesRegion customRegion = new CustomShippingQuotesRegion(); - - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT);//only production - - model.addAttribute("environments", environments); - model.addAttribute("configuration", configuration); - model.addAttribute("customConfiguration", customConfiguration); - model.addAttribute("customRegion", customRegion); - model.addAttribute("shippingCountries", shipToCountries); - - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-methods", "shipping-methods"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/ShippingConfigsController.java+0 −234 removed@@ -1,234 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.shipping.ShippingService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.shipping.ShippingConfiguration; -import com.salesmanager.core.model.shipping.ShippingType; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; - - -@Controller -public class ShippingConfigsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ShippingConfigsController.class); - - - @Inject - private ShippingService shippingService; - - @Inject - private CountryService countryService; - - /** - * Configures the shipping mode, shows shipping countries - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/shippingConfigs.html", method=RequestMethod.GET) - public String displayShippingConfigs(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL); - } - - - model.addAttribute("configuration", shippingConfiguration); - return "shipping-configs"; - - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/saveShippingConfiguration.html", method=RequestMethod.POST) - public String saveShippingConfiguration(@ModelAttribute("configuration") ShippingConfiguration configuration, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get original configuration - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - } - - shippingConfiguration.setShippingType(configuration.getShippingType()); - - shippingService.saveShippingConfiguration(shippingConfiguration, store); - - model.addAttribute("configuration", shippingConfiguration); - model.addAttribute("success","success"); - return "shipping-configs"; - - } - - @SuppressWarnings({ "unchecked"}) - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/countries/paging.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> pageCountries(HttpServletRequest request, HttpServletResponse response) { - String countryName = request.getParameter("name"); - AjaxResponse resp = new AjaxResponse(); - - try { - - Language language = (Language)request.getAttribute("LANGUAGE"); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get list of countries - Map<String,Country> countries = countryService.getCountriesMap(language); - - //get inclusions - List<String> includedCountries = shippingService.getSupportedCountries(store); - - - for(String key : countries.keySet()) { - - Country country = (Country)countries.get(key); - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("code", country.getIsoCode()); - entry.put("name", country.getName()); - - if(includedCountries.contains(key)) { - entry.put("supported", true); - } else { - entry.put("supported", false); - } - - if(!StringUtils.isBlank(countryName)) { - if(country.getName().contains(countryName)){ - resp.addDataEntry(entry); - } - } else { - resp.addDataEntry(entry); - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging shipping countries", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/countries/update.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> updateCountry(HttpServletRequest request, HttpServletResponse response) { - String values = request.getParameter("_oldValues"); - String supported = request.getParameter("supported"); - - - - - - - AjaxResponse resp = new AjaxResponse(); - - try { - - ObjectMapper mapper = new ObjectMapper(); - @SuppressWarnings("rawtypes") - Map conf = mapper.readValue(values, Map.class); - - String countryCode = (String)conf.get("code"); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get list of countries - List<String> includedCountries = shippingService.getSupportedCountries(store); - - if(!StringUtils.isBlank(supported)) { - if("true".equals(supported)) { - includedCountries.add(countryCode); - } else { - includedCountries.remove(countryCode); - } - } - - - shippingService.setSupportedCountries(store, includedCountries); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while paging shipping countries", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-configs", "shipping-configs"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/ShippingMethodsController.java+0 −182 removed@@ -1,182 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import com.salesmanager.core.business.services.shipping.ShippingService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.system.IntegrationConfiguration; -import com.salesmanager.core.model.system.IntegrationModule; -import com.salesmanager.core.modules.integration.IntegrationException; -import com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesConfiguration; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - -@Controller -public class ShippingMethodsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ShippingMethodsController.class); - - - @Inject - private ShippingService shippingService; - - @Inject - LabelUtils messages; - - /** - * Configures the shipping shows shipping methods - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/shippingMethods.html", method=RequestMethod.GET) - public String displayShippingMethods(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get shipping methods - List<IntegrationModule> modules = shippingService.getShippingMethods(store); - - //get configured shipping modules - Map<String,IntegrationConfiguration> configuredModules = shippingService.getShippingModulesConfigured(store); - - - - model.addAttribute("modules", modules); - model.addAttribute("configuredModules", configuredModules); - - - return ControllerConstants.Tiles.Shipping.shippingMethods; - - - } - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/shippingMethod.html", method=RequestMethod.GET) - public String displayShippingMethod(@RequestParam("code") String code, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //get configured shipping modules - IntegrationConfiguration configuration = shippingService.getShippingConfiguration(code, store); - if(configuration==null) { - configuration = new IntegrationConfiguration(); - } - - configuration.setModuleCode(code); - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.TEST_ENVIRONMENT); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - model.addAttribute("configuration", configuration); - model.addAttribute("environments", environments); - return ControllerConstants.Tiles.Shipping.shippingMethod; - - - } - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/saveShippingMethod.html", method=RequestMethod.POST) - public String saveShippingMethod(@ModelAttribute("configuration") IntegrationConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - String moduleCode = configuration.getModuleCode(); - LOGGER.debug("Saving module code " + moduleCode); - - List<String> environments = new ArrayList<String>(); - environments.add(com.salesmanager.core.business.constants.Constants.TEST_ENVIRONMENT); - environments.add(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT); - - model.addAttribute("environments", environments); - model.addAttribute("configuration", configuration); - - try { - shippingService.saveShippingQuoteModuleConfiguration(configuration, store); - } catch (Exception e) { - if(e instanceof IntegrationException) { - if(((IntegrationException)e).getErrorCode()==IntegrationException.ERROR_VALIDATION_SAVE) { - - List<String> errorCodes = ((IntegrationException)e).getErrorFields(); - for(String errorCode : errorCodes) { - model.addAttribute(errorCode,messages.getMessage("message.fielderror", locale)); - } - model.addAttribute("validationError","validationError"); - return ControllerConstants.Tiles.Shipping.shippingMethod; - } - } else { - throw new Exception(e); - } - } - - - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingMethod; - - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/weightBased.html", method=RequestMethod.POST) - public String saveCustomWeightBasedShippingMethod(@ModelAttribute("configuration") CustomShippingQuotesConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingMethod; - - } - - @RequestMapping(value="/admin/shipping/deleteShippingMethod.html", method=RequestMethod.POST) - public String deleteShippingMethod(@RequestParam("code") String code, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - shippingService.removeShippingQuoteModuleConfiguration(code, store); - - return "redirect:/admin/shipping/shippingMethods.html"; - - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-methods", "shipping-methods"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/ShippingOptionsController.java+0 −176 removed@@ -1,176 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import java.math.BigDecimal; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.inject.Inject; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.shipping.ShippingConfiguration; -import com.salesmanager.core.model.shipping.ShippingType; -import com.salesmanager.core.business.services.shipping.ShippingService; -import com.salesmanager.core.business.utils.ProductPriceUtils; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; - -@Controller -public class ShippingOptionsController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ShippingOptionsController.class); - - - @Inject - private ShippingService shippingService; - - @Inject - LabelUtils messages; - - @Inject - private ProductPriceUtils priceUtil; - - /** - * Displays shipping options - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/shippingOptions.html", method=RequestMethod.GET) - public String displayShippingOptions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL); - } - - if(shippingConfiguration!=null) { - - if(shippingConfiguration.getHandlingFees()!=null) { - shippingConfiguration.setHandlingFeesText(priceUtil.getAdminFormatedAmount(store,shippingConfiguration.getHandlingFees())); - } - - if(shippingConfiguration.getOrderTotalFreeShipping()!=null) { - shippingConfiguration.setOrderTotalFreeShippingText(priceUtil.getAdminFormatedAmount(store,shippingConfiguration.getOrderTotalFreeShipping())); - } - - } - - - model.addAttribute("configuration", shippingConfiguration); - return ControllerConstants.Tiles.Shipping.shippingOptions; - - - } - - /** - * Saves shipping options - * @param configuration - * @param result - * @param model - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/saveShippingOptions.html", method=RequestMethod.POST) - public String saveShippingOptions(@ModelAttribute("configuration") ShippingConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get original configuration - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - } - - BigDecimal submitedOrderPrice = null; - if(!StringUtils.isBlank(configuration.getOrderTotalFreeShippingText())){ - try { - submitedOrderPrice = priceUtil.getAmount(configuration.getOrderTotalFreeShippingText()); - shippingConfiguration.setOrderTotalFreeShipping(submitedOrderPrice); - } catch (Exception e) { - ObjectError error = new ObjectError("orderTotalFreeShippingText",messages.getMessage("message.invalid.price", locale)); - result.addError(error); - } - } - - BigDecimal submitedHandlingPrice = null; - if(!StringUtils.isBlank(configuration.getHandlingFeesText())){ - try { - submitedHandlingPrice = priceUtil.getAmount(configuration.getHandlingFeesText()); - shippingConfiguration.setHandlingFees(submitedHandlingPrice); - } catch (Exception e) { - ObjectError error = new ObjectError("handlingFeesText",messages.getMessage("message.invalid.price", locale)); - result.addError(error); - } - } - - shippingConfiguration.setFreeShippingEnabled(configuration.isFreeShippingEnabled()); - shippingConfiguration.setTaxOnShipping(configuration.isTaxOnShipping()); - if(configuration.getShipFreeType()!=null) { - shippingConfiguration.setShipFreeType(configuration.getShipFreeType()); - } - shippingConfiguration.setShipOptionPriceType(configuration.getShipOptionPriceType()); - - shippingService.saveShippingConfiguration(shippingConfiguration, store); - - model.addAttribute("configuration", configuration); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingOptions; - - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-options", "shipping-options"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/ShippingOriginController.java+0 −168 removed@@ -1,168 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.shipping.ShippingOriginService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.reference.zone.Zone; -import com.salesmanager.core.model.shipping.ShippingOrigin; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - - -@Controller -public class ShippingOriginController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ShippingOriginController.class); - - - @Inject - private ShippingOriginService shippingOriginService; - - @Inject - private CountryService countryService; - - @Inject - private ZoneService zoneService; - - /** - * Configures the shipping mode, shows shipping countries - * @param request - * @param response - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/origin/get.html", method=RequestMethod.GET) - public String displayShippingOrigin(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store); - - List<Country> countries = countryService.getCountries(language); - - if(shippingOrigin==null) { - shippingOrigin = new ShippingOrigin(); - shippingOrigin.setCountry(store.getCountry()); - shippingOrigin.setState(store.getStorestateprovince()); - shippingOrigin.setZone(store.getZone()); - } - - model.addAttribute("countries", countries); - model.addAttribute("origin", shippingOrigin); - return "shipping-origin"; - - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/origin/post.html", method=RequestMethod.POST) - public String saveShippingOrigin(@Valid @ModelAttribute("origin") ShippingOrigin origin, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - List<Country> countries = countryService.getCountries(language); - - ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store); - if(shippingOrigin!=null) { - origin.setId(shippingOrigin.getId()); - } - - origin.setMerchantStore(store); - - Country country = countryService.getByCode(origin.getCountry().getIsoCode()); - origin.setCountry(country); - - if(origin.getZone() !=null) { - Zone zone = zoneService.getByCode(origin.getZone().getCode()); - origin.setZone(zone); - } - - if(shippingOrigin!=null) { - shippingOriginService.update(origin); - } else { - shippingOriginService.save(origin); - } - - model.addAttribute("countries", countries); - model.addAttribute("origin", origin); - model.addAttribute("success","success"); - return "shipping-origin"; - - } - - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/origin/delete.html", method=RequestMethod.POST) - public String deleteShippingOrigin(@ModelAttribute("origin") ShippingOrigin origin, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store); - - Language language = (Language)request.getAttribute("LANGUAGE"); - List<Country> countries = countryService.getCountries(language); - - - if(shippingOrigin!=null && origin !=null) { - if(shippingOrigin.getId().longValue() == origin.getId().longValue()) { - shippingOriginService.delete(shippingOrigin); - model.addAttribute("success","success"); - } else { - return "redirect:/admin/shipping/origin/get.html"; - } - } else { - return "redirect:/admin/shipping/origin/get.html"; - } - - model.addAttribute("countries", countries); - model.addAttribute("origin", null); - model.addAttribute("success","success"); - return "shipping-origin"; - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-origin", "shipping-origin"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/shipping/ShippingPackagingController.java+0 −140 removed@@ -1,140 +0,0 @@ -package com.salesmanager.shop.admin.controller.shipping; - -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.salesmanager.core.business.services.shipping.ShippingService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.shipping.ShippingConfiguration; -import com.salesmanager.core.model.shipping.ShippingType; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; - -@Controller -public class ShippingPackagingController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ShippingPackagingController.class); - - - @Inject - private ShippingService shippingService; - - @Inject - LabelUtils messages; - - - /** - * Displays shipping packaging - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/shippingPackaging.html", method=RequestMethod.GET) - public String displayShippingPackaging(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - - this.setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL); - } - - model.addAttribute("configuration", shippingConfiguration); - model.addAttribute("store",store); - return ControllerConstants.Tiles.Shipping.shippingPackaging; - - - } - - /** - * Saves shipping packaging - * @param configuration - * @param result - * @param model - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('SHIPPING')") - @RequestMapping(value="/admin/shipping/saveShippingPackaging.html", method=RequestMethod.POST) - public String saveShippingPackaging(@ModelAttribute("configuration") ShippingConfiguration configuration, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - this.setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - //get original configuration - ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store); - - if(shippingConfiguration==null) { - shippingConfiguration = new ShippingConfiguration(); - } - - DecimalFormat df = new DecimalFormat("#.##"); - String sweight = df.format(configuration.getBoxWeight()); - double weight = Double.parseDouble(sweight); - - shippingConfiguration.setBoxHeight(configuration.getBoxHeight()); - shippingConfiguration.setBoxLength(configuration.getBoxLength()); - shippingConfiguration.setBoxWeight(weight); - shippingConfiguration.setBoxWidth(configuration.getBoxWidth()); - - shippingConfiguration.setShipPackageType(configuration.getShipPackageType()); - - - shippingService.saveShippingConfiguration(shippingConfiguration, store); - - model.addAttribute("configuration", configuration); - model.addAttribute("success","success"); - return ControllerConstants.Tiles.Shipping.shippingPackaging; - - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("shipping", "shipping"); - activeMenus.put("shipping-packages", "shipping-packages"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("shipping"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/tax/TaxClassController.java+0 −312 removed@@ -1,312 +0,0 @@ -package com.salesmanager.shop.admin.controller.tax; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.tax.TaxClassService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.tax.taxclass.TaxClass; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -@Controller -public class TaxClassController { - - @Inject - private TaxClassService taxClassService = null; - - @Inject - private ProductService productService=null; - - @Inject - LabelUtils messages; - - private static final Logger LOGGER = LoggerFactory.getLogger(TaxClassController.class); - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value={"/admin/tax/taxclass/list.html"}, method=RequestMethod.GET) - public String displayTaxClasses(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - TaxClass taxClass = new TaxClass(); - taxClass.setMerchantStore(store); - - model.addAttribute("taxClass", taxClass); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClasses; - } - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value = "/admin/tax/taxclass/paging.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageTaxClasses(HttpServletRequest request, - HttpServletResponse response, Locale locale) { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - AjaxResponse resp = new AjaxResponse(); - try { - - List<TaxClass> taxClasses = taxClassService.listByStore(store); - for(TaxClass tax : taxClasses) { - if(!tax.getCode().equals(TaxClass.DEFAULT_TAX_CLASS)) { - Map<String,String> entry = new HashMap<String,String>(); - entry.put("taxClassId", String.valueOf(tax.getId())); - entry.put("code", tax.getCode()); - entry.put("name", tax.getTitle()); - resp.addDataEntry(entry); - } - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging permissions", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxclass/save.html", method=RequestMethod.POST) - public String saveTaxClass(@Valid @ModelAttribute("taxClass") TaxClass taxClass, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //requires code and name - if(taxClass.getCode().equals(TaxClass.DEFAULT_TAX_CLASS)) { - ObjectError error = new ObjectError("code",messages.getMessage("message.taxclass.alreadyexist", locale)); - result.addError(error); - } - - - - //check if the code already exist - TaxClass taxClassDb = taxClassService.getByCode(taxClass.getCode(),store); - - if(taxClassDb!=null) { - ObjectError error = new ObjectError("code",messages.getMessage("message.taxclass.alreadyexist", locale)); - result.addError(error); - } - - if (result.hasErrors()) { - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClasses; - } - - taxClassService.create(taxClass); - - model.addAttribute("success","success"); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClasses; - - } - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxclass/update.html", method=RequestMethod.POST) - public String updateTaxClass(@Valid @ModelAttribute("taxClass") TaxClass taxClass, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - //requires code and name - if(taxClass.getCode().equals(TaxClass.DEFAULT_TAX_CLASS)) { - ObjectError error = new ObjectError("code",messages.getMessage("message.taxclass.alreadyexist", locale)); - result.addError(error); - } - - - - //check if the code already exist - TaxClass taxClassDb = taxClassService.getByCode(taxClass.getCode(),store); - - if(taxClassDb!=null && taxClassDb.getId().longValue()!=taxClass.getId().longValue()) { - ObjectError error = new ObjectError("code",messages.getMessage("message.taxclass.alreadyexist", locale)); - result.addError(error); - } - - if (result.hasErrors()) { - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClass; - } - - taxClassService.update(taxClass); - - model.addAttribute("success","success"); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClass; - - } - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxclass/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeTaxClass(HttpServletRequest request, Locale locale) throws Exception { - - //do not remove super admin - - String taxClassId = request.getParameter("taxClassId"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - /** - * In order to remove a User the logged in ser must be ADMIN - * or SUPER_USER - */ - - - if(taxClassId==null){ - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - long lTaxClassId; - try { - lTaxClassId = Long.parseLong(taxClassId); - } catch (Exception e) { - LOGGER.error("Invalid taxClassId " + taxClassId); - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - TaxClass taxClass = taxClassService.getById(lTaxClassId); - - if(taxClass==null) { - LOGGER.error("Invalid taxClassId " + taxClassId); - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - //look if the taxclass is used for products - List<Product> products = productService.listByTaxClass(taxClass); - - if(products!=null && products.size()>0) { - resp.setStatusMessage(messages.getMessage("message.product.association", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - taxClassService.delete(taxClass); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting tax class", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxclass/edit.html", method=RequestMethod.GET) - public String editTaxClass(@ModelAttribute("id") String id, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - TaxClass taxClass = null; - try { - Long taxClassId = Long.parseLong(id); - taxClass = taxClassService.getById(taxClassId); - } catch (Exception e) { - LOGGER.error("Cannot parse taxclassid " + id); - return "redirect:/admin/tax/taxclass/list.html"; - } - - if(taxClass==null || taxClass.getMerchantStore().getId()!=store.getId()) { - return "redirect:/admin/tax/taxclass/list.html"; - } - - - - - model.addAttribute("taxClass", taxClass); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxClass; - - - - } - - - - private void setMenu(Model model, HttpServletRequest request) - throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("tax", "tax"); - activeMenus.put("taxclass", "taxclass"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request - .getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("tax"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/tax/TaxConfigurationController.java+0 −87 removed@@ -1,87 +0,0 @@ -package com.salesmanager.shop.admin.controller.tax; - -import com.salesmanager.core.business.services.tax.TaxService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.tax.TaxConfiguration; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -@Controller -public class TaxConfigurationController { - - @Inject - private TaxService taxService = null; - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value={"/admin/tax/taxconfiguration/edit.html"}, method=RequestMethod.GET) - public String displayTaxConfiguration(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - TaxConfiguration taxConfiguration = taxService.getTaxConfiguration(store); - if(taxConfiguration == null) { - - taxConfiguration = new TaxConfiguration(); - - } - - model.addAttribute("taxConfiguration", taxConfiguration); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxConfiguration; - } - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxconfiguration/save.html", method=RequestMethod.POST) - public String saveTaxConfiguration(@Valid @ModelAttribute("taxConfiguration") TaxConfiguration taxConfiguration, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - taxService.saveTaxConfiguration(taxConfiguration, store); - - model.addAttribute("success","success"); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxConfiguration; - - } - - - private void setMenu(Model model, HttpServletRequest request) - throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("tax", "tax"); - activeMenus.put("taxconfiguration", "taxconfiguration"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request - .getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("tax"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/tax/TaxRatesController.java+0 −473 removed@@ -1,473 +0,0 @@ -package com.salesmanager.shop.admin.controller.tax; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.tax.TaxClassService; -import com.salesmanager.core.business.services.tax.TaxRateService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.country.Country; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.reference.zone.Zone; -import com.salesmanager.core.model.tax.taxclass.TaxClass; -import com.salesmanager.core.model.tax.taxrate.TaxRate; -import com.salesmanager.core.model.tax.taxrate.TaxRateDescription; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; -import java.math.BigDecimal; -import java.text.NumberFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - - -@Controller -public class TaxRatesController { - - - private static final Logger LOGGER = LoggerFactory.getLogger(TaxRatesController.class); - - private final static char DECIMALCOUNT = '3'; - - - @Inject - LabelUtils messages; - - @Inject - private CountryService countryService; - - @Inject - private TaxRateService taxRateService; - - @Inject - private TaxClassService taxClassService; - - @Inject - private ZoneService zoneService; - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value={"/admin/tax/taxrates/list.html"}, method=RequestMethod.GET) - public String displayTaxRates(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model, request); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - - List<Country> countries = countryService.getCountries(language); - TaxRate taxRate = new TaxRate(); - List<Language> languages = store.getLanguages(); - - for(Language l : languages) { - TaxRateDescription taxRateDescription = new TaxRateDescription(); - taxRateDescription.setLanguage(l); - taxRate.getDescriptions().add(taxRateDescription); - } - - taxRate.setMerchantStore(store); - taxRate.setCountry(store.getCountry()); - - List<TaxRate> taxRates = taxRateService.listByStore(store); - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - model.addAttribute("taxRate", taxRate); - model.addAttribute("countries", countries); - model.addAttribute("taxRates", taxRates); - model.addAttribute("taxClasses", taxClasses); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRates; - } - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value = "/admin/tax/taxrates/page.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageTaxRates(HttpServletRequest request, - HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - - - try { - - NumberFormat nf = null; - - - nf = NumberFormat.getInstance(Locale.US); - nf.setMaximumFractionDigits(Integer.parseInt(Character - .toString(DECIMALCOUNT))); - nf.setMinimumFractionDigits(Integer.parseInt(Character - .toString(DECIMALCOUNT))); - - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - List<TaxRate> taxRates = taxRateService.listByStore(store,language); - - if(taxRates!=null) { - for (TaxRate rate : taxRates) { - - Map entry = new HashMap (); - entry.put("taxRateId", String.valueOf(rate.getId())); - entry.put("code", rate.getCode()); - List<TaxRateDescription> descriptions = rate.getDescriptions(); - String name = ""; - if(descriptions!=null && descriptions.size()>0) { - TaxRateDescription desc = descriptions.get(0); - for(TaxRateDescription description : descriptions) { - if(description.getLanguage().getCode().equals(language.getCode())) { - desc = description; - break; - } - } - name = desc.getName(); - } - - entry.put("name", name); - entry.put("priority", rate.getTaxPriority()); - - entry.put("piggyback", rate.isPiggyback()); - entry.put("country", rate.getCountry().getIsoCode()); - entry.put("taxClass", rate.getTaxClass().getCode()); - - - String zoneCode = rate.getStateProvince(); - if(rate.getZone()!=null) { - zoneCode = rate.getZone().getCode(); - } - entry.put("zone", zoneCode); - entry.put("rate", nf.format(rate.getTaxRate())); - - resp.addDataEntry(entry); - - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging custom weight based", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxrates/save.html", method=RequestMethod.POST) - public String saveTaxRate(@Valid @ModelAttribute("taxRate") TaxRate taxRate, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - - this.validateTaxRate(model, taxRate, result, store, language, locale); - - if (result.hasErrors()) { - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRates; - - } - - - taxRateService.create(taxRate); - - List<TaxRate> taxRates = taxRateService.listByStore(store); - - model.addAttribute("success","success"); - model.addAttribute("taxRates", taxRates); - - - - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRates; - - } - - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxrates/update.html", method=RequestMethod.POST) - public String updateTaxRate(@Valid @ModelAttribute("taxRate") TaxRate taxRate, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - setMenu(model, request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - Language language = (Language)request.getAttribute("LANGUAGE"); - - this.validateTaxRate(model, taxRate, result, store, language, locale); - - if (result.hasErrors()) { - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRate; - - } - - - taxRateService.update(taxRate); - - List<TaxRate> taxRates = taxRateService.listByStore(store); - - model.addAttribute("success","success"); - model.addAttribute("taxRates", taxRates); - - - - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRate; - - - } - - private void validateTaxRate(Model model, TaxRate taxRate, BindingResult result, MerchantStore store, Language language, Locale locale) throws Exception { - - - - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - - List<Country> countries = countryService.getCountries(language); - List<TaxRate> taxRates = taxRateService.listByStore(store); - - - model.addAttribute("countries", countries); - model.addAttribute("taxRates", taxRates); - model.addAttribute("taxClasses", taxClasses); - - if(StringUtils.isBlank(taxRate.getRateText())) { - FieldError error = new FieldError("taxRate","rateText",messages.getMessage("NotEmpty.taxRate.rateText", locale)); - result.addError(error); - } - - //if(taxRate.isPiggyback() && taxRate.getParent()==null) { - //FieldError error = new FieldError("taxRate","piggyback",messages.getMessage("NotNull.taxRate.parent", locale)); - //result.addError(error); - //} - - try { - BigDecimal rate = new BigDecimal(taxRate.getRateText()); - taxRate.setTaxRate(rate); - } catch (Exception e) { - FieldError error = new FieldError("taxRate","rateText",messages.getMessage("message.invalid.rate", locale)); - result.addError(error); - } - - //check if code exists - String taxRateCode = taxRate.getCode(); - TaxRate tr = taxRateService.getByCode(taxRateCode, store); - if(tr!=null) { - if(tr.getId().longValue()!=taxRate.getId().longValue()){ - FieldError error = new FieldError("taxRate","code",messages.getMessage("NotEmpty.taxRate.unique.code", locale)); - result.addError(error); - } - } - - - if(taxRate.getTaxPriority()==null) { - taxRate.setTaxPriority(0); - } - - - if(taxRate.getZone()!=null) { - Zone z = zoneService.getById(taxRate.getZone().getId()); - taxRate.setZone(z); - } - - - - Country c = countryService.getByCode(taxRate.getCountry().getIsoCode()); - - taxRate.setCountry(c); - - List<TaxRateDescription> descriptions = taxRate.getDescriptions(); - for(TaxRateDescription description : descriptions) { - description.setTaxRate(taxRate); - } - - if(!taxRate.isPiggyback()) { - taxRate.setParent(null); - } - - return; - - } - - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxrates/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeTaxRate(HttpServletRequest request, Locale locale) throws Exception { - - //do not remove super admin - - String taxRateId = request.getParameter("taxRateId"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - - /** - * In order to remove a User the logged in must be ADMIN - * or SUPER_USER - */ - - - if(taxRateId==null){ - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - long ltaxRateId; - try { - ltaxRateId = Long.parseLong(taxRateId); - } catch (Exception e) { - LOGGER.error("Invalid taxRateId " + taxRateId); - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - TaxRate taxRate = taxRateService.getById(ltaxRateId); - - if(taxRate==null) { - LOGGER.error("Invalid taxRateId " + taxRateId); - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - taxRateService.delete(taxRate); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting tax rate", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('TAX')") - @RequestMapping(value="/admin/tax/taxrates/edit.html", method=RequestMethod.GET) - public String editTaxRate(@ModelAttribute("id") String id, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language language = (Language)request.getAttribute("LANGUAGE"); - - TaxRate taxRate = null; - try { - Long taxRateId = Long.parseLong(id); - taxRate = taxRateService.getById(taxRateId); - } catch (Exception e) { - LOGGER.error("Cannot parse taxRateId " + id); - return "redirect:/admin/tax/taxrates/list.html"; - } - - if(taxRate==null || taxRate.getMerchantStore().getId()!=store.getId()) { - return "redirect:/admin/tax/taxrates/list.html"; - } - - - NumberFormat nf = null; - - - nf = NumberFormat.getInstance(Locale.US); - - nf.setMaximumFractionDigits(Integer.parseInt(Character - .toString(DECIMALCOUNT))); - nf.setMinimumFractionDigits(Integer.parseInt(Character - .toString(DECIMALCOUNT))); - - taxRate.setRateText(nf.format(taxRate.getTaxRate())); - - - - List<TaxClass> taxClasses = taxClassService.listByStore(store); - - - - List<Country> countries = countryService.getCountries(language); - List<TaxRate> taxRates = taxRateService.listByStore(store); - - - model.addAttribute("countries", countries); - model.addAttribute("taxRates", taxRates); - model.addAttribute("taxClasses", taxClasses); - - model.addAttribute("taxRate", taxRate); - - return com.salesmanager.shop.admin.controller.ControllerConstants.Tiles.Tax.taxRate; - - - - } - - - - - private void setMenu(Model model, HttpServletRequest request) - throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("tax", "tax"); - activeMenus.put("taxrates", "taxrates"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request - .getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("tax"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/user/GroupsController.java+0 −315 removed@@ -1,315 +0,0 @@ -package com.salesmanager.shop.admin.controller.user; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.business.services.user.PermissionService; -import com.salesmanager.core.business.utils.ajax.AjaxPageableResponse; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.user.Group; -import com.salesmanager.core.model.user.GroupType; -import com.salesmanager.shop.admin.model.permission.GroupDetails; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LabelUtils; - -@Controller -public class GroupsController { - - private static final Logger LOGGER = LoggerFactory - .getLogger(GroupsController.class); - - @Inject - LanguageService languageService; - - @Inject - protected GroupService groupService; - - @Inject - PermissionService permissionService; - - @Inject - CountryService countryService; - - @Inject - LabelUtils messages; - - - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/groups/editGroup.html", method = RequestMethod.GET) - public String displayGroup(@RequestParam("id") Integer groupId, Model model, - Locale locale, HttpServletRequest request, HttpServletResponse response) - throws Exception { - // display menu - setMenu(model, request); - - GroupType[] groupTypes = GroupType.values(); - List<String> groups = new ArrayList<String>(); - - for(GroupType t : groupTypes) { - if(GroupType.ADMIN.name() != t.name()) { - groups.add(t.name()); - } - } - - Group group = groupService.getById(groupId); - - if(group == null) { - return "redirect://admin/groups/groups.html"; - - } - - GroupDetails groupDetails = new GroupDetails(); - groupDetails.setGroup(group); - groupDetails.setTypes(groups); - - - model.addAttribute("group", groupDetails); - - return "admin-user-group"; - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/groups/delete.html", method = RequestMethod.POST) - public @ResponseBody ResponseEntity<String> delete(Model model, - Locale locale, HttpServletRequest request, HttpServletResponse response) - throws Exception { - // display menu - - String sGroupId = request.getParameter("groupId"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - - try { - - Integer groupId = Integer.parseInt(sGroupId); - Group group = groupService.getById(groupId); - - - if(group==null){ - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(!request.isUserInRole(Constants.GROUP_ADMIN)) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(GroupType.ADMIN.name().equals(group.getGroupType().name())) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - groupService.delete(group); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting group", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/group/save.html", method = RequestMethod.POST) - public String save(@Valid @ModelAttribute("group") GroupDetails group, BindingResult result, Locale locale, Model model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { - // display menu - setMenu(model, request); - - GroupType[] groupTypes = GroupType.values(); - List<String> groups = new ArrayList<String>(); - - for(GroupType t : groupTypes) { - if(GroupType.ADMIN.name() != t.name()) { - groups.add(t.name()); - } - } - - //check if already exists - Group g = null; - if(group.getGroup().getId()!=null) { - Group gid = groupService.getById(group.getGroup().getId()); - if(gid != null && !gid.getGroupName().equals(group.getGroup().getGroupName())) { - g = groupService.findByName(group.getGroup().getGroupName()); - } - } else { - g = groupService.findByName(group.getGroup().getGroupName()); - } - - if(g != null) { - ObjectError error = new ObjectError("group.groupName", messages.getMessage("message.name.exist", locale)); - result.addError(error); - model.addAttribute("error","error"); - } else { - groupService.save(group.getGroup()); - model.addAttribute("success","success"); - } - - GroupDetails groupDetails = new GroupDetails(); - groupDetails.setGroup(group.getGroup()); - groupDetails.setTypes(groups); - - - model.addAttribute("group", groupDetails); - - return "admin-user-group"; - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/groups/new.html", method = RequestMethod.GET) - public String displayGroup(Model model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { - // display menu - setMenu(model, request); - - GroupType[] groupTypes = GroupType.values(); - List<String> groups = new ArrayList<String>(); - - for(GroupType t : groupTypes) { - if(GroupType.ADMIN.name() != t.name()) { - groups.add(t.name()); - } - } - GroupDetails group = new GroupDetails(); - Group g = new Group(); - group.setGroup(g); - group.setTypes(groups); - model.addAttribute("group", group); - - - return "admin-user-group"; - } - - - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/groups/groups.html", method = RequestMethod.GET) - public String displayGroups(Model model, HttpServletRequest request, - HttpServletResponse response) throws Exception { - - setMenu(model, request); - List<Group> groups = groupService.listGroup(GroupType.ADMIN); - model.addAttribute("groups", groups); - - return "admin-user-groups"; - } - - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/groups/paging.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageGroups(HttpServletRequest request, - HttpServletResponse response, Locale locale) { - - AjaxResponse resp = new AjaxResponse(); - try { - - List<Group> groups = groupService.list(); - - for(Group group : groups) { - Map entry = new HashMap(); - entry.put("groupId", group.getId()); - entry.put("name", group.getGroupName()); - entry.put("type", group.getGroupType().name()); - - StringBuilder key = new StringBuilder().append("security.group.description.").append(group.getGroupName()); - try { - - String message = messages.getMessage(key.toString(), locale); - entry.put("description",message); - - } catch(Exception noLabelException) { - LOGGER.error("No label found for key [" + key.toString() + "]"); - } - - - - - resp.addDataEntry(entry); - } - - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging permissions", e); - resp.setStatus(AjaxPageableResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - private void setMenu(Model model, HttpServletRequest request) - throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("profile", "profile"); - activeMenus.put("security", "security"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request - .getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("profile"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/user/LoginController.java+0 −45 removed@@ -1,45 +0,0 @@ -package com.salesmanager.shop.admin.controller.user; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Controller -public class LoginController { - - - @RequestMapping(value="/admin/logon.html", method=RequestMethod.GET) - public String displayLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { - - return "admin/logon"; - - } - - - @RequestMapping(value="/admin/denied.html", method=RequestMethod.GET) - public String displayDenied(HttpServletRequest request, HttpServletResponse response) throws Exception { - - //logoff the user - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth != null){ - new SecurityContextLogoutHandler().logout(request, response, auth); - //new PersistentTokenBasedRememberMeServices().logout(request, response, auth); - } - - return "admin/logon"; - - } - - @RequestMapping(value="/admin/unauthorized.html", method=RequestMethod.GET) - public String unauthorized(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - return "admin/unauthorized"; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/user/PermissionController.java+0 −122 removed@@ -1,122 +0,0 @@ -package com.salesmanager.shop.admin.controller.user; - -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.business.services.user.PermissionService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.user.Permission; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.utils.LabelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Controller -public class PermissionController { - - private static final Logger LOGGER = LoggerFactory - .getLogger(PermissionController.class); - - @Inject - protected PermissionService permissionService; - - @Inject - protected GroupService groupService; - - @Inject - CountryService countryService; - - @Inject - LabelUtils messages; - - - - - - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/permissions/permissions.html", method = RequestMethod.GET) - public String displayPermissions(Model model, HttpServletRequest request, - HttpServletResponse response) throws Exception { - - //setMenu(model, request); - //return "admin-user-permissions"; - - throw new Exception("Not implemented"); - } - - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/permissions/paging.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pagePermissions(HttpServletRequest request, - HttpServletResponse response) { - //String permissionName = request.getParameter("name"); - - AjaxResponse resp = new AjaxResponse(); - - try { - - List<Permission> permissions = null; - permissions = permissionService.listPermission(); - - for (Permission permission : permissions) { - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("permissionId", permission.getId()); - entry.put("name", permission.getPermissionName()); - resp.addDataEntry(entry); - - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging permissions", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - @SuppressWarnings("unused") - private void setMenu(Model model, HttpServletRequest request) - throws Exception { - - // display menu - Map<String, String> activeMenus = new HashMap<String, String>(); - activeMenus.put("profile", "profile"); - activeMenus.put("security", "security"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>) request - .getAttribute("MENUMAP"); - - Menu currentMenu = (Menu) menus.get("profile"); - model.addAttribute("currentMenu", currentMenu); - model.addAttribute("activeMenus", activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/user/SecurityController.java+0 −65 removed@@ -1,65 +0,0 @@ -package com.salesmanager.shop.admin.controller.user; - -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.model.user.Group; -import com.salesmanager.core.model.user.GroupType; -import com.salesmanager.shop.admin.model.web.Menu; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Controller -public class SecurityController { - - @Inject - GroupService groupService; - - @RequestMapping(value="/admin/user/permissions.html", method=RequestMethod.GET) - public String displayPermissions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - return "admin-user-permissions"; - - - } - - - @RequestMapping(value="/admin/user/groups.html", method=RequestMethod.GET) - public String displayGroups(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { - - setMenu(model,request); - List<Group> groups = groupService.listGroup(GroupType.ADMIN); - - model.addAttribute("groups", groups); - - return "admin-user-groups"; - - - } - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("profile", "profile"); - activeMenus.put("security", "security"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("profile"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/controller/user/UserController.java+0 −866 removed@@ -1,866 +0,0 @@ -package com.salesmanager.shop.admin.controller.user; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.Valid; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.salesmanager.core.business.exception.ServiceException; -import com.salesmanager.core.business.modules.email.Email; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.system.EmailService; -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.business.services.user.UserService; -import com.salesmanager.core.business.utils.ajax.AjaxResponse; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.user.Group; -import com.salesmanager.core.model.user.GroupType; -import com.salesmanager.core.model.user.User; -import com.salesmanager.shop.admin.controller.ControllerConstants; -import com.salesmanager.shop.admin.model.secutity.Password; -import com.salesmanager.shop.admin.model.userpassword.UserReset; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.admin.security.SecurityQuestion; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.constants.EmailConstants; -import com.salesmanager.shop.utils.EmailUtils; -import com.salesmanager.shop.utils.FilePathUtils; -import com.salesmanager.shop.utils.LabelUtils; -import com.salesmanager.shop.utils.LocaleUtils; -import com.salesmanager.shop.utils.UserUtils; - -@Controller -public class UserController { - - private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); - - @Inject - private LanguageService languageService; - - @Inject - private UserService userService; - - @Inject - private GroupService groupService; - - @Inject - private EmailService emailService; - - @Inject - private MerchantStoreService merchantStoreService; - - @Inject - LabelUtils messages; - - @Inject - private FilePathUtils filePathUtils; - - @Inject - private EmailUtils emailUtils; - - @Inject - @Named("passwordEncoder") - private PasswordEncoder passwordEncoder; - - private final static String QUESTION_1 = "question1"; - private final static String QUESTION_2 = "question2"; - private final static String QUESTION_3 = "question3"; - private final static String RESET_PASSWORD_TPL = "email_template_password_reset_user.ftl"; - private final static String NEW_USER_TMPL = "email_template_new_user.ftl"; - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value="/admin/users/list.html", method=RequestMethod.GET) - public String displayUsers(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - //The users are retrieved from the paging method - setMenu(model,request); - return ControllerConstants.Tiles.User.users; - } - - /** - * Displays a list of users that can be managed by admins - * @param request - * @param response - * @return - */ - @SuppressWarnings("unchecked") - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/admin/users/paging.html", method = RequestMethod.POST) - public @ResponseBody - ResponseEntity<String> pageUsers(HttpServletRequest request, - HttpServletResponse response) { - - AjaxResponse resp = new AjaxResponse(); - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - String sCurrentUser = request.getRemoteUser(); - - - try { - - User currentUser = userService.getByUserName(sCurrentUser); - List<User> users = null; - if(UserUtils.userInGroup(currentUser, Constants.GROUP_SUPERADMIN) ) { - users = userService.listUser(); - } else { - users = userService.listByStore(store); - } - - - for (User user : users) { - - if(!UserUtils.userInGroup(user, Constants.GROUP_SUPERADMIN)) { - - if(!currentUser.equals(user.getAdminName())){ - - @SuppressWarnings("rawtypes") - Map entry = new HashMap(); - entry.put("userId", user.getId()); - entry.put("name", user.getFirstName() + " " + user.getLastName()); - entry.put("email", user.getAdminEmail()); - entry.put("active", user.isActive()); - resp.addDataEntry(entry); - - } - } - } - - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - - } catch (Exception e) { - LOGGER.error("Error while paging products", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,HttpStatus.OK); - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/password.html", method=RequestMethod.GET) - public String displayChangePassword(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - setMenu(model,request); - String userName = request.getRemoteUser(); - User user = userService.getByUserName(userName); - - Password password = new Password(); - password.setUser(user); - - model.addAttribute("password",password); - model.addAttribute("user",user); - return ControllerConstants.Tiles.User.password; - } - - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/savePassword.html", method=RequestMethod.POST) - public String changePassword(@ModelAttribute("password") Password password, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - setMenu(model,request); - String userName = request.getRemoteUser(); - User dbUser = userService.getByUserName(userName); - - - if(password.getUser().getId().longValue()!= dbUser.getId().longValue()) { - return "redirect:/admin/users/displayUser.html"; - } - - //validate password not empty - if(StringUtils.isBlank(password.getPassword())) { - ObjectError error = new ObjectError("password",new StringBuilder().append(messages.getMessage("label.generic.password", locale)).append(" ").append(messages.getMessage("message.cannot.empty", locale)).toString()); - result.addError(error); - return ControllerConstants.Tiles.User.password; - } - - if(!passwordEncoder.matches(password.getPassword(), dbUser.getAdminPassword())) { - ObjectError error = new ObjectError("password",messages.getMessage("message.password.invalid", locale)); - result.addError(error); - return ControllerConstants.Tiles.User.password; - } - - - if(StringUtils.isBlank(password.getNewPassword())) { - ObjectError error = new ObjectError("newPassword",new StringBuilder().append(messages.getMessage("label.generic.newpassword", locale)).append(" ").append(messages.getMessage("message.cannot.empty", locale)).toString()); - result.addError(error); - } - - if(StringUtils.isBlank(password.getRepeatPassword())) { - ObjectError error = new ObjectError("newPasswordAgain",new StringBuilder().append(messages.getMessage("label.generic.newpassword.repeat", locale)).append(" ").append(messages.getMessage("message.cannot.empty", locale)).toString()); - result.addError(error); - } - - if(!password.getRepeatPassword().equals(password.getNewPassword())) { - ObjectError error = new ObjectError("newPasswordAgain",messages.getMessage("message.password.different", locale)); - result.addError(error); - } - - if(password.getNewPassword().length()<6) { - ObjectError error = new ObjectError("newPassword",messages.getMessage("message.password.length", locale)); - result.addError(error); - } - - if (result.hasErrors()) { - return ControllerConstants.Tiles.User.password; - } - - - - String pass = passwordEncoder.encode(password.getNewPassword()); - dbUser.setAdminPassword(pass); - userService.update(dbUser); - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.User.password; - } - - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value="/admin/users/createUser.html", method=RequestMethod.GET) - public String displayUserCreate(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - return displayUser(null,model,request,response,locale); - } - - - /** - * From user list - * @param id - * @param model - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/displayStoreUser.html", method=RequestMethod.GET) - public String displayUserEdit(@ModelAttribute("id") Long id, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - User dbUser = userService.getById(id); - - if(dbUser==null) { - LOGGER.info("User is null for id " + id); - return "redirect://admin/users/list.html"; - } - - - return displayUser(dbUser,model,request,response,locale); - - } - - /** - * From user profile - * @param model - * @param request - * @param response - * @param locale - * @return - * @throws Exception - */ - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/displayUser.html", method=RequestMethod.GET) - public String displayUserEdit(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - String userName = request.getRemoteUser(); - User user = userService.getByUserName(userName); - return displayUser(user,model,request,response,locale); - - } - - private void populateUserObjects(User user, MerchantStore store, Model model, Locale locale) throws Exception { - - //get groups - List<Group> groups = new ArrayList<Group>(); - List<Group> userGroups = groupService.listGroup(GroupType.ADMIN); - for(Group group : userGroups) { - if(!group.getGroupName().equals(Constants.GROUP_SUPERADMIN)) { - groups.add(group); - } - } - - - List<MerchantStore> stores = new ArrayList<MerchantStore>(); - //stores.add(store); - stores = merchantStoreService.list(); - - - //questions - List<SecurityQuestion> questions = new ArrayList<SecurityQuestion>(); - - SecurityQuestion question = new SecurityQuestion(); - question.setId("1"); - question.setLabel(messages.getMessage("security.question.1", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("2"); - question.setLabel(messages.getMessage("security.question.2", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("3"); - question.setLabel(messages.getMessage("security.question.3", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("4"); - question.setLabel(messages.getMessage("security.question.4", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("5"); - question.setLabel(messages.getMessage("security.question.5", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("6"); - question.setLabel(messages.getMessage("security.question.6", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("7"); - question.setLabel(messages.getMessage("security.question.7", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("8"); - question.setLabel(messages.getMessage("security.question.8", locale)); - questions.add(question); - - question = new SecurityQuestion(); - question.setId("9"); - question.setLabel(messages.getMessage("security.question.9", locale)); - questions.add(question); - - model.addAttribute("questions", questions); - model.addAttribute("stores", stores); - model.addAttribute("languages", store.getLanguages()); - model.addAttribute("groups", groups); - - - } - - - - private String displayUser(User user, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { - - - //display menu - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - - - if(user==null) { - user = new User(); - } else { - user.setAdminPassword("TRANSIENT"); - } - - this.populateUserObjects(user, store, model, locale); - - - model.addAttribute("user", user); - - - - return ControllerConstants.Tiles.User.profile; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/checkUserCode.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> checkUserCode(HttpServletRequest request, HttpServletResponse response, Locale locale) { - String code = request.getParameter("code"); - String id = request.getParameter("id"); - - AjaxResponse resp = new AjaxResponse(); - - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - try { - - if(StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - User user = userService.getByUserName(code); - - - if(!StringUtils.isBlank(id)&& user!=null) { - try { - Long lid = Long.parseLong(id); - - if(user.getAdminName().equals(code) && user.getId()==lid) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - } catch (Exception e) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - } - - - if(StringUtils.isBlank(code)) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(user!=null) { - resp.setStatus(AjaxResponse.CODE_ALREADY_EXIST); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - } catch (Exception e) { - LOGGER.error("Error while getting user", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/save.html", method=RequestMethod.POST) - public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result, Model model, HttpServletRequest request, Locale locale) throws Exception { - - - setMenu(model,request); - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - - - this.populateUserObjects(user, store, model, locale); - - Language language = user.getDefaultLanguage(); - - Language l = languageService.getById(language.getId()); - - user.setDefaultLanguage(l); - - Locale userLocale = LocaleUtils.getLocale(l); - - - - User dbUser = null; - - //edit mode, need to get original user important information - if(user.getId()!=null) { - dbUser = userService.getByUserName(user.getAdminName()); - if(dbUser==null) { - return "redirect:///admin/users/displayUser.html"; - } - } - - List<Group> submitedGroups = user.getGroups(); - Set<Integer> ids = new HashSet<Integer>(); - for(Group group : submitedGroups) { - ids.add(group.getId()); - } - - - - //validate security questions not empty - if(StringUtils.isBlank(user.getAnswer1())) { - ObjectError error = new ObjectError("answer1",messages.getMessage("security.answer.question1.message", locale)); - result.addError(error); - } - - if(StringUtils.isBlank(user.getAnswer2())) { - ObjectError error = new ObjectError("answer2",messages.getMessage("security.answer.question2.message", locale)); - result.addError(error); - } - - if(StringUtils.isBlank(user.getAnswer3())) { - ObjectError error = new ObjectError("answer3",messages.getMessage("security.answer.question3.message", locale)); - result.addError(error); - } - - if(user.getQuestion1().equals(user.getQuestion2()) || user.getQuestion1().equals(user.getQuestion3()) - || user.getQuestion2().equals(user.getQuestion1()) || user.getQuestion1().equals(user.getQuestion3()) - || user.getQuestion3().equals(user.getQuestion1()) || user.getQuestion1().equals(user.getQuestion2())) - - - { - ObjectError error = new ObjectError("question1",messages.getMessage("security.questions.differentmessages", locale)); - result.addError(error); - } - - - Group superAdmin = null; - - if(user.getId()!=null && user.getId()>0) { - if(user.getId().longValue()!=dbUser.getId().longValue()) { - return "redirect:///admin/users/displayUser.html"; - } - - List<Group> groups = dbUser.getGroups(); - //boolean removeSuperAdmin = true; - for(Group group : groups) { - //can't revoke super admin - if(group.getGroupName().equals("SUPERADMIN")) { - superAdmin = group; - } - } - - } else { - - if(user.getAdminPassword().length()<6) { - ObjectError error = new ObjectError("adminPassword",messages.getMessage("message.password.length", locale)); - result.addError(error); - } - - } - - if(superAdmin!=null) { - ids.add(superAdmin.getId()); - } - - - List<Group> newGroups = groupService.listGroupByIds(ids); - - //set actual user groups - user.setGroups(newGroups); - - if (result.hasErrors()) { - return ControllerConstants.Tiles.User.profile; - } - - String decodedPassword = user.getAdminPassword(); - if(user.getId()!=null && user.getId()>0) { - user.setAdminPassword(dbUser.getAdminPassword()); - } else { - String encoded = passwordEncoder.encode(user.getAdminPassword()); - user.setAdminPassword(encoded); - } - - - if(user.getId()==null || user.getId().longValue()==0) { - - //save or update user - userService.saveOrUpdate(user); - - try { - - //creation of a user, send an email - String userName = user.getFirstName(); - if(StringUtils.isBlank(userName)) { - userName = user.getAdminName(); - } - String[] userNameArg = {userName}; - - - Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, userLocale); - templateTokens.put(EmailConstants.EMAIL_NEW_USER_TEXT, messages.getMessage("email.greeting", userNameArg, userLocale)); - templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, user.getFirstName()); - templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, user.getLastName()); - templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",userLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_NAME, user.getAdminName()); - templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_CREATED, messages.getMessage("email.newuser.text",userLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",userLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD, decodedPassword); - templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",userLocale)); - templateTokens.put(EmailConstants.EMAIL_ADMIN_URL, filePathUtils.buildAdminUri(store, request)); - - - Email email = new Email(); - email.setFrom(store.getStorename()); - email.setFromEmail(store.getStoreEmailAddress()); - email.setSubject(messages.getMessage("email.newuser.title",userLocale)); - email.setTo(user.getAdminEmail()); - email.setTemplateName(NEW_USER_TMPL); - email.setTemplateTokens(templateTokens); - - - - emailService.sendHtmlEmail(store, email); - - } catch (Exception e) { - LOGGER.error("Cannot send email to user",e); - } - - } else { - //save or update user - userService.saveOrUpdate(user); - } - - model.addAttribute("success","success"); - return ControllerConstants.Tiles.User.profile; - } - - @PreAuthorize("hasRole('AUTH')") - @RequestMapping(value="/admin/users/remove.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> removeUser(HttpServletRequest request, Locale locale) throws Exception { - - //do not remove super admin - - String sUserId = request.getParameter("userId"); - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - String userName = request.getRemoteUser(); - User remoteUser = userService.getByUserName(userName); - - - try { - - Long userId = Long.parseLong(sUserId); - User user = userService.getById(userId); - - /** - * In order to remove a User the logged in ser must be ADMIN - * or SUPER_USER - */ - - - if(user==null){ - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - if(!request.isUserInRole(Constants.GROUP_ADMIN)) { - resp.setStatusMessage(messages.getMessage("message.unauthorized", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - //check if the user removed has group ADMIN - boolean isAdmin = false; - if(UserUtils.userInGroup(remoteUser, Constants.GROUP_ADMIN) || UserUtils.userInGroup(remoteUser, Constants.GROUP_SUPERADMIN)) { - isAdmin = true; - } - - - if(!isAdmin) { - resp.setStatusMessage(messages.getMessage("message.security.caanotremovesuperadmin", locale)); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - userService.delete(user); - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - - - } catch (Exception e) { - LOGGER.error("Error while deleting user", e); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setErrorMessage(e); - } - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - - } - - - private void setMenu(Model model, HttpServletRequest request) throws Exception { - - //display menu - Map<String,String> activeMenus = new HashMap<String,String>(); - activeMenus.put("profile", "profile"); - activeMenus.put("user", "create-user"); - - @SuppressWarnings("unchecked") - Map<String, Menu> menus = (Map<String, Menu>)request.getAttribute("MENUMAP"); - - Menu currentMenu = (Menu)menus.get("profile"); - model.addAttribute("currentMenu",currentMenu); - model.addAttribute("activeMenus",activeMenus); - // - - } - - //password reset functionality --- Sajid Shajahan - @RequestMapping(value="/admin/users/resetPassword.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> resetPassword(HttpServletRequest request, HttpServletResponse response, Locale locale) { - - AjaxResponse resp = new AjaxResponse(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - - String userName = request.getParameter("username"); - - - - /** - * Get User with userService.getByUserName - * Get 3 security questions from User.getQuestion1, user.getQuestion2, user.getQuestion3 - */ - - HttpSession session = request.getSession(); - session.setAttribute("username_reset", userName); - - try { - if(!StringUtils.isBlank(userName)){ - - User dbUser = userService.getByUserName(userName); - - if(dbUser==null) { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("message.username.notfound", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - Map<String,String> entry = new HashMap<String,String>(); - entry.put(QUESTION_1, dbUser.getQuestion1()); - entry.put(QUESTION_2, dbUser.getQuestion2()); - entry.put(QUESTION_3, dbUser.getQuestion3()); - resp.addDataEntry(entry); - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - - }else - { - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale)); - - } - } catch (Exception e) { - e.printStackTrace(); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale)); - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - - - - String returnString = resp.toJSONString(); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - //password reset functionality --- Sajid Shajahan - @RequestMapping(value="/admin/users/resetPasswordSecurityQtn.html", method=RequestMethod.POST) - public @ResponseBody ResponseEntity<String> resetPasswordSecurityQtn(@ModelAttribute(value="userReset") UserReset userReset,HttpServletRequest request, HttpServletResponse response, Locale locale) { - - MerchantStore store = (MerchantStore)request.getAttribute(Constants.ADMIN_STORE); - Language userLanguage = null; - Locale userLocale = null; - AjaxResponse resp = new AjaxResponse(); - - - String answer1 = request.getParameter("answer1"); - String answer2 = request.getParameter("answer2"); - String answer3 = request.getParameter("answer3"); - - try { - - HttpSession session = request.getSession(); - User dbUser = userService.getByUserName((String) session.getAttribute("username_reset")); - - if(dbUser!= null){ - - if(dbUser.getAnswer1().equals(answer1.trim()) && dbUser.getAnswer2().equals(answer2.trim()) && dbUser.getAnswer3().equals(answer3.trim())){ - userLanguage = dbUser.getDefaultLanguage(); - userLocale = LocaleUtils.getLocale(userLanguage); - - String tempPass = userReset.generateRandomString(); - String pass = passwordEncoder.encode(tempPass); - - dbUser.setAdminPassword(pass); - userService.update(dbUser); - - //send email - - try { - String[] storeEmail = {store.getStoreEmailAddress()}; - - Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, userLocale); - templateTokens.put(EmailConstants.EMAIL_RESET_PASSWORD_TXT, messages.getMessage("email.user.resetpassword.text", userLocale)); - templateTokens.put(EmailConstants.EMAIL_CONTACT_OWNER, messages.getMessage("email.contactowner", storeEmail, userLocale)); - templateTokens.put(EmailConstants.EMAIL_PASSWORD_LABEL, messages.getMessage("label.generic.password",userLocale)); - templateTokens.put(EmailConstants.EMAIL_USER_PASSWORD, tempPass); - - Email email = new Email(); - email.setFrom(store.getStorename()); - email.setFromEmail(store.getStoreEmailAddress()); - email.setSubject(messages.getMessage("label.generic.changepassword",userLocale)); - email.setTo(dbUser.getAdminEmail() ); - email.setTemplateName(RESET_PASSWORD_TPL); - email.setTemplateTokens(templateTokens); - - emailService.sendHtmlEmail(store, email); - - } catch (Exception e) { - LOGGER.error("Cannot send email to user",e); - } - - resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED); - resp.setStatusMessage(messages.getMessage("User.resetPassword.resetSuccess", locale)); - } - else{ - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("User.resetPassword.wrongSecurityQtn", locale)); - - } - }else{ - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("User.resetPassword.userNotFound", locale)); - - } - - } catch (ServiceException e) { - e.printStackTrace(); - resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE); - resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale)); - } - - String returnString = resp.toJSONString(); - final HttpHeaders httpHeaders= new HttpHeaders(); - httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new ResponseEntity<String>(returnString,httpHeaders,HttpStatus.OK); - } - - }
sm-shop/src/main/java/com/salesmanager/shop/admin/model/catalog/Category.java+0 −42 removed@@ -1,42 +0,0 @@ -package com.salesmanager.shop.admin.model.catalog; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import javax.validation.Valid; -import com.salesmanager.core.model.catalog.category.CategoryDescription; - -/** - * Wrapper to ease admin jstl - * @author carlsamson - * - */ -public class Category implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - private com.salesmanager.core.model.catalog.category.Category category; - - @Valid - private List<CategoryDescription> descriptions = new ArrayList<CategoryDescription>(); - - public com.salesmanager.core.model.catalog.category.Category getCategory() { - return category; - } - - public void setCategory(com.salesmanager.core.model.catalog.category.Category category) { - this.category = category; - } - - public List<CategoryDescription> getDescriptions() { - return descriptions; - } - - public void setDescriptions(List<CategoryDescription> descriptions) { - this.descriptions = descriptions; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/catalog/Keyword.java+0 −41 removed@@ -1,41 +0,0 @@ -package com.salesmanager.shop.admin.model.catalog; - -import javax.validation.constraints.NotEmpty; - -import java.io.Serializable; - -/** - * Post keyword from the admin - * @author Carl Samson - * - */ -public class Keyword implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private long productId; - private String languageCode; - @NotEmpty - private String keyword; - public void setProductId(long productId) { - this.productId = productId; - } - public long getProductId() { - return productId; - } - public void setLanguageCode(String languageCode) { - this.languageCode = languageCode; - } - public String getLanguageCode() { - return languageCode; - } - public void setKeyword(String keyword) { - this.keyword = keyword; - } - public String getKeyword() { - return keyword; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/catalog/Manufacturer.java+0 −91 removed@@ -1,91 +0,0 @@ -package com.salesmanager.shop.admin.model.catalog; - -import com.salesmanager.core.model.catalog.product.image.ProductImage; -import com.salesmanager.core.model.catalog.product.manufacturer.ManufacturerDescription; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - - -public class Manufacturer implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -4531526676134574984L; - - /** - * - */ - - //provides wrapping to the main Manufacturer entity - private com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer manufacturer; - - @Valid - private List<ManufacturerDescription> descriptions = new ArrayList<ManufacturerDescription>(); - - private Integer order = new Integer(0); - private MultipartFile image = null; - @NotNull - private String code; - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - private ProductImage productImage = null; - - - - public MultipartFile getImage() { - return image; - } - - public void setImage(MultipartFile image) { - this.image = image; - } - - public ProductImage getProductImage() { - return productImage; - } - - public void setProductImage(ProductImage productImage) { - this.productImage = productImage; - } - - public com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer getManufacturer() { - return manufacturer; - } - - public void setManufacturer( - com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer manufacturer) { - this.manufacturer = manufacturer; - } - - public List<ManufacturerDescription> getDescriptions() { - return descriptions; - } - - public void setDescriptions(List<ManufacturerDescription> descriptions) { - this.descriptions = descriptions; - } - - public Integer getOrder() { - return order; - } - - public void setOrder(Integer order) { - this.order = order; - } - - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/catalog/Product.java+0 −112 removed@@ -1,112 +0,0 @@ -package com.salesmanager.shop.admin.model.catalog; - -import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; -import com.salesmanager.core.model.catalog.product.description.ProductDescription; -import com.salesmanager.core.model.catalog.product.image.ProductImage; -import com.salesmanager.core.model.catalog.product.price.ProductPrice; -import javax.validation.constraints.NotEmpty; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.Valid; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -public class Product implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * - */ - - //provides wrapping to the main product entity - @Valid - private com.salesmanager.core.model.catalog.product.Product product; - - @Valid - private List<ProductDescription> descriptions = new ArrayList<ProductDescription>(); - - @Valid - private ProductAvailability availability = null; - - @Valid - private ProductPrice price = null; - - private MultipartFile image = null; - - private ProductImage productImage = null; - - @NotEmpty - private String productPrice = "0"; - - private String dateAvailable; - - private ProductDescription description = null; - - public String getDateAvailable() { - return dateAvailable; - } - public void setDateAvailable(String dateAvailable) { - this.dateAvailable = dateAvailable; - } - public com.salesmanager.core.model.catalog.product.Product getProduct() { - return product; - } - public void setProduct(com.salesmanager.core.model.catalog.product.Product product) { - this.product = product; - } - - public List<ProductDescription> getDescriptions() { - return descriptions; - } - public void setDescriptions(List<ProductDescription> descriptions) { - this.descriptions = descriptions; - } - public void setAvailability(ProductAvailability availability) { - this.availability = availability; - } - public ProductAvailability getAvailability() { - return availability; - } - public void setPrice(ProductPrice price) { - this.price = price; - } - public ProductPrice getPrice() { - return price; - } - public MultipartFile getImage() { - return image; - } - public void setImage(MultipartFile image) { - this.image = image; - } - - public void setProductPrice(String productPrice) { - this.productPrice = productPrice; - } - public String getProductPrice() { - return productPrice; - } - public void setProductImage(ProductImage productImage) { - this.productImage = productImage; - } - public ProductImage getProductImage() { - return productImage; - } - public void setDescription(ProductDescription description) { - this.description = description; - } - public ProductDescription getDescription() { - return description; - } - - - - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/catalog/ProductPrice.java+0 −82 removed@@ -1,82 +0,0 @@ -package com.salesmanager.shop.admin.model.catalog; - -import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; -import com.salesmanager.core.model.catalog.product.price.ProductPriceDescription; - -import javax.validation.Valid; -import java.util.ArrayList; -import java.util.List; - -public class ProductPrice { - - @Valid - private com.salesmanager.core.model.catalog.product.price.ProductPrice price = null; - @Valid - private List <ProductPriceDescription> descriptions = new ArrayList<ProductPriceDescription>(); - private String priceText; - private String specialPriceText; - private ProductAvailability productAvailability; - - - //cannot convert in this object to date ??? needs to use a string, parse, bla bla - private String productPriceSpecialStartDate; - private String productPriceSpecialEndDate; - - private com.salesmanager.core.model.catalog.product.Product product; - - - - - - public List <ProductPriceDescription> getDescriptions() { - return descriptions; - } - public void setDescriptions(List <ProductPriceDescription> descriptions) { - this.descriptions = descriptions; - } - public ProductAvailability getProductAvailability() { - return productAvailability; - } - public void setProductAvailability(ProductAvailability productAvailability) { - this.productAvailability = productAvailability; - } - public String getPriceText() { - return priceText; - } - public void setPriceText(String priceText) { - this.priceText = priceText; - } - public com.salesmanager.core.model.catalog.product.price.ProductPrice getPrice() { - return price; - } - public void setPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice price) { - this.price = price; - } - public String getSpecialPriceText() { - return specialPriceText; - } - public void setSpecialPriceText(String specialPriceText) { - this.specialPriceText = specialPriceText; - } - - public com.salesmanager.core.model.catalog.product.Product getProduct() { - return product; - } - public void setProduct(com.salesmanager.core.model.catalog.product.Product product) { - this.product = product; - } - public String getProductPriceSpecialStartDate() { - return productPriceSpecialStartDate; - } - public void setProductPriceSpecialStartDate( - String productPriceSpecialStartDate) { - this.productPriceSpecialStartDate = productPriceSpecialStartDate; - } - public String getProductPriceSpecialEndDate() { - return productPriceSpecialEndDate; - } - public void setProductPriceSpecialEndDate(String productPriceSpecialEndDate) { - this.productPriceSpecialEndDate = productPriceSpecialEndDate; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/content/ContentFiles.java+0 −57 removed@@ -1,57 +0,0 @@ -/** - * - */ -package com.salesmanager.shop.admin.model.content; - -import javax.validation.constraints.NotEmpty; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.Valid; -import java.io.Serializable; -import java.util.List; - -/** - * A bean class responsible for getting form data from shop Admin for uploading - * content files for a given merchant and validating the provided data. - * - * This will work as a wrapper for underlying cache where these content images will be stored - * and retrieved in future. - * - * @author Umesh Awasthi - * @since 1.2 - * - */ -public class ContentFiles implements Serializable -{ - - private static final long serialVersionUID = 1L; - - - private List<MultipartFile> file; - - public void setFile(List<MultipartFile> file) { - this.file = file; - } - - private String fileName; - - //@NotEmpty(message="{merchant.files.invalid}") - //@Valid - public List<MultipartFile> getFile() - { - return file; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getFileName() { - return fileName; - } - - - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/content/ProductImages.java+0 −19 removed@@ -1,19 +0,0 @@ -package com.salesmanager.shop.admin.model.content; - -public class ProductImages extends ContentFiles { - - /** - * - */ - private static final long serialVersionUID = 7732719188032287938L; - private long productId; - - public long getProductId() { - return productId; - } - - public void setProductId(long productId) { - this.productId = productId; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/customer/attribute/CustomerAttributes.java+0 −18 removed@@ -1,18 +0,0 @@ -package com.salesmanager.shop.admin.model.customer.attribute; - -import java.util.List; - - -public class CustomerAttributes { - - private List<CustomerOption> customerOptions; - - public List<CustomerOption> getCustomerOptions() { - return customerOptions; - } - - public void setCustomerOptions(List<CustomerOption> customerOptions) { - this.customerOptions = customerOptions; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/customer/attribute/CustomerOption.java+0 −67 removed@@ -1,67 +0,0 @@ -package com.salesmanager.shop.admin.model.customer.attribute; - -import java.io.Serializable; -import java.util.List; - -import com.salesmanager.shop.model.entity.ShopEntity; - - - -public class CustomerOption extends ShopEntity implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String type; - private String name; - - - private CustomerOptionValue defaultValue; - - - private List<CustomerOptionValue> availableValues; - - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public CustomerOptionValue getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(CustomerOptionValue defaultValue) { - this.defaultValue = defaultValue; - } - - public List<CustomerOptionValue> getAvailableValues() { - return availableValues; - } - - public void setAvailableValues(List<CustomerOptionValue> availableValues) { - this.availableValues = availableValues; - } - - - - - - - - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/customer/attribute/CustomerOptionValue.java+0 −24 removed@@ -1,24 +0,0 @@ -package com.salesmanager.shop.admin.model.customer.attribute; - -import java.io.Serializable; - -import com.salesmanager.shop.model.entity.ShopEntity; - - - -public class CustomerOptionValue extends ShopEntity implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String name; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/digital/ProductFiles.java+0 −69 removed@@ -1,69 +0,0 @@ -/** - * - */ -package com.salesmanager.shop.admin.model.digital; - -import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.file.DigitalProduct; -import javax.validation.constraints.NotEmpty; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.Valid; -import java.io.Serializable; -import java.util.List; - -/** - * A bean class responsible for getting form data from shop Admin for uploading - * product files for a given product and validating the provided data. - * - * This will work as a wrapper for underlying cache where these content images will be stored - * and retrieved in future. - * - * @author Carl Samson - * @since 1.2 - * - */ -public class ProductFiles implements Serializable -{ - - private static final long serialVersionUID = 1L; - - - private List<MultipartFile> file; - private DigitalProduct digitalProduct; - private Product product; - - @NotEmpty(message="{product.files.invalid}") - @Valid - public List<MultipartFile> getFile() - { - return file; - } - - public void setFile( final List<MultipartFile> file ) - { - this.file = file; - } - - - - public Product getProduct() { - return product; - } - - public void setProduct(Product product) { - this.product = product; - } - - public void setDigitalProduct(DigitalProduct digitalProduct) { - this.digitalProduct = digitalProduct; - } - - public DigitalProduct getDigitalProduct() { - return digitalProduct; - } - - - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/merchant/StoreLandingDescription.java+0 −68 removed@@ -1,68 +0,0 @@ -package com.salesmanager.shop.admin.model.merchant; - -import com.salesmanager.core.model.reference.language.Language; - -import java.io.Serializable; - -import javax.validation.constraints.NotEmpty; - -public class StoreLandingDescription implements Serializable { - - - /** - * - */ - private static final long serialVersionUID = 1L; - @NotEmpty - private String title; - private String description; - private String keywords; - private String homePageContent; - - - private Language language; - - - - - public void setDescription(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setHomePageContent(String homePageContent) { - this.homePageContent = homePageContent; - } - - public String getHomePageContent() { - return homePageContent; - } - - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - public String getKeywords() { - return keywords; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getTitle() { - return title; - } - - public void setLanguage(Language language) { - this.language = language; - } - - public Language getLanguage() { - return language; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/merchant/StoreLanding.java+0 −20 removed@@ -1,20 +0,0 @@ -package com.salesmanager.shop.admin.model.merchant; - -import javax.validation.Valid; -import java.util.ArrayList; -import java.util.List; - -public class StoreLanding { - - @Valid - private List<StoreLandingDescription> descriptions = new ArrayList<StoreLandingDescription>(); - - public void setDescriptions(List<StoreLandingDescription> descriptions) { - this.descriptions = descriptions; - } - - public List<StoreLandingDescription> getDescriptions() { - return descriptions; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/orders/Order.java+0 −96 removed@@ -1,96 +0,0 @@ -package com.salesmanager.shop.admin.model.orders; - -import com.salesmanager.core.model.common.Billing; -import com.salesmanager.core.model.common.Delivery; -import com.salesmanager.core.model.order.orderstatus.OrderStatus; - -import javax.persistence.Embedded; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - - -public class Order implements Serializable { - - - /** - * - */ - private static final long serialVersionUID = 1L; - private Long Id; - private String orderHistoryComment = ""; - - List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.values()); - private String datePurchased = ""; - private com.salesmanager.core.model.order.Order order; - - @Embedded - private com.salesmanager.core.model.common.Delivery delivery = null; - - @Embedded - private com.salesmanager.core.model.common.Billing billing = null; - - - - - public String getDatePurchased() { - return datePurchased; - } - - public void setDatePurchased(String datePurchased) { - this.datePurchased = datePurchased; - } - - public Long getId() { - return Id; - } - - public void setId(Long id) { - Id = id; - } - - public String getOrderHistoryComment() { - return orderHistoryComment; - } - - public void setOrderHistoryComment(String orderHistoryComment) { - this.orderHistoryComment = orderHistoryComment; - } - - public List<OrderStatus> getOrderStatusList() { - return orderStatusList; - } - - public void setOrderStatusList(List<OrderStatus> orderStatusList) { - this.orderStatusList = orderStatusList; - } - - public com.salesmanager.core.model.order.Order getOrder() { - return order; - } - - public void setOrder(com.salesmanager.core.model.order.Order order) { - this.order = order; - } - - public Delivery getDelivery() { - return delivery; - } - - public void setDelivery(Delivery delivery) { - this.delivery = delivery; - } - - public Billing getBilling() { - return billing; - } - - public void setBilling(Billing billing) { - this.billing = billing; - } - - - - - -} \ No newline at end of file
sm-shop/src/main/java/com/salesmanager/shop/admin/model/orders/Refund.java+0 −26 removed@@ -1,26 +0,0 @@ -package com.salesmanager.shop.admin.model.orders; - -import java.io.Serializable; - -public class Refund implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 2392736671094915447L; - private Long orderId; - private String amount; - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - public String getAmount() { - return amount; - } - public void setAmount(String amount) { - this.amount = amount; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/permission/GroupDetails.java+0 −32 removed@@ -1,32 +0,0 @@ -package com.salesmanager.shop.admin.model.permission; - -import java.io.Serializable; -import java.util.List; - -import javax.validation.Valid; - -import com.salesmanager.core.model.user.Group; - -public class GroupDetails implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - @Valid - private Group group; - private List<String> types; - public Group getGroup() { - return group; - } - public void setGroup(Group group) { - this.group = group; - } - public List<String> getTypes() { - return types; - } - public void setTypes(List<String> types) { - this.types = types; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/permission/Permissions.java+0 −49 removed@@ -1,49 +0,0 @@ - -package com.salesmanager.shop.admin.model.permission; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "permission" -}) -public class Permissions implements Serializable -{ - - @JsonProperty("permission") - private List<ShopPermission> shopPermission = null; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = 1L; - - @JsonProperty("permission") - public List<ShopPermission> getShopPermission() { - return shopPermission; - } - - @JsonProperty("permission") - public void setShopPermission(List<ShopPermission> shopPermission) { - this.shopPermission = shopPermission; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/permission/ShopGroup.java+0 −49 removed@@ -1,49 +0,0 @@ - -package com.salesmanager.shop.admin.model.permission; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "name" -}) -public class ShopGroup implements Serializable -{ - - @JsonProperty("name") - private List<String> name = null; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = 8390421982207090115L; - - @JsonProperty("name") - public List<String> getName() { - return name; - } - - @JsonProperty("name") - public void setName(List<String> name) { - this.name = name; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/permission/ShopPermission.java+0 −61 removed@@ -1,61 +0,0 @@ - -package com.salesmanager.shop.admin.model.permission; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "type", - "group" -}) -public class ShopPermission implements Serializable -{ - - @JsonProperty("type") - private String type; - @JsonProperty("group") - private ShopGroup shopGroup; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = -7938476709520334066L; - - @JsonProperty("type") - public String getType() { - return type; - } - - @JsonProperty("type") - public void setType(String type) { - this.type = type; - } - - @JsonProperty("group") - public ShopGroup getShopGroup() { - return shopGroup; - } - - @JsonProperty("group") - public void setShopGroup(ShopGroup shopGroup) { - this.shopGroup = shopGroup; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/reference/Size.java+0 −32 removed@@ -1,32 +0,0 @@ -package com.salesmanager.shop.admin.model.reference; - -import java.io.Serializable; - -public class Size implements Serializable { - - - /** - * - */ - private static final long serialVersionUID = -4737272153685816396L; - private String code; - private String name; - public String getCode() { - return code; - } - public void setCode(String code) { - this.code = code; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public Size(String code, String name) { - this.code = code; - this.name = name; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/reference/Weight.java+0 −31 removed@@ -1,31 +0,0 @@ -package com.salesmanager.shop.admin.model.reference; - -import java.io.Serializable; - -public class Weight implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -1006772612089740285L; - private String code; - private String name; - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getCode() { - return code; - } - public void setCode(String code) { - this.code = code; - } - - public Weight(String code, String name) { - this.code = code; - this.name = name; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/secutity/Password.java+0 −59 removed@@ -1,59 +0,0 @@ -package com.salesmanager.shop.admin.model.secutity; - -import com.salesmanager.core.model.user.User; - -import java.io.Serializable; - -/** - * Entity used in the cahange passord page - * @author csamson777 - * - */ -public class Password implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String password; - private String newPassword; - private String repeatPassword; - - private User user; - - - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getNewPassword() { - return newPassword; - } - - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } - - public String getRepeatPassword() { - return repeatPassword; - } - - public void setRepeatPassword(String repeatPassword) { - this.repeatPassword = repeatPassword; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/userpassword/UserReset.java+0 −51 removed@@ -1,51 +0,0 @@ -package com.salesmanager.shop.admin.model.userpassword; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class UserReset -{ - final static String CHAR_LIST_WITHNUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - final static String CHAR_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"; - - final static int RANDOM_STRING_LENGTH = 10; - - private static final Logger LOGGER = LoggerFactory.getLogger(UserReset.class); - - public static String generateRandomString() - { - StringBuilder randStr = new StringBuilder(); - for (int i = 0; i < RANDOM_STRING_LENGTH; i++) { - int number = getRandomNumber(); - char ch = CHAR_LIST_WITHNUM.charAt(number); - randStr.append(ch); - } - return randStr.toString(); - } - - public static String generateRandomString(int length) - { - StringBuilder randStr = new StringBuilder(); - for (int i = 0; i < length; i++) { - int number = getRandomNumber(); - char ch = CHAR_LIST.charAt(number); - randStr.append(ch); - } - return randStr.toString(); - } - - private static int getRandomNumber() - { - int randomInt = 0; - - UniformRandomProvider randomGenerator = RandomSource.create(RandomSource.MT); - randomInt = randomGenerator.nextInt(CHAR_LIST.length()); - - return randomInt; - } - - -} \ No newline at end of file
sm-shop/src/main/java/com/salesmanager/shop/admin/model/web/ConfigListWrapper.java+0 −23 removed@@ -1,23 +0,0 @@ -package com.salesmanager.shop.admin.model.web; - -import java.util.List; - -import com.salesmanager.core.model.system.MerchantConfiguration; - - - -public class ConfigListWrapper -{ - private List<MerchantConfiguration> merchantConfigs; - - public List<MerchantConfiguration> getMerchantConfigs() - { - return merchantConfigs; - } - - public void setMerchantConfigs(List<MerchantConfiguration> merchantConfigs) - { - this.merchantConfigs = merchantConfigs; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/admin/model/web/Menu.java+0 −68 removed@@ -1,68 +0,0 @@ -package com.salesmanager.shop.admin.model.web; - - - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Menu implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String code; - private String url; - private String icon; - private String role; - private int order; - private List<Menu> menus = new ArrayList<Menu>(); - public String getCode() { - return code; - } - @JsonProperty("code") - public void setCode(String code) { - this.code = code; - } - public String getUrl() { - return url; - } - @JsonProperty("url") - public void setUrl(String url) { - this.url = url; - } - - - - public int getOrder() { - return order; - } - @JsonProperty("order") - public void setOrder(int order) { - this.order = order; - } - public List<Menu> getMenus() { - return menus; - } - @JsonProperty("menus") - public void setMenus(List<Menu> menus) { - this.menus = menus; - } - public void setIcon(String icon) { - this.icon = icon; - } - public String getIcon() { - return icon; - } - public String getRole() { - return role; - } - @JsonProperty("role") - public void setRole(String role) { - this.role = role; - } - -}
sm-shop/src/main/java/com/salesmanager/shop/application/config/ShopApplicationConfiguration.java+0 −7 modified@@ -32,7 +32,6 @@ import org.springframework.web.servlet.i18n.SessionLocaleResolver; import com.salesmanager.core.business.configuration.CoreApplicationConfiguration; -import com.salesmanager.shop.filter.AdminFilter; import com.salesmanager.shop.filter.CorsFilter; import com.salesmanager.shop.filter.StoreFilter; import com.salesmanager.shop.filter.XssFilter; @@ -95,8 +94,6 @@ public void addInterceptors(InterceptorRegistry registry) { // REST api .addPathPatterns("/api/**"); - // admin panel filter - registry.addInterceptor(adminFilter()).addPathPatterns("/admin/**"); } @Bean @@ -124,10 +121,6 @@ public CorsFilter corsFilter() { return new CorsFilter(); } - @Bean - public AdminFilter adminFilter() { - return new AdminFilter(); - } @Bean public SessionLocaleResolver localeResolver() {
sm-shop/src/main/java/com/salesmanager/shop/filter/AdminFilter.java+0 −205 removed@@ -1,205 +0,0 @@ -package com.salesmanager.shop.filter; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.user.UserService; -import com.salesmanager.core.business.utils.CacheUtils; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.core.model.user.User; -import com.salesmanager.shop.admin.model.web.Menu; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.utils.LanguageUtils; - - -public class AdminFilter extends HandlerInterceptorAdapter { - - - private static final Logger LOGGER = LoggerFactory.getLogger(AdminFilter.class); - - @Inject - private MerchantStoreService merchantService; - - @Inject - private UserService userService; - - @Inject - private CacheUtils cache; - - @Inject - private LanguageUtils languageUtils; - - public boolean preHandle( - HttpServletRequest request, - HttpServletResponse response, - Object handler) throws Exception { - - request.setCharacterEncoding("UTF-8"); - @SuppressWarnings("unchecked") - Map<String,Menu> menus = (Map<String,Menu>) cache.getFromCache("MENUMAP"); - - User user = (User)request.getSession().getAttribute(Constants.ADMIN_USER); - - - String storeCode = MerchantStore.DEFAULT_STORE; - MerchantStore store = (MerchantStore)request.getSession().getAttribute(Constants.ADMIN_STORE); - - - String userName = request.getRemoteUser(); - - if(userName==null) {//** IMPORTANT FOR SPRING SECURITY **// - //response.sendRedirect(new StringBuilder().append(request.getContextPath()).append("/").append("/admin").toString()); - } else { - - if(user==null) { - user = userService.getByUserName(userName); - request.getSession().setAttribute(Constants.ADMIN_USER, user); - if(user!=null) { - storeCode = user.getMerchantStore().getCode(); - } else { - LOGGER.warn("User name not found " + userName); - } - store=null; - } - - if(user==null) { - response.sendRedirect(request.getContextPath() + "/admin/unauthorized.html"); - return true; - } - - if(!user.getAdminName().equals(userName)) { - user = userService.getByUserName(userName); - if(user!=null) { - storeCode = user.getMerchantStore().getCode(); - } else { - LOGGER.warn("User name not found " + userName); - } - store=null; - } - - } - - if(store==null) { - store = merchantService.getByCode(storeCode); - request.getSession().setAttribute(Constants.ADMIN_STORE, store); - } - request.setAttribute(Constants.ADMIN_STORE, store); - - - Language language = languageUtils.getRequestLanguage(request, response); - - if(language==null) { - - //TODO get the Locale from Spring API, is it simply request.getLocale() ??? - //if so then based on the Locale language locale.getLanguage() get the appropriate Language - //object as represented below - if(user!=null) { - language = user.getDefaultLanguage(); - if(language==null) { - language = store.getDefaultLanguage(); - } - } else { - language = store.getDefaultLanguage(); - } - - request.getSession().setAttribute("LANGUAGE", language); - - } - - - request.setAttribute(Constants.LANGUAGE, language); - - - if(menus==null) { - InputStream in = null; - ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally - try { - in = - (InputStream) this.getClass().getClassLoader().getResourceAsStream("admin/menu.json"); - - Map<String,Object> data = mapper.readValue(in, Map.class); - - Menu currentMenu = null; - - menus = new LinkedHashMap<String,Menu>(); - List objects = (List)data.get("menus"); - for(Object object : objects) { - Menu m = getMenu(object); - menus.put(m.getCode(),m); - } - - cache.putInCache(menus,"MENUMAP"); - - } catch (JsonParseException e) { - LOGGER.error("Error while creating menu", e); - } catch (JsonMappingException e) { - LOGGER.error("Error while creating menu", e); - } catch (IOException e) { - LOGGER.error("Error while creating menu", e); - } finally { - if(in !=null) { - try { - in.close(); - } catch (Exception ignore) { - // TODO: handle exception - } - } - } - - } - - - List<Menu> list = new ArrayList<Menu>(menus.values()); - - request.setAttribute("MENULIST", list); - - request.setAttribute("MENUMAP", menus); - response.setCharacterEncoding("UTF-8"); - - return true; - } - - - private Menu getMenu(Object object) { - - Map o = (Map)object; - Map menu = (Map)o.get("menu"); - - Menu m = new Menu(); - m.setCode((String)menu.get("code")); - - - m.setUrl((String)menu.get("url")); - m.setIcon((String)menu.get("icon")); - m.setRole((String)menu.get("role")); - - List menus = (List)menu.get("menus"); - if(menus!=null) { - for(Object oo : menus) { - - Menu mm = getMenu(oo); - m.getMenus().add(mm); - } - - } - - return m; - - } - -}
sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/PersistableProductAttributeMapper.java+38 −3 modified@@ -1,11 +1,17 @@ package com.salesmanager.shop.mapper.catalog; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + import javax.inject.Inject; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.springframework.stereotype.Component; +import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionService; import com.salesmanager.core.business.services.catalog.product.attribute.ProductOptionValueService; @@ -17,6 +23,8 @@ import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.mapper.Mapper; import com.salesmanager.shop.model.catalog.product.attribute.PersistableProductAttribute; +import com.salesmanager.shop.model.catalog.product.attribute.PersistableProductOptionValue; +import com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription; import com.salesmanager.shop.store.api.exception.ConversionRuntimeException; @Component @@ -28,6 +36,8 @@ public class PersistableProductAttributeMapper implements Mapper<PersistableProd private ProductOptionValueService productOptionValueService; @Inject private ProductService productService; + @Inject + private PersistableProductOptionValueMapper persistableProductOptionValueMapper; @Override public ProductAttribute convert(PersistableProductAttribute source, MerchantStore store, Language language) { @@ -57,19 +67,43 @@ public ProductAttribute merge(PersistableProductAttribute source, ProductAttribu if(!StringUtils.isBlank(source.getOptionValue().getCode())) { productOptionValue = productOptionValueService.getByCode(store, source.getOptionValue().getCode()); - } else { + } else if(source.getProductId() != null && source.getOptionValue().getId().longValue()>0) { productOptionValue = productOptionValueService.getById(source.getOptionValue().getId()); + } else { + //ProductOption value is text + productOptionValue = new ProductOptionValue(); + productOptionValue.setProductOptionDisplayOnly(true); + productOptionValue.setCode(UUID.randomUUID().toString()); + productOptionValue.setMerchantStore(store); + } + + if(!CollectionUtils.isEmpty((source.getOptionValue().getDescriptions()))) { + productOptionValue = persistableProductOptionValueMapper.merge(source.getOptionValue(),productOptionValue, store, language); + try { + productOptionValueService.saveOrUpdate(productOptionValue); + } catch (ServiceException e) { + throw new ConversionRuntimeException("Error converting ProductOptionValue",e); + } } - if(productOptionValue==null) { + if(productOptionValue==null && ! source.isAttributeDisplayOnly()) { throw new ConversionRuntimeException("Product option value id " + source.getOptionValue().getId() + " does not exist"); } + + + /** + productOptionValue + .getDescriptions().stream() + .map(val -> this.persistableProductOptionValueMapper.convert(val, store, language)).collect(Collectors.toList()); + + }**/ + if(productOption.getMerchantStore().getId().intValue()!=store.getId().intValue()) { throw new ConversionRuntimeException("Invalid product option id "); } - if(productOptionValue.getMerchantStore().getId().intValue()!=store.getId().intValue()) { + if(productOptionValue!=null && productOptionValue.getMerchantStore().getId().intValue()!=store.getId().intValue()) { throw new ConversionRuntimeException("Invalid product option value id "); } @@ -87,6 +121,7 @@ public ProductAttribute merge(PersistableProductAttribute source, ProductAttribu } else { destination.setId(null); } + destination.setProductOption(productOption); destination.setProductOptionValue(productOptionValue); destination.setProductAttributePrice(source.getProductAttributePrice());
sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/PersistableProductDefinitionMapper.java+40 −8 modified@@ -10,7 +10,6 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; -import org.drools.core.util.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -149,10 +148,10 @@ public Product merge(PersistableProductDefinition source, Product destination, M destination.setDescriptions(descriptions); } - if(source.getRating() != null) { - destination.setProductReviewAvg(new BigDecimal(source.getRating())); - } - destination.setProductReviewCount(source.getRatingCount()); + //if(source.getRating() != null) { + // destination.setProductReviewAvg(new BigDecimal(source.getRating())); + //} + //destination.setProductReviewCount(source.getRatingCount()); /** * Product definition @@ -167,9 +166,11 @@ public Product merge(PersistableProductDefinition source, Product destination, M if(productAvailability == null) { productAvailability = avail; defaultPrice = p; + productAvailability.setProductQuantity(source.getQuantity()); + productAvailability.setProductStatus(source.isCanBePurchased()); + p.setProductPriceAmount(source.getPrice()); break; } - p.setDefaultPrice(false); } } } @@ -179,11 +180,12 @@ public Product merge(PersistableProductDefinition source, Product destination, M productAvailability = new ProductAvailability(destination, store); destination.getAvailabilities().add(productAvailability); - productAvailability.setProductQuantity(1); + productAvailability.setProductQuantity(source.getQuantity()); productAvailability.setProductQuantityOrderMin(1); productAvailability.setProductQuantityOrderMax(1); productAvailability.setRegion(Constants.ALL_REGIONS); productAvailability.setAvailable(Boolean.valueOf(destination.isAvailable())); + productAvailability.setProductStatus(source.isCanBePurchased()); } @@ -193,7 +195,7 @@ public Product merge(PersistableProductDefinition source, Product destination, M defaultPrice = new ProductPrice(); defaultPrice.setDefaultPrice(true); - defaultPrice.setProductPriceAmount(new BigDecimal(0)); + defaultPrice.setProductPriceAmount(source.getPrice()); defaultPrice.setCode(ProductPriceEntity.DEFAULT_PRICE_CODE); defaultPrice.setProductAvailability(productAvailability); productAvailability.getPrices().add(defaultPrice); @@ -207,6 +209,36 @@ public Product merge(PersistableProductDefinition source, Product destination, M } } + if(source.getProductSpecifications()!=null) { + destination.setProductHeight(source.getProductSpecifications().getHeight()); + destination.setProductLength(source.getProductSpecifications().getLength()); + destination.setProductWeight(source.getProductSpecifications().getWeight()); + destination.setProductWidth(source.getProductSpecifications().getWidth()); + + + if(source.getProductSpecifications().getManufacturer()!=null) { + + Manufacturer manuf = null; + if(!StringUtils.isBlank(source.getProductSpecifications().getManufacturer())) { + manuf = manufacturerService.getByCode(store, source.getProductSpecifications().getManufacturer()); + } + + if(manuf==null) { + throw new ConversionException("Invalid manufacturer id"); + } + if(manuf!=null) { + if(manuf.getMerchantStore().getId().intValue()!=store.getId().intValue()) { + throw new ConversionException("Invalid manufacturer id"); + } + destination.setManufacturer(manuf); + } + } + + } + destination.setSortOrder(source.getSortOrder()); + destination.setProductVirtual(source.isVirtual()); + destination.setProductShipeable(source.isShipeable()); + //attributes if(source.getProperties()!=null) {
sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/PersistableProductOptionValueMapper.java+0 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductAttributeMapper.java+1 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductDefinitionMapper.java+52 −2 modifiedsm-shop/src/main/java/com/salesmanager/shop/populator/catalog/PersistableProductPopulator.java+47 −39 modifiedsm-shop/src/main/java/com/salesmanager/shop/populator/catalog/ReadableProductPopulator.java+204 −94 modifiedsm-shop/src/main/java/com/salesmanager/shop/populator/customer/CustomerOptionPopulator.java+13 −16 modifiedsm-shop/src/main/java/com/salesmanager/shop/populator/customer/ReadableCustomerOptionPopulator.java+14 −3 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v0/customer/CustomerRESTController.java+0 −385 removedsm-shop/src/main/java/com/salesmanager/shop/store/api/v0/search/SearchRESTController.java+0 −71 removedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/category/CategoryApi.java+3 −1 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/order/OrderApi.java+54 −23 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductApi.java+3 −3 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductAttributeOptionApi.java+51 −11 renamedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductPropertySetApi.java+27 −12 renamedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/store/MerchantStoreApi.java+1 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/system/ModulesApi.java+1 −3 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/api/v1/system/SearchToolsApi.java+86 −0 addedsm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/CustomerDashboardController.java+0 −133 removedsm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java+6 −6 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java+24 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacade.java+27 −21 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/controller/order/ShoppingOrderController.java+1 −2 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/controller/store/facade/StoreFacadeImpl.java+2 −10 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeImpl.java+1 −1 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionFacadeImpl.java+64 −13 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionSetFacadeImpl.java+52 −26 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductTypeFacadeImpl.java+18 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/store/facade/user/UserFacadeImpl.java+4 −0 modifiedsm-shop/src/main/java/com/salesmanager/shop/utils/CategoryUtils.java+0 −39 removedsm-shop/src/main/resources/bundles/messages_cn.properties+219 −0 addedsm-shop/src/main/resources/bundles/messages_pt_BR.properties+188 −0 addedsm-shop/src/main/resources/bundles/payment_pt_BR.properties+50 −0 addedsm-shop/src/main/resources/bundles/shipping_pt_BR.properties+107 −0 addedsm-shop/src/main/resources/bundles/shopizer_es.properties+1 −0 modifiedsm-shop/src/main/resources/bundles/shopizer_fr.properties+1 −1 modifiedsm-shop/src/main/resources/bundles/shopizer.properties+1 −0 modifiedsm-shop/src/main/resources/bundles/shopizer_pt_BR.properties+697 −0 addedsm-shop/src/main/resources/shopizer-properties.properties+1 −1 modifiedsm-shop/src/test/java/com/salesmanager/test/shop/integration/cart/ShoppingCartAPIIntegrationTest.java+15 −16 modifiedsm-shop/src/test/java/com/salesmanager/test/shop/util/GeneratePasswordTest.java+3 −14 modified
Vulnerability mechanics
Generated by null/stub on May 9, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.
References
4- github.com/advisories/GHSA-p2j7-6g9h-32xhghsaADVISORY
- nvd.nist.gov/vuln/detail/CVE-2022-23059ghsaADVISORY
- github.com/shopizer-ecommerce/shopizer/commit/6b9f1ecd303b3b724d96bd08095c1a751dcc287eghsax_refsource_CONFIRMWEB
- www.whitesourcesoftware.com/vulnerability-database/CVE-2022-23059ghsax_refsource_MISCWEB
News mentions
0No linked articles in our index yet.