浏览代码

Add 添加食品

enilu 6 年之前
父节点
当前提交
e03a0c14cb

+ 45 - 11
flash-waimai-api/src/main/java/cn/enilu/flash/api/controller/business/FoodController.java

@@ -11,6 +11,7 @@ import cn.enilu.flash.bean.vo.business.SpecVo;
 import cn.enilu.flash.bean.vo.front.Rets;
 import cn.enilu.flash.dao.MongoRepository;
 import cn.enilu.flash.service.front.IdsService;
+import cn.enilu.flash.utils.BeanUtil;
 import cn.enilu.flash.utils.Lists;
 import cn.enilu.flash.utils.Maps;
 import cn.enilu.flash.utils.StringUtils;
@@ -19,11 +20,11 @@ import org.nutz.json.Json;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
-import javax.servlet.http.HttpServletRequest;
 import javax.validation.Valid;
 import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 
 /**
  * Created  on 2017/12/29 0029.
@@ -40,25 +41,58 @@ public class FoodController extends BaseController {
     @Autowired
     private IdsService idsService;
 
-    @RequestMapping(value = "addfood",method = RequestMethod.GET)
+    @RequestMapping(value = "addfood",method = RequestMethod.POST)
+    public Object add(@Valid @ModelAttribute FoodVo foodVo) {
+        System.out.println(Json.toJson(foodVo));
+        Food food = new Food();
+        BeanUtil.copyProperties(foodVo,food);
+        food.setRestaurant_id(foodVo.getIdShop());
+        List<SpecVo> specVoList = Json.fromJsonAsList(SpecVo.class,foodVo.getSpecsJson());
+        List<SpecFood> specList = Lists.newArrayList();
+        for(SpecVo specVo:specVoList){
+            SpecFood specFood = new SpecFood();
+            specFood.setName(specVo.getSpecs());
+            specFood.setPinyin_name(StringUtils.getPingYin(specVo.getSpecs()));
+            specFood.setPrice(Double.valueOf(specVo.getPrice()));
+            specFood.setPacking_fee(Double.valueOf(specVo.getPacking_fee()));
+            specFood.setSpecs_name(specVo.getSpecs());
+            specList.add(specFood);
+        }
+        List<String> attributes = Json.fromJsonAsList(String.class,foodVo.getAttributesJson());
+        List<Map> attributes1 = Lists.newArrayList();
+        for(String attribute:attributes){
+            switch (attribute) {
+                case "新":
+                    attributes1.add(Maps.newHashMap(
+                            "icon_color", "5ec452",
+                            "icon_name", "新"
+                    ));
+
+                    break;
+                case "招牌":
+                    attributes1.add(Maps.newHashMap(
+                            "icon_color", "f07373",
+                            "icon_name", "'招牌'"
+                    ));
+                    break;
+            }
 
-    public Object add(HttpServletRequest request) {
-        String json = getRequestPayload();
-        Food food = Json.fromJson(Food.class, json);
+        }
+        food.setAttributes(attributes1);
+        food.setDescription(foodVo.getDescript());
+        food.setSpecfoods(specList);
         food.setItem_id(idsService.getId(Ids.ITEM_ID));
-        List<SpecFood> specFoods = new ArrayList<SpecFood>(2);
-        specFoods.add(buidSpecFood(food));
-        food.setSpecfoods(specFoods);
         setTips(food);
+        food.setPinyin_name(StringUtils.getPingYin(food.getName()));
         food.setSatisfy_rate(new BigDecimal(Math.ceil(Math.random() * 100)).setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());
         food.setSatisfy_count(new BigDecimal(Math.ceil(Math.random() * 1000)).setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());
         food.setRating(new BigDecimal(Math.random() * 5).setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());
+        System.out.println(Json.toJson(food));
         mongoRepository.save(food);
         return Rets.success();
     }
     @RequestMapping(value="/v2/foods",method = RequestMethod.GET)
-    public Object list(@RequestParam(value = "restaurant_id",required = false) Long restaurantId
-                       ) {
+    public Object list(@RequestParam(value = "restaurant_id",required = false) Long restaurantId) {
         //restaurantId="11";
         Page<Food> page = new PageFactory<Food>().defaultPage();
         if (StringUtils.isNullOrEmpty(restaurantId) || "undefined".equals(restaurantId)) {
@@ -92,9 +126,9 @@ public class FoodController extends BaseController {
             specFood.setSpecs_name(specVo.getSpecs());
             specList.add(specFood);
         }
-
         Food old = mongoRepository.findOne(Food.class,"item_id",food.getId());
         old.setName(food.getName());
+        old.setPinyin_name(StringUtils.getPingYin(food.getName()));
         old.setDescription(food.getDescript());
         old.setCategory_id(food.getIdMenu());
         old.setImage_path(food.getImagePath());

+ 1 - 4
flash-waimai-api/src/main/java/cn/enilu/flash/api/controller/business/ShopController.java

@@ -22,7 +22,6 @@ import org.springframework.data.geo.GeoResult;
 import org.springframework.data.geo.GeoResults;
 import org.springframework.web.bind.annotation.*;
 
-import javax.servlet.http.HttpServletRequest;
 import javax.validation.Valid;
 import java.util.*;
 
@@ -204,8 +203,7 @@ public class ShopController extends BaseController {
 
     @RequestMapping(value = "addcategory", method = RequestMethod.POST)
 
-    public Object addCategory(HttpServletRequest request) {
-        Menu menu = getRequestPayload(Menu.class);
+    public Object addCategory(@Valid @ModelAttribute Menu menu) {
         menu.setId(idsService.getId(Ids.CATEGORY_ID));
         System.out.println(Json.toJson(menu));
         //todo 进行处理后保存
@@ -220,7 +218,6 @@ public class ShopController extends BaseController {
     }
 
     @RequestMapping(value = "/getcategory/{id}", method = RequestMethod.GET)
-
     public Object getCategory(@PathVariable("id") Long restaurantId) {
         List list = mongoRepository.findAll("menus", "restaurant_id", restaurantId);
         return Rets.success("category_list", list);

+ 4 - 0
flash-waimai-core/pom.xml

@@ -105,6 +105,10 @@
             <artifactId>commons-codec</artifactId>
         </dependency>
         <dependency>
+            <groupId>com.belerweb</groupId>
+            <artifactId>pinyin4j</artifactId>
+        </dependency>
+        <dependency>
             <groupId>org.quartz-scheduler</groupId>
             <artifactId>quartz</artifactId>
         </dependency>

+ 4 - 1
flash-waimai-core/src/main/java/cn/enilu/flash/bean/vo/business/FoodVo.java

@@ -1,5 +1,6 @@
 package cn.enilu.flash.bean.vo.business;
 
+import cn.enilu.flash.bean.entity.front.Food;
 import lombok.Data;
 
 import java.util.List;
@@ -10,7 +11,7 @@ import java.util.List;
  * @date :Created in 2019/9/7 10:36
  */
 @Data
