net.groupbuy.controller.admin.ProductController.java Source code

Java tutorial

Introduction

Here is the source code for net.groupbuy.controller.admin.ProductController.java

Source

/*
 * Copyright 2005-2013 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package net.groupbuy.controller.admin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.groupbuy.Message;
import net.groupbuy.Pageable;
import net.groupbuy.Setting;
import net.groupbuy.FileInfo.FileType;
import net.groupbuy.entity.Attribute;
import net.groupbuy.entity.Brand;
import net.groupbuy.entity.Goods;
import net.groupbuy.entity.MemberRank;
import net.groupbuy.entity.Parameter;
import net.groupbuy.entity.ParameterGroup;
import net.groupbuy.entity.Product;
import net.groupbuy.entity.ProductCategory;
import net.groupbuy.entity.ProductImage;
import net.groupbuy.entity.Promotion;
import net.groupbuy.entity.Specification;
import net.groupbuy.entity.SpecificationValue;
import net.groupbuy.entity.Tag;
import net.groupbuy.entity.Product.OrderType;
import net.groupbuy.entity.Tag.Type;
import net.groupbuy.service.BrandService;
import net.groupbuy.service.FileService;
import net.groupbuy.service.GoodsService;
import net.groupbuy.service.MemberRankService;
import net.groupbuy.service.ProductCategoryService;
import net.groupbuy.service.ProductImageService;
import net.groupbuy.service.ProductService;
import net.groupbuy.service.PromotionService;
import net.groupbuy.service.SpecificationService;
import net.groupbuy.service.SpecificationValueService;
import net.groupbuy.service.TagService;
import net.groupbuy.util.SettingUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.servlet.mvc.support.RedirectAttributes;

/**
 * Controller - ?
 * 
 * @author SHOP++ Team
 * @version 3.0
 */
@Controller("adminProductController")
@RequestMapping("/admin/product")
public class ProductController extends BaseController {

    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "productCategoryServiceImpl")
    private ProductCategoryService productCategoryService;
    @Resource(name = "goodsServiceImpl")
    private GoodsService goodsService;
    @Resource(name = "brandServiceImpl")
    private BrandService brandService;
    @Resource(name = "promotionServiceImpl")
    private PromotionService promotionService;
    @Resource(name = "tagServiceImpl")
    private TagService tagService;
    @Resource(name = "memberRankServiceImpl")
    private MemberRankService memberRankService;
    @Resource(name = "productImageServiceImpl")
    private ProductImageService productImageService;
    @Resource(name = "specificationServiceImpl")
    private SpecificationService specificationService;
    @Resource(name = "specificationValueServiceImpl")
    private SpecificationValueService specificationValueService;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;

    /**
     * ??
     */
    @RequestMapping(value = "/check_sn", method = RequestMethod.GET)
    public @ResponseBody boolean checkSn(String previousSn, String sn) {
        if (StringUtils.isEmpty(sn)) {
            return false;
        }
        if (productService.snUnique(previousSn, sn)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * ??
     */
    @RequestMapping(value = "/parameter_groups", method = RequestMethod.GET)
    public @ResponseBody Set<ParameterGroup> parameterGroups(Long id) {
        ProductCategory productCategory = productCategoryService.find(id);
        return productCategory.getParameterGroups();
    }

    /**
     * ?
     */
    @RequestMapping(value = "/attributes", method = RequestMethod.GET)
    public @ResponseBody Set<Attribute> attributes(Long id) {
        ProductCategory productCategory = productCategoryService.find(id);
        return productCategory.getAttributes();
    }

    /**
     * 
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model) {
        model.addAttribute("productCategoryTree", productCategoryService.findTree());
        model.addAttribute("brands", brandService.findAll());
        model.addAttribute("tags", tagService.findList(Type.product));
        model.addAttribute("memberRanks", memberRankService.findAll());
        model.addAttribute("specifications", specificationService.findAll());
        return "/admin/product/add";
    }

    /**
     * ?
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Product product, Long productCategoryId, Long brandId, Long[] tagIds,
            Long[] specificationIds, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
            ProductImage productImage = iterator.next();
            if (productImage == null || productImage.isEmpty()) {
                iterator.remove();
                continue;
            }
            if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
                if (!fileService.isValid(FileType.image, productImage.getFile())) {
                    addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
                    return "redirect:add.jhtml";
                }
            }
        }
        product.setProductCategory(productCategoryService.find(productCategoryId));
        product.setBrand(brandService.find(brandId));
        product.setTags(new HashSet<Tag>(tagService.findList(tagIds)));
        if (!isValid(product)) {
            return ERROR_VIEW;
        }
        if (StringUtils.isNotEmpty(product.getSn()) && productService.snExists(product.getSn())) {
            return ERROR_VIEW;
        }
        if (product.getMarketPrice() == null) {
            BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product.getPrice());
            product.setMarketPrice(defaultMarketPrice);
        }
        if (product.getPoint() == null) {
            long point = calculateDefaultPoint(product.getPrice());
            product.setPoint(point);
        }
        product.setFullName(null);
        product.setAllocatedStock(0);
        product.setScore(0F);
        product.setTotalScore(0L);
        product.setScoreCount(0L);
        product.setHits(0L);
        product.setWeekHits(0L);
        product.setMonthHits(0L);
        product.setSales(0L);
        product.setWeekSales(0L);
        product.setMonthSales(0L);
        product.setWeekHitsDate(new Date());
        product.setMonthHitsDate(new Date());
        product.setWeekSalesDate(new Date());
        product.setMonthSalesDate(new Date());
        product.setReviews(null);
        product.setConsultations(null);
        product.setFavoriteMembers(null);
        product.setPromotions(null);
        product.setCartItems(null);
        product.setOrderItems(null);
        product.setGiftItems(null);
        product.setProductNotifies(null);

        for (MemberRank memberRank : memberRankService.findAll()) {
            String price = request.getParameter("memberPrice_" + memberRank.getId());
            if (StringUtils.isNotEmpty(price) && new BigDecimal(price).compareTo(new BigDecimal(0)) >= 0) {
                product.getMemberPrice().put(memberRank, new BigDecimal(price));
            } else {
                product.getMemberPrice().remove(memberRank);
            }
        }

        for (ProductImage productImage : product.getProductImages()) {
            productImageService.build(productImage);
        }
        Collections.sort(product.getProductImages());
        if (product.getImage() == null && product.getThumbnail() != null) {
            product.setImage(product.getThumbnail());
        }

        for (ParameterGroup parameterGroup : product.getProductCategory().getParameterGroups()) {
            for (Parameter parameter : parameterGroup.getParameters()) {
                String parameterValue = request.getParameter("parameter_" + parameter.getId());
                if (StringUtils.isNotEmpty(parameterValue)) {
                    product.getParameterValue().put(parameter, parameterValue);
                } else {
                    product.getParameterValue().remove(parameter);
                }
            }
        }

        for (Attribute attribute : product.getProductCategory().getAttributes()) {
            String attributeValue = request.getParameter("attribute_" + attribute.getId());
            if (StringUtils.isNotEmpty(attributeValue)) {
                product.setAttributeValue(attribute, attributeValue);
            } else {
                product.setAttributeValue(attribute, null);
            }
        }

        Goods goods = new Goods();
        List<Product> products = new ArrayList<Product>();
        if (specificationIds != null && specificationIds.length > 0) {
            for (int i = 0; i < specificationIds.length; i++) {
                Specification specification = specificationService.find(specificationIds[i]);
                String[] specificationValueIds = request
                        .getParameterValues("specification_" + specification.getId());
                if (specificationValueIds != null && specificationValueIds.length > 0) {
                    for (int j = 0; j < specificationValueIds.length; j++) {
                        if (i == 0) {
                            if (j == 0) {
                                product.setGoods(goods);
                                product.setSpecifications(new HashSet<Specification>());
                                product.setSpecificationValues(new HashSet<SpecificationValue>());
                                products.add(product);
                            } else {
                                Product specificationProduct = new Product();
                                BeanUtils.copyProperties(product, specificationProduct);
                                specificationProduct.setId(null);
                                specificationProduct.setCreateDate(null);
                                specificationProduct.setModifyDate(null);
                                specificationProduct.setSn(null);
                                specificationProduct.setFullName(null);
                                specificationProduct.setAllocatedStock(0);
                                specificationProduct.setIsList(false);
                                specificationProduct.setScore(0F);
                                specificationProduct.setTotalScore(0L);
                                specificationProduct.setScoreCount(0L);
                                specificationProduct.setHits(0L);
                                specificationProduct.setWeekHits(0L);
                                specificationProduct.setMonthHits(0L);
                                specificationProduct.setSales(0L);
                                specificationProduct.setWeekSales(0L);
                                specificationProduct.setMonthSales(0L);
                                specificationProduct.setWeekHitsDate(new Date());
                                specificationProduct.setMonthHitsDate(new Date());
                                specificationProduct.setWeekSalesDate(new Date());
                                specificationProduct.setMonthSalesDate(new Date());
                                specificationProduct.setGoods(goods);
                                specificationProduct.setReviews(null);
                                specificationProduct.setConsultations(null);
                                specificationProduct.setFavoriteMembers(null);
                                specificationProduct.setSpecifications(new HashSet<Specification>());
                                specificationProduct.setSpecificationValues(new HashSet<SpecificationValue>());
                                specificationProduct.setPromotions(null);
                                specificationProduct.setCartItems(null);
                                specificationProduct.setOrderItems(null);
                                specificationProduct.setGiftItems(null);
                                specificationProduct.setProductNotifies(null);
                                products.add(specificationProduct);
                            }
                        }
                        Product specificationProduct = products.get(j);
                        SpecificationValue specificationValue = specificationValueService
                                .find(Long.valueOf(specificationValueIds[j]));
                        specificationProduct.getSpecifications().add(specification);
                        specificationProduct.getSpecificationValues().add(specificationValue);
                    }
                }
            }
        } else {
            product.setGoods(goods);
            product.setSpecifications(null);
            product.setSpecificationValues(null);
            products.add(product);
        }
        goods.getProducts().clear();
        goods.getProducts().addAll(products);
        goodsService.save(goods);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("productCategoryTree", productCategoryService.findTree());
        model.addAttribute("brands", brandService.findAll());
        model.addAttribute("tags", tagService.findList(Type.product));
        model.addAttribute("memberRanks", memberRankService.findAll());
        model.addAttribute("specifications", specificationService.findAll());
        model.addAttribute("product", productService.find(id));
        return "/admin/product/edit";
    }

    /**
     * 
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Product product, Long productCategoryId, Long brandId, Long[] tagIds,
            Long[] specificationIds, Long[] specificationProductIds, HttpServletRequest request,
            RedirectAttributes redirectAttributes) {
        for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
            ProductImage productImage = iterator.next();
            if (productImage == null || productImage.isEmpty()) {
                iterator.remove();
                continue;
            }
            if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
                if (!fileService.isValid(FileType.image, productImage.getFile())) {
                    addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
                    return "redirect:edit.jhtml?id=" + product.getId();
                }
            }
        }
        product.setProductCategory(productCategoryService.find(productCategoryId));
        product.setBrand(brandService.find(brandId));
        product.setTags(new HashSet<Tag>(tagService.findList(tagIds)));
        if (!isValid(product)) {
            return ERROR_VIEW;
        }
        Product pProduct = productService.find(product.getId());
        if (pProduct == null) {
            return ERROR_VIEW;
        }
        if (StringUtils.isNotEmpty(product.getSn())
                && !productService.snUnique(pProduct.getSn(), product.getSn())) {
            return ERROR_VIEW;
        }
        if (product.getMarketPrice() == null) {
            BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product.getPrice());
            product.setMarketPrice(defaultMarketPrice);
        }
        if (product.getPoint() == null) {
            long point = calculateDefaultPoint(product.getPrice());
            product.setPoint(point);
        }

        for (MemberRank memberRank : memberRankService.findAll()) {
            String price = request.getParameter("memberPrice_" + memberRank.getId());
            if (StringUtils.isNotEmpty(price) && new BigDecimal(price).compareTo(new BigDecimal(0)) >= 0) {
                product.getMemberPrice().put(memberRank, new BigDecimal(price));
            } else {
                product.getMemberPrice().remove(memberRank);
            }
        }

        for (ProductImage productImage : product.getProductImages()) {
            productImageService.build(productImage);
        }
        Collections.sort(product.getProductImages());
        if (product.getImage() == null && product.getThumbnail() != null) {
            product.setImage(product.getThumbnail());
        }

        for (ParameterGroup parameterGroup : product.getProductCategory().getParameterGroups()) {
            for (Parameter parameter : parameterGroup.getParameters()) {
                String parameterValue = request.getParameter("parameter_" + parameter.getId());
                if (StringUtils.isNotEmpty(parameterValue)) {
                    product.getParameterValue().put(parameter, parameterValue);
                } else {
                    product.getParameterValue().remove(parameter);
                }
            }
        }

        for (Attribute attribute : product.getProductCategory().getAttributes()) {
            String attributeValue = request.getParameter("attribute_" + attribute.getId());
            if (StringUtils.isNotEmpty(attributeValue)) {
                product.setAttributeValue(attribute, attributeValue);
            } else {
                product.setAttributeValue(attribute, null);
            }
        }

        Goods goods = pProduct.getGoods();
        List<Product> products = new ArrayList<Product>();
        if (specificationIds != null && specificationIds.length > 0) {
            for (int i = 0; i < specificationIds.length; i++) {
                Specification specification = specificationService.find(specificationIds[i]);
                String[] specificationValueIds = request
                        .getParameterValues("specification_" + specification.getId());
                if (specificationValueIds != null && specificationValueIds.length > 0) {
                    for (int j = 0; j < specificationValueIds.length; j++) {
                        if (i == 0) {
                            if (j == 0) {
                                BeanUtils.copyProperties(product, pProduct,
                                        new String[] { "id", "createDate", "modifyDate", "fullName",
                                                "allocatedStock", "score", "totalScore", "scoreCount", "hits",
                                                "weekHits", "monthHits", "sales", "weekSales", "monthSales",
                                                "weekHitsDate", "monthHitsDate", "weekSalesDate", "monthSalesDate",
                                                "goods", "reviews", "consultations", "favoriteMembers",
                                                "specifications", "specificationValues", "promotions", "cartItems",
                                                "orderItems", "giftItems", "productNotifies" });
                                pProduct.setSpecifications(new HashSet<Specification>());
                                pProduct.setSpecificationValues(new HashSet<SpecificationValue>());
                                products.add(pProduct);
                            } else {
                                if (specificationProductIds != null && j < specificationProductIds.length) {
                                    Product specificationProduct = productService.find(specificationProductIds[j]);
                                    if (specificationProduct == null || (specificationProduct.getGoods() != null
                                            && !specificationProduct.getGoods().equals(goods))) {
                                        return ERROR_VIEW;
                                    }
                                    specificationProduct.setSpecifications(new HashSet<Specification>());
                                    specificationProduct.setSpecificationValues(new HashSet<SpecificationValue>());
                                    products.add(specificationProduct);
                                } else {
                                    Product specificationProduct = new Product();
                                    BeanUtils.copyProperties(product, specificationProduct);
                                    specificationProduct.setId(null);
                                    specificationProduct.setCreateDate(null);
                                    specificationProduct.setModifyDate(null);
                                    specificationProduct.setSn(null);
                                    specificationProduct.setFullName(null);
                                    specificationProduct.setAllocatedStock(0);
                                    specificationProduct.setIsList(false);
                                    specificationProduct.setScore(0F);
                                    specificationProduct.setTotalScore(0L);
                                    specificationProduct.setScoreCount(0L);
                                    specificationProduct.setHits(0L);
                                    specificationProduct.setWeekHits(0L);
                                    specificationProduct.setMonthHits(0L);
                                    specificationProduct.setSales(0L);
                                    specificationProduct.setWeekSales(0L);
                                    specificationProduct.setMonthSales(0L);
                                    specificationProduct.setWeekHitsDate(new Date());
                                    specificationProduct.setMonthHitsDate(new Date());
                                    specificationProduct.setWeekSalesDate(new Date());
                                    specificationProduct.setMonthSalesDate(new Date());
                                    specificationProduct.setGoods(goods);
                                    specificationProduct.setReviews(null);
                                    specificationProduct.setConsultations(null);
                                    specificationProduct.setFavoriteMembers(null);
                                    specificationProduct.setSpecifications(new HashSet<Specification>());
                                    specificationProduct.setSpecificationValues(new HashSet<SpecificationValue>());
                                    specificationProduct.setPromotions(null);
                                    specificationProduct.setCartItems(null);
                                    specificationProduct.setOrderItems(null);
                                    specificationProduct.setGiftItems(null);
                                    specificationProduct.setProductNotifies(null);
                                    products.add(specificationProduct);
                                }
                            }
                        }
                        Product specificationProduct = products.get(j);
                        SpecificationValue specificationValue = specificationValueService
                                .find(Long.valueOf(specificationValueIds[j]));
                        specificationProduct.getSpecifications().add(specification);
                        specificationProduct.getSpecificationValues().add(specificationValue);
                    }
                }
            }
        } else {
            product.setSpecifications(null);
            product.setSpecificationValues(null);
            BeanUtils.copyProperties(product, pProduct,
                    new String[] { "id", "createDate", "modifyDate", "fullName", "allocatedStock", "score",
                            "totalScore", "scoreCount", "hits", "weekHits", "monthHits", "sales", "weekSales",
                            "monthSales", "weekHitsDate", "monthHitsDate", "weekSalesDate", "monthSalesDate",
                            "goods", "reviews", "consultations", "favoriteMembers", "promotions", "cartItems",
                            "orderItems", "giftItems", "productNotifies" });
            products.add(pProduct);
        }
        goods.getProducts().clear();
        goods.getProducts().addAll(products);
        goodsService.update(goods);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Long productCategoryId, Long brandId, Long promotionId, Long tagId, Boolean isMarketable,
            Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
            Pageable pageable, ModelMap model) {
        ProductCategory productCategory = productCategoryService.find(productCategoryId);
        Brand brand = brandService.find(brandId);
        Promotion promotion = promotionService.find(promotionId);
        List<Tag> tags = tagService.findList(tagId);
        model.addAttribute("productCategoryTree", productCategoryService.findTree());
        model.addAttribute("brands", brandService.findAll());
        model.addAttribute("promotions", promotionService.findAll());
        model.addAttribute("tags", tagService.findList(Type.product));
        model.addAttribute("productCategoryId", productCategoryId);
        model.addAttribute("brandId", brandId);
        model.addAttribute("promotionId", promotionId);
        model.addAttribute("tagId", tagId);
        model.addAttribute("isMarketable", isMarketable);
        model.addAttribute("isList", isList);
        model.addAttribute("isTop", isTop);
        model.addAttribute("isGift", isGift);
        model.addAttribute("isOutOfStock", isOutOfStock);
        model.addAttribute("isStockAlert", isStockAlert);
        model.addAttribute("page",
                productService.findPage(productCategory, brand, promotion, tags, null, null, null, isMarketable,
                        isList, isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc, pageable));
        return "/admin/product/list";
    }

    /**
     * 
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody Message delete(Long[] ids) {
        productService.delete(ids);
        return SUCCESS_MESSAGE;
    }

    /**
     * 
     * 
     * @param price
     *            
     */
    private BigDecimal calculateDefaultMarketPrice(BigDecimal price) {
        Setting setting = SettingUtils.get();
        Double defaultMarketPriceScale = setting.getDefaultMarketPriceScale();
        return setting.setScale(price.multiply(new BigDecimal(defaultMarketPriceScale.toString())));
    }

    /**
     * 
     * 
     * @param price
     *            
     */
    private long calculateDefaultPoint(BigDecimal price) {
        Setting setting = SettingUtils.get();
        Double defaultPointScale = setting.getDefaultPointScale();
        return price.multiply(new BigDecimal(defaultPointScale.toString())).longValue();
    }

}