<file_sep>package com.mmall.service.Impl;

import com.google.common.collect.Lists;
import com.mmall.common.ServerResponse;
import com.mmall.service.FileService;
import com.mmall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 *Author gaofeng <<EMAIL>>
 */
@Service
public class FileServiceImpl implements FileService{
    Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    public String  upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        String extensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String newFileName = UUID.randomUUID().toString()+extensionName;
        logger.info("文件开始上传，上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,path,newFileName);

        File fileDir = new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File fileTarget = new File(path,newFileName);
        try {
            //上传文件到Upload文件夹下
            file.transferTo(fileTarget);
            //然后再上传到FTP服务器上存储图片
            FTPUtil.uploadFile(Lists.newArrayList(fileTarget));
            //删除upload下的fileTarget文件
            fileTarget.delete();

        } catch (IOException e) {
            logger.error("上传失败",e);
            return null;
        }

        return fileTarget.getName();
    }
}
<file_sep>package com.mmall.service;

import com.mmall.common.ServerResponse;
import com.mmall.pojo.Shipping;

import java.util.Map;

/**
 *Author gaofeng <<EMAIL>>
 */
public interface ShippingService {
    ServerResponse<Map> add(Integer userId, Shipping shipping);
    ServerResponse delete(Integer userId,Integer shippingId);
    ServerResponse update(Integer userId,Shipping shipping);
    ServerResponse<Shipping> select(Integer userId,Integer shippingId);
}
<file_sep>package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.FileService;
import com.mmall.service.IUserService;
import com.mmall.service.ProductService;
import com.mmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *Author gaofeng <<EMAIL>>
 */
@Controller
@RequestMapping("/manage/product")
public class ProductManageController {

    @Autowired
    private IUserService iUserService;
    private ProductService productService;
    private FileService fileService;
    //后台新增或者更新产品接口
    @RequestMapping("/save.do")
    @ResponseBody
    public ServerResponse addOrUpdateProduct(HttpSession httpSession, Product product){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑
           return productService.addOrUpdateProduct(product);
        }else   {
            return ServerResponse.createByError("新增或者更新失败");
        }
    }
    //后台管理员更新产品销售状态
    @RequestMapping("set_sale_status.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession httpSession, Integer productId,Integer status){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑
            return productService.setSaleStatus(productId,status);
        }else   {
            return ServerResponse.createByError("无权限操作");
        }
    }
    //获取商品详情
    @RequestMapping("detail.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession httpSession, Integer productId){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑
           return productService.manageProductDetail(productId);
        }else   {
            return ServerResponse.createByError("无权限操作");
         }
    }
    //产品list
    @RequestMapping("list.do")
    @ResponseBody
    public ServerResponse getList(HttpSession httpSession, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑
            return productService.getProductList(pageNum,pageSize);
        }else   {
            return ServerResponse.createByError("无权限操作");
        }
    }
    //后台产品搜索接口
    @RequestMapping("search.do")
    @ResponseBody
    public ServerResponse getList(HttpSession httpSession,String productName,Integer productId, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑
            return productService.searchProduct(productName,productId,pageNum,pageSize);
        }else   {
            return ServerResponse.createByError("无权限操作");
        }
    }
    //图片文件上传
    @RequestMapping("upload.do")
    @ResponseBody
    public ServerResponse upload(HttpSession httpSession, MultipartFile file, HttpServletRequest request){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑,返回图片的存储名称和它在服务器中的地址
            String path = request.getSession().getServletContext().getRealPath("upload");
            String fileTargetName = fileService.upload(file, path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/") + fileTargetName;
            HashMap<String, String > mapFile = Maps.newHashMap();
            mapFile.put("uri",fileTargetName);
            mapFile.put("url",url);
            return ServerResponse.createBySuccess(mapFile);
        }else   {
            return ServerResponse.createByError("无权限操作");
        }
    }
    //富文本编辑器图片上传，由于前端使用simditor富文本，应该按照官方文档的返回格式返回(可以用map来接收)，加上对应的响应头
    @RequestMapping("richtext_img_upload.do")
    @ResponseBody
    public Map richtextImgUpload(HttpSession httpSession, MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        User user = (User) httpSession.getAttribute(Const.CURRENT_USER);
        Map map = Maps.newHashMap();
        if (user==null){
            map.put("success","false");
            map.put("msg","用户未登陆");
            map.put("file_path","[real file path]");
            return map;
        }
        if (iUserService.checkAdmin(user).isSuccess()){
            //添加业务逻辑,返回图片的存储名称和它在服务器中的地址
            String path = request.getSession().getServletContext().getRealPath("upload");
            String fileTargetName = fileService.upload(file, path);
            if (StringUtils.isBlank(fileTargetName)){
                map.put("success","false");
                map.put("msg","上传失败");
                return map;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/") + fileTargetName;
            map.put("success","true");
            map.put("msg","上传成功");
            map.put("file_path",url);
            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
            return map;
        }else   {
            map.put("success","false");
            map.put("msg","无权限操作");
            map.put("file_path","[real file path]");
            return map;
        }
    }
}
<file_sep>package com.mmall.common;

import com.google.common.collect.Sets;

import java.util.Set;

/**
 *Author gaofeng <<EMAIL>>
 */
public class Const {

    public static final String CURRENT_USER = "currentUser";
    public static final String EMAIL = "email";
    public static final String USERNAME = "username";
    public interface Role{
        int ROLE_COSTEMER=0;//用户
        int ROLE_ADMIN=1;//管理员
    }
    public interface CartCheck{
        Integer CHECKED = 1;//已选择
        Integer UN_CHECKED = 0;//未选择
        String LIMIT_NUM_FAIL = "LIMIT_NUM_FAIL";
        String LIMIT_NUM_SUCCESS = "LIMIT_NUM_SUCCESS";
    }
    public interface ProductListOrderBy{
        Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc");
    }
    public enum ProductStatus{
        ON_SALE("商品在架",1);
        private String status;
        private int num;
        ProductStatus(String status,int num){
            this.status = status;
            this.num = num;
        }

        public String getStatus() {
            return status;
        }

        public int getNum() {
            return num;
        }
    }

}
<file_sep>package com.mmall.service.Impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.CartService;
import com.mmall.util.BigDecimalUtil;
import com.mmall.vo.CartProductVo;
import com.mmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 *Author gaofeng <<EMAIL>>
 */
@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    //购物车添加商品
    public ServerResponse<CartVo> add(Integer userId,Integer productId,Integer count){
        if (productId==null || count==null){
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCart(userId, productId);
        if (cart==null){
            Cart newCart = new Cart();
            newCart.setUserId(userId);
            newCart.setProductId(productId);
            newCart.setQuantity(count);
            newCart.setChecked(Const.CartCheck.CHECKED);
            cartMapper.insert(newCart);
        }else {
            count = count + cart.getQuantity();
            cart.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        CartVo cartVo = getCartVoLimit(userId);

        return ServerResponse.createBySuccess(cartVo);
    }
    //更新购物车产品数量
    public ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count){
        if (productId==null || count==null){
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCart(userId, productId);
        if (cart!=null){
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.getCartVo(userId);
    }
    //删除购物车里面的商品
    public ServerResponse<CartVo> delete(Integer userId,String productIds){
        if (StringUtils.isBlank(productIds)){
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<String> list = Splitter.on(",").splitToList(productIds);
        cartMapper.deleteByUserIdAndProductIds(userId,list);
        return this.getCartVo(userId);
    }
    //查询购物车List
    public ServerResponse<CartVo> list(Integer userId){
        return this.list(userId);
    }
    //选择或者不选择购物车商品
    public ServerResponse<CartVo> selectOrUnselect(Integer userId,Integer productId,Integer check){
        cartMapper.updateCheck(userId, productId, check);
        return this.list(userId);
    }
    //获取购物车产品数量
    public ServerResponse<Integer> getProductCount(Integer userId){
        if (userId==null){
            return ServerResponse.createByError("0");
        }
        return ServerResponse.createBySuccess(cartMapper.getProductCount(userId));
    }





    //购物车操作通用功能方法
    private ServerResponse<CartVo> getCartVo(Integer userId){
        CartVo newCartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(newCartVo);
    }


    private CartVo getCartVoLimit(Integer userId){
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);
        List<CartProductVo> cartProductVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");
        if (CollectionUtils.isNotEmpty(cartList)){
            for (Cart cartItem:cartList
                 ) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(cartItem.getUserId());
                cartProductVo.setProductId(cartItem.getProductId());
                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if (product!=null){
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductChecked(cartItem.getChecked());
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductStock(product.getStock());
                    if (product.getStock()>=cartItem.getQuantity()){
                        //库存充足
                        cartProductVo.setLimitQuantity(Const.CartCheck.LIMIT_NUM_SUCCESS);
                        cartProductVo.setQuantity(cartItem.getQuantity());
                    }else {
                        //库存不足时先在购物车更新有效库存
                        int canBuy = product.getStock();
                        Cart updateCartQuantity = new Cart();
                        updateCartQuantity.setId(cartItem.getId());
                        updateCartQuantity.setQuantity(canBuy);
                        cartMapper.updateByPrimaryKeySelective(updateCartQuantity);
                        cartProductVo.setLimitQuantity(Const.CartCheck.LIMIT_NUM_FAIL);
                        cartProductVo.setQuantity(product.getStock());
                    }
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartProductVo.getQuantity()));
                    if(cartItem.getChecked()==Const.CartCheck.CHECKED){
                        cartTotalPrice=BigDecimalUtil.add(cartProductVo.getProductTotalPrice().doubleValue(),cartTotalPrice.doubleValue());
                    }
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        cartVo.setImageHost("ftp.server.http.prefix");
        return cartVo;
    }
    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;

    }





}
<file_sep>package com.mmall.service;

import com.mmall.common.ServerResponse;
import com.mmall.vo.CartVo;

/**
 *Author gaofeng <<EMAIL>>
 */
public interface CartService {
    ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count);
    ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count);
    ServerResponse<CartVo> delete(Integer userId,String productIds);
    ServerResponse<CartVo> list(Integer userId);
    ServerResponse<CartVo> selectOrUnselect(Integer userId,Integer productId,Integer check);
    ServerResponse<Integer> getProductCount(Integer userId);

}