-public class FoodVo {
+public class FoodVo  extends Food {
     private Long id;
     private String name;
     private String descript;
@@ -19,5 +20,7 @@ public class FoodVo {
     private Long idShop;
     private List<SpecVo> specs;
     private String specsJson;
+    private String attributesJson;
+
 
 }

+ 34 - 73
flash-waimai-core/src/main/java/cn/enilu/flash/utils/StringUtils.java

@@ -2,16 +2,17 @@ package cn.enilu.flash.utils;
 
 
 import com.google.common.base.Strings;
+import net.sourceforge.pinyin4j.PinyinHelper;
+import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
+import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
+import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
+import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
+import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 
 import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Field;
 import java.nio.charset.Charset;
-import java.text.DecimalFormat;
 import java.util.Arrays;
-import java.util.Date;
 import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 /**
@@ -23,10 +24,8 @@ import java.util.regex.Pattern;
 public class StringUtils {
 
     public static final String EMPTY = "";
-    private static final AtomicLong ORDER_SEQ = new AtomicLong(1);
     private static final Pattern SELECT_PATTERN_COMPILE = Pattern.compile("(?si)^.*?select(.*?)from");
 
-    private static final Pattern PATTERN_URL_VERSION = Pattern.compile("/.*?/.*?/.*?/(v[0-9]+)");
     private static  final Pattern PATERN_IP = Pattern.compile("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
     /**
      * 是否为空字符
@@ -207,7 +206,6 @@ public class StringUtils {
      * 根据文件扩展名判断文件类型,是否为图片文件
      */
     public static boolean isPic(String fileName) {
-        // return fileName.matches("[\\s\\S]+.[gif|jpg|png|jpeg|bmp]");
         return fileName.matches("^[\\s\\S]+\\.+(gif|jpg|jpeg|png|bmp)$");
     }
 
@@ -215,13 +213,6 @@ public class StringUtils {
         return PATERN_IP.matcher(ip).find();
     }
 
-    public static String getMethod(Field field) {
-        return (field.getType() == boolean.class ? "is" : "get") + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
-    }
-
-    public static String getMethod(String field) {
-        return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
-    }
 
     /**
      * 根据文件扩展名判断文件类型,是否为图片文件
@@ -245,39 +236,6 @@ public class StringUtils {
         return false;
     }
 
-    /**
-     * 获取MD5摘要信息
-     */
-    public static String getMD5(String msg) {
-        return MD5.getMD5String(msg);
-    }
-
-    /**
-     * 获取新的订单号
-     */
-    public static String getNewOrderNo() {
-        String orderNo = DateUtil.format(new Date(),"yyyyMMddHHmmssSSS");
-        orderNo += String.format("%04d", ORDER_SEQ.incrementAndGet() % 9999 + 1);
-        return orderNo;
-    }
-
-    /**
-     * 获取新支付交易号
-     */
-    public static String getReqSnNo(String mertid) {
-        String rst = "";
-        DecimalFormat formatter = new DecimalFormat("00000");
-        String index = formatter.format(ORDER_SEQ.incrementAndGet() % 9999 + 1);
-        rst = mertid + DateUtil.getAllTime()+ index;
-        return rst;
-    }
-
-    /**
-     * 获取新的用户唯一标识码
-     */
-    public static String getNewUserNo() {
-        return MD5.getMD5String(RandomUtils.getUUIDRandom());
-    }
 
     public static boolean validIP(String rule, String ip) {
         if ("1.1.1.1".equals(ip)) {
@@ -297,32 +255,9 @@ public class StringUtils {
         return str.replaceAll("\\t|\\s", "");
     }
 
-    /**
-     * 组织机构代码清理
-     */
-    public static String orgCodeFormat(String orgCode) {
-        if (Strings.isNullOrEmpty(orgCode)) {
-            return "";
-        }
-        orgCode = orgCode.replaceAll("[^\\da-zA-Z]", "");
-        return orgCode.length() == 9 ? orgCode : "";
-    }
 
 
 
-    public static String getResUrl(String url) {
-        return url.replaceAll("/v[0-9]+", "");
-    }
-
-    public static String getUrlVersion(String url) {
-        Matcher m = PATTERN_URL_VERSION.matcher(url);
-        if (m.find()) {
-            return m.group(1);
-        }
-
-        return null;
-    }
-
     public static String cutLeft(String str, int width) {
         if (str == null) {
             return "";
@@ -620,8 +555,34 @@ public class StringUtils {
         }
         return null == charset ? str.getBytes() : str.getBytes(charset);
     }
-
-
+    public static String getPingYin(String inputString) {
+        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
+        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
+        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
+        format.setVCharType(HanyuPinyinVCharType.WITH_V);
+        String output = "";
+        if (inputString != null && inputString.length() > 0
+                && !"null".equals(inputString)) {
+            char[] input = inputString.trim().toCharArray();
+            try {
+                for (int i = 0; i < input.length; i++) {
+                    if (java.lang.Character.toString(input[i]).matches(
+                            "[\\u4E00-\\u9FA5]+")) {
+                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(
+                                input[i], format);
+                        output += temp[0];
+                    } else {
+                        output += java.lang.Character.toString(input[i]);
+                    }
+                }
+            } catch (BadHanyuPinyinOutputFormatCombination e) {
+                e.printStackTrace();
+            }
+        } else {
+            return "*";
+        }
+        return output;
+    }
     /**
      * 切分字符串<br>
      * from jodd

+ 25 - 0
flash-waimai-manage/src/api/business/shop.js

@@ -60,6 +60,7 @@ export function getResturantsCount(params) {
     method: 'get'
   })
 }
+
 /**
  * 添加商铺
  */
@@ -110,6 +111,7 @@ export function getResturantDetail(id) {
     method: 'get'
   })
 }
+
 /**
  * 获取menu列表
  */
@@ -122,6 +124,7 @@ export function getMenu(params) {
     params
   })
 }
+
 /**
  * 获取menu详情
  */
@@ -134,3 +137,25 @@ export function getMenuById(category_id) {
   })
 }
 
+/**
+ * 获取当前店铺食品种类
+ */
+
+export function getCategory(restaurant_id) {
+  return request({
+    url: '/shopping/getcategory/' + restaurant_id,
+    method: 'get'
+  })
+}
+
+/**
+ * 添加食品种类
+ */
+
+export function addCategory(params) {
+  return request({
+    url: '/shopping/addcategory',
+    method: 'post',
+    params
+  })
+}

+ 4 - 2
flash-waimai-manage/src/permission.js

@@ -39,18 +39,20 @@ router.beforeEach((to, from, next) => {
           // next()
         }).catch((err) => {
           store.dispatch('FedLogOut').then(() => {
-            Message.error(err || 'Verification failed, please login again')
+            console.log('1111111'.err)
+            // Message.error(err || 'Verification failed, please login again')
             next({ path: '/' })
           })
         })
       } else {
         // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
         if (hasPermission(store.getters.roles, to.meta.roles)) {
+          console.log('next')
           next()
         } else {
+          console.log(401)
           next({ path: '/401', replace: true, query: { noGoBack: true }})
         }
-        // next()
       }
     }
   } else {

+ 28 - 12
flash-waimai-manage/src/views/business/food/add.js

@@ -1,5 +1,7 @@
 import { getApiUrl } from '@/utils/utils'
-import { getCategory, addCategory, addFood } from '@/api/business/food'
+import { getToken } from '@/utils/auth'
+import { addFood } from '@/api/business/food'
+import { getCategory, addCategory } from '@/api/business/shop'
 
 export default {
   data() {
@@ -11,6 +13,10 @@ export default {
         name: '',
         description: ''
       },
+      fileMgrUrl: getApiUrl() + '/file',
+      uploadHeaders: {
+        'Authorization': ''
+      },
       foodForm: {
         name: '',
         description: '',
@@ -51,6 +57,7 @@ export default {
     }
   },
   created() {
+    this.uploadHeaders['Authorization'] = getToken()
     if (this.$route.query.restaurant_id) {
       this.restaurant_id = this.$route.query.restaurant_id
     } else {
@@ -86,7 +93,7 @@ export default {
     async initData() {
       try {
         const result = await getCategory(this.restaurant_id)
-        if (result.status == 1) {
+        if (result.code === 20000) {
           result.category_list.map((item, index) => {
             item.value = index
             item.label = item.name
@@ -102,9 +109,11 @@ export default {
     addCategoryFun() {
       this.showAddCategory = !this.showAddCategory
     },
-    submitcategoryForm(categoryForm) {
-      this.$refs[categoryForm].validate(async(valid) => {
+    submitcategoryForm(formName) {
+      console.log(this.categoryForm)
+      this.$refs[formName].validate(async(valid) => {
         if (valid) {
+          console.log(2,this.categoryForm)
           const params = {
             name: this.categoryForm.name,
             description: this.categoryForm.description,
@@ -112,7 +121,7 @@ export default {
           }
           try {
             const result = await addCategory(params)
-            if (result.status == 1) {
+            if (result.code === 20000) {
               this.initData()
               this.categoryForm.name = ''
               this.categoryForm.description = ''
@@ -136,11 +145,8 @@ export default {
       })
     },
     uploadImg(res, file) {
-      if (res.status == 1) {
-        this.foodForm.image_path = res.image_path
-      } else {
-        this.$message.error('上传图片失败!')
-      }
+      this.foodForm.imagePath = getApiUrl() + '/file/getImgStream?fileName=' + res.data.realFileName
+      this.foodForm.image_path = res.data.realFileName
     },
     beforeImgUpload(file) {
       const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png')
@@ -181,8 +187,18 @@ export default {
             restaurant_id: this.restaurant_id
           }
           try {
-            const result = await addFood(params)
-            if (result.status == 1) {
+            const me = this
+            const result = await addFood({
+              name: me.foodForm.name,
+              descript: me.foodForm.description,
+              idShop: me.restaurant_id,
+              category_id: me.selectValue.id,
+              image_path: me.foodForm.image_path,
+              activity: me.foodForm.activity,
+              attributesJson:JSON.stringify(me.foodForm.attributes),
+              specsJson: JSON.stringify(me.foodForm.specs)
+            })
+            if (result.code === 20000) {
               console.log(result)
               this.$message({
                 type: 'success',

+ 3 - 2
flash-waimai-manage/src/views/business/food/add.vue

@@ -52,10 +52,11 @@
               <el-upload
                 class="avatar-uploader"
                 :action="fileMgrUrl"
+                :headers="uploadHeaders"
                 :show-file-list="false"
                 :on-success="uploadImg"
                 :before-upload="beforeImgUpload">
-                <img v-if="foodForm.image_path" :src="baseImgPath + foodForm.image_path" class="avatar">
+                <img v-if="foodForm.image_path" :src="foodForm.imagePath" class="avatar">
                 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
             </el-form-item>
@@ -114,7 +115,7 @@
               <el-button type="primary" @click="addFood('foodForm')">确认添加食品</el-button>
             </el-form-item>
           </el-form>
-          <el-dialog title="添加规格" v-model="dialogFormVisible">
+          <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
             <el-form :rules="specsFormrules" :model="specsForm">
               <el-form-item label="规格" label-width="100px" prop="specs">
                 <el-input v-model="specsForm.specs" auto-complete="off"></el-input>

+ 0 - 1
flash-waimai-manage/src/views/business/food/food.js

@@ -263,7 +263,6 @@ export default {
           message: err.message
         })
       })
-
     },
     fetchNext() {
       this.listQuery.page = this.listQuery.page + 1

+ 1 - 1
flash-waimai-manage/src/views/business/food/index.vue

@@ -32,7 +32,7 @@
                 <span>{{ props.row.rating }}</span>
               </el-form-item>
               <el-form-item label="食品分类">
-                <span>{{ props.row.category_name }}</span>
+                <span>{{ props.row.category_id }}</span>
               </el-form-item>
               <el-form-item label="月销量">
                 <span>{{ props.row.month_sales }}</span>

二进制
flash-waimai-manage/static/img/bg.jpg


+ 7 - 0
pom.xml

@@ -294,6 +294,11 @@
                 <artifactId>jxls-poi</artifactId>
                 <version>1.0.9</version>
             </dependency>
+            <dependency>
+                <groupId>com.belerweb</groupId>
+                <artifactId>pinyin4j</artifactId>
+                <version>2.5.1</version>
+            </dependency>
 
             <!-- message  start-->
             <dependency>
@@ -302,6 +307,8 @@
                 <version>1.0.6</version>
             </dependency>
             <!-- message end-->
+
+
         </dependencies>
 
     </dependencyManagement>