优化前项目提交

This commit is contained in:
zyx 2023-02-26 21:10:08 +08:00
commit cf208cb4b5
190 changed files with 37910 additions and 0 deletions

75
pom.xml Normal file
View File

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/>
</parent>
<groupId>cn.czyx007</groupId>
<artifactId>reggie_take_out</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,19 @@
package cn.czyx007.reggie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:04
*/
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement
public class ReggieApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieApplication.class);
}
}

View File

@ -0,0 +1,92 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 地址簿
*/
@Data
public class AddressBook implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//用户id
private Long userId;
//收货人
private String consignee;
//手机号
private String phone;
//性别 0 1
private String sex;
//省级区划编号
private String provinceCode;
//省级名称
private String provinceName;
//市级区划编号
private String cityCode;
//市级名称
private String cityName;
//区级区划编号
private String districtCode;
//区级名称
private String districtName;
//详细地址
private String detail;
//标签
private String label;
//是否默认 0 1是
private Integer isDefault;
//创建时间
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
//创建人
@TableField(fill = FieldFill.INSERT)
private Long createUser;
//修改人
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}

View File

@ -0,0 +1,59 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 分类
*/
@Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//类型 1 菜品分类 2 套餐分类
private Integer type;
//分类名称
private String name;
//顺序
private Integer sort;
//创建时间
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
//创建人
@TableField(fill = FieldFill.INSERT)
private Long createUser;
//修改人
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
//private Integer isDeleted;
}

View File

@ -0,0 +1,74 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
菜品
*/
@Data
public class Dish implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//菜品名称
private String name;
//菜品分类id
private Long categoryId;
//菜品价格
private BigDecimal price;
//商品码
private String code;
//图片
private String image;
//描述信息
private String description;
//0 停售 1 起售
private Integer status;
//顺序
private Integer sort;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}

View File

@ -0,0 +1,53 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
菜品口味
*/
@Data
public class DishFlavor implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//菜品id
private Long dishId;
//口味名称
private String name;
//口味数据list
private String value;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}

View File

@ -0,0 +1,45 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:20
*/
@Data
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String sex;
private String idNumber;
private Integer status;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}

View File

@ -0,0 +1,46 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 订单明细
*/
@Data
public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//名称
private String name;
//订单id
private Long orderId;
//菜品id
private Long dishId;
//套餐id
private Long setmealId;
//口味
private String dishFlavor;
//数量
private Integer number;
//金额
private BigDecimal amount;
//图片
private String image;
}

View File

@ -0,0 +1,64 @@
package cn.czyx007.reggie.bean;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 订单
*/
@Data
public class Orders implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//订单号
private String number;
//订单状态 1待付款2待派送3已派送4已完成5已取消
private Integer status;
//下单用户id
private Long userId;
//地址id
private Long addressBookId;
//下单时间
private LocalDateTime orderTime;
//结账时间
private LocalDateTime checkoutTime;
//支付方式 1微信2支付宝
private Integer payMethod;
//实收金额
private BigDecimal amount;
//备注
private String remark;
//用户名
private String userName;
//手机号
private String phone;
//地址
private String address;
//收货人
private String consignee;
}

View File

@ -0,0 +1,69 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 套餐
*/
@Data
public class Setmeal implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//分类id
private Long categoryId;
//套餐名称
private String name;
//套餐价格
private BigDecimal price;
//状态 0:停用 1:启用
private Integer status;
//编码
private String code;
//描述信息
private String description;
//图片
private String image;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}

View File

@ -0,0 +1,61 @@
package cn.czyx007.reggie.bean;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 套餐菜品关系
*/
@Data
public class SetmealDish implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//套餐id
private Long setmealId;
//菜品id
private Long dishId;
//菜品名称 冗余字段
private String name;
//菜品原价
private BigDecimal price;
//份数
private Integer copies;
//排序
private Integer sort;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}

View File

@ -0,0 +1,43 @@
package cn.czyx007.reggie.bean;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 购物车
*/
@Data
public class ShoppingCart implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//名称
private String name;
//用户id
private Long userId;
//菜品id
private Long dishId;
//套餐id
private Long setmealId;
//口味
private String dishFlavor;
//数量
private Integer number;
//金额
private BigDecimal amount;
//图片
private String image;
private LocalDateTime createTime;
}

View File

@ -0,0 +1,43 @@
package cn.czyx007.reggie.bean;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
/**
* 用户信息
*/
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//姓名
private String name;
//手机号
private String phone;
//性别 0 1
private String sex;
//身份证号
private String idNumber;
//头像
private String avatar;
//状态 0:禁用1:正常
private Integer status;
}

View File

@ -0,0 +1,19 @@
package cn.czyx007.reggie.common;
/**
* @author : 张宇轩
* @createTime : 2022/12/21 - 18:19
*/
public class BaseContext {
private BaseContext(){}
private static ThreadLocal<Long> local = new ThreadLocal<>();
public static void setCurrentId(Long id){
local.set(id);
}
public static Long getCurrentId(){
return local.get();
}
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.common;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 12:01
*/
public class CustomException extends RuntimeException{
public CustomException(String message) {
super(message);
}
}

View File

@ -0,0 +1,36 @@
package cn.czyx007.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* @author : 张宇轩
* @createTime : 2022/12/20 - 18:32
*/
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
log.error(e.getMessage());
if(e.getMessage().contains("Duplicate entry")){
return R.error(e.getMessage().split(" ")[2] + "已存在");
}
return R.error("未知错误");
}
@ExceptionHandler(CustomException.class)
public R<String> exceptionHandler(CustomException e){
log.error(e.getMessage());
return R.error(e.getMessage());
}
}

View File

@ -0,0 +1,54 @@
package cn.czyx007.reggie.common;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/**
* 对象映射器:基于jackson将Java对象转为json或者将json转为Java对象
* 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
* 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
*/
public class JacksonObjectMapper extends ObjectMapper {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public JacksonObjectMapper() {
super();
//收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(BigInteger.class, ToStringSerializer.instance)
.addSerializer(Long.class, ToStringSerializer.instance)
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//注册功能模块 例如可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
}

View File

@ -0,0 +1,38 @@
package cn.czyx007.reggie.common;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 元数据对象处理器
* @author : 张宇轩
* @createTime : 2022/12/21 - 16:03
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作时自动填充
* @param metaObject 元对象
*/
@Override
public void insertFill(MetaObject metaObject) {
LocalDateTime now = LocalDateTime.now();
metaObject.setValue("createTime", now);
metaObject.setValue("updateTime", now);
metaObject.setValue("createUser", BaseContext.getCurrentId());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
/**
* 更新操作时自动填充
* @param metaObject 元对象
*/
@Override
public void updateFill(MetaObject metaObject) {
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
}

View File

@ -0,0 +1,40 @@
package cn.czyx007.reggie.common;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:32
*/
@Data
public class R<T> {
private Integer code; //状态码1成功0和其它数字为失败
private String msg; //错误信息
private T data; //数据
private Map map = new HashMap(); //动态数据
public static <T> R<T> success(T object) {
R<T> r = new R<T>();
r.data = object;
r.code = 1;
return r;
}
public static <T> R<T> error(String msg) {
R r = new R();
r.msg = msg;
r.code = 0;
return r;
}
public R<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}

View File

@ -0,0 +1,20 @@
package cn.czyx007.reggie.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : 张宇轩
* @createTime : 2022/12/20 - 19:09
*/
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}

View File

@ -0,0 +1,41 @@
package cn.czyx007.reggie.config;
import cn.czyx007.reggie.common.JacksonObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2022/12/20 - 19:54
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 设置静态资源映射
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/static/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/static/front/");
}
/**
* 扩展mvc框架的消息转换器
* @param converters the list of configured converters to extend
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建消息转换器
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
//设置对象转换器
messageConverter.setObjectMapper(new JacksonObjectMapper());
//将对象转换器追加到mvc框架的转换器集合中
converters.add(0, messageConverter);
}
}

View File

@ -0,0 +1,86 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.AddressBook;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.service.AddressBookService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 17:57
*/
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
@Autowired
private AddressBookService addressBookService;
@GetMapping("/list")
public R<List<AddressBook>> list(AddressBook addressBook){
addressBook.setUserId(BaseContext.getCurrentId());
LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
lqw.eq(addressBook.getUserId() != null, AddressBook::getUserId, addressBook.getUserId());
lqw.orderByDesc(AddressBook::getUpdateTime);
return R.success(addressBookService.list(lqw));
}
@PostMapping
public R<AddressBook> save(@RequestBody AddressBook addressBook){
addressBook.setUserId(BaseContext.getCurrentId());
addressBookService.save(addressBook);
return R.success(addressBook);
}
@PutMapping
public R<AddressBook> update(@RequestBody AddressBook addressBook){
addressBookService.updateById(addressBook);
return R.success(addressBook);
}
@PutMapping("/default")
public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
luw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
luw.set(AddressBook::getIsDefault, 0);
addressBookService.update(luw);
addressBook.setIsDefault(1);
addressBookService.updateById(addressBook);
return R.success(addressBook);
}
@GetMapping("/{id}")
public R<AddressBook> get(@PathVariable long id){
AddressBook addressBook = addressBookService.getById(id);
if (addressBook != null) {
return R.success(addressBook);
}
return R.error("没有找到该用户");
}
@GetMapping("/default")
public R<AddressBook> getDefault(){
LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
lqw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
lqw.eq(AddressBook::getIsDefault, 1);
AddressBook addressBook = addressBookService.getOne(lqw);
if (addressBook == null) {
return R.error("没有找到该用户");
}
return R.success(addressBook);
}
@DeleteMapping
public R<String> delete(@RequestParam("ids") long ids){
addressBookService.removeById(ids);
return R.success("地址删除成功");
}
}

View File

@ -0,0 +1,70 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.Category;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 10:50
*/
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增菜品/套餐分类
* @param category
* @return
*/
@PostMapping
public R<String> save(@RequestBody Category category){
categoryService.save(category);
return R.success("新增分类成功");
}
@GetMapping("/page")
public R<Page<Category>> getPage(long page, long pageSize){
LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
lqw.orderByAsc(Category::getSort);
return R.success(categoryService.page(new Page<>(page, pageSize), lqw));
}
@DeleteMapping
public R<String> delete(long ids){
categoryService.remove(ids);
return R.success("分类信息删除成功");
}
/**
* 根据id修改分类信息
* @param category
* @return
*/
@PutMapping
public R<String> update(@RequestBody Category category){
categoryService.updateById(category);
return R.success("修改分类信息成功");
}
/**
* 根据条件查询分类数据
* @param category
* @return
*/
@GetMapping("/list")
public R<List<Category>> list(Category category){
LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
lqw.eq(category.getType() != null, Category::getType, category.getType());
lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
return R.success(categoryService.list(lqw));
}
}

View File

@ -0,0 +1,81 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 12:59
*/
@RestController
@RequestMapping("/common")
public class CommonController {
@Value("${reggie.path}")
private String basePath;
/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
//使用UUID重新生成文件名
String originalFilename = file.getOriginalFilename();
String newFilename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//判断目录是否存在若不存在则创建
File dir = new File(basePath);
if (!dir.exists()) {
dir.mkdirs();
}
try {
file.transferTo(new File(basePath + newFilename));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(newFilename);
}
/**
* 文件下载
* @param name
* @param response
*/
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try {
FileInputStream fis = new FileInputStream(basePath + name);
ServletOutputStream os = response.getOutputStream();
response.setContentType("image/jpeg");
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1){
os.write(buffer, 0, len);
os.flush();
}
fis.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,146 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.Category;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.bean.DishFlavor;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.common.CustomException;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.dto.DishDto;
import cn.czyx007.reggie.service.CategoryService;
import cn.czyx007.reggie.service.DishFlavorService;
import cn.czyx007.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 13:49
*/
@RestController
@RequestMapping("/dish")
public class DishController {
@Autowired
private DishService dishService;
@Autowired
private DishFlavorService dishFlavorService;
@Autowired
private CategoryService categoryService;
/**
* 新增菜品
* @param dishDto
* @return
*/
@PostMapping
public R<String> save(@RequestBody DishDto dishDto){
dishService.saveWithFlavor(dishDto);
return R.success("新增菜品成功");
}
@GetMapping("/page")
public R<Page<DishDto>> page(int page, int pageSize, String name){
LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
lqw.like(StringUtils.hasLength(name), Dish::getName, name);
lqw.orderByDesc(Dish::getUpdateTime);
Page<Dish> pageInfo = dishService.page(new Page<>(page, pageSize), lqw);
Page<DishDto> dishDtoPage = new Page<>();
BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
List<Dish> records = pageInfo.getRecords();
List<DishDto> list = records.stream().map((item) -> {
DishDto dishDto = new DishDto();
BeanUtils.copyProperties(item, dishDto);
Category category = categoryService.getById(item.getCategoryId());
if(category != null){
dishDto.setCategoryName(category.getName());
}
return dishDto;
}).collect(Collectors.toList());
dishDtoPage.setRecords(list);
return R.success(dishDtoPage);
}
/**
* 根据id查询菜品信息和对应的口味信息
* @param id
* @return
*/
@GetMapping("/{id}")
public R<DishDto> get(@PathVariable long id){
return R.success(dishService.getByIdWithFlavor(id));
}
@PutMapping
public R<String> update(@RequestBody DishDto dishDto){
dishService.updateWithFlavor(dishDto);
return R.success("修改菜品成功");
}
/**
* 更新菜品起售停售状态
* @param status
* @param ids
* @return
*/
@PostMapping("/status/{status}")
public R<String> updateStatus(@PathVariable int status, @RequestParam("ids") List<Long> ids){
ids.forEach((id) -> {
Dish dish = dishService.getById(id);
dish.setStatus(status);
dishService.updateById(dish);
});
return R.success("菜品状态已经更改成功!");
}
/**
* 删除菜品
* @param ids
* @return
*/
@Transactional
@DeleteMapping
public R<String> delete(@RequestParam("ids") List<Long> ids){
LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
qw.in(Dish::getId, ids);
qw.eq(Dish::getStatus, 1);
if (dishService.count(qw)>0) {
throw new CustomException("菜品正在售卖中,不能删除");
}
dishService.removeByIds(ids);
LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
lqw.in(DishFlavor::getDishId, ids);
dishFlavorService.remove(lqw);
return R.success("删除成功!");
}
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish){
LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
lqw.eq(Dish::getStatus, 1);
lqw.like(StringUtils.hasLength(dish.getName()), Dish::getName, dish.getName());
lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
List<Dish> dishes = dishService.list(lqw);
List<DishDto> dtoList = dishes.stream().map((item) ->
dishService.getByIdWithFlavor(item.getId())
).collect(Collectors.toList());
return R.success(dtoList);
}
}

View File

@ -0,0 +1,136 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.Employee;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:26
*/
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
/**
* 员工登录
* @param request
* @param employee
* @return
*/
@PostMapping("/login")
public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Employee::getUsername, employee.getUsername());
Employee emp = employeeService.getOne(queryWrapper);
if (emp == null) {
return R.error("登陆失败");
}
if (!emp.getPassword().equals(password)) {
return R.error("登陆失败");
}
if(emp.getStatus() == 0){
return R.error("账号已禁用");
}
//登录成功将员工id存入session并返回登录成功结果
request.getSession().setAttribute("employee", emp.getId());
emp.setPassword(null);
return R.success(emp);
}
/**
* 员工退出
* @param request
* @return
*/
@PostMapping("/logout")
public R<String> logout(HttpServletRequest request){
request.getSession().removeAttribute("employee");
return R.success("退出成功");
}
@PostMapping
public R<String> save(HttpServletRequest request, @RequestBody Employee employee){
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
// LocalDateTime now = LocalDateTime.now();
// employee.setCreateTime(now);
// employee.setUpdateTime(now);
// Long empId = (Long) request.getSession().getAttribute("employee");
// employee.setCreateUser(empId);
// employee.setUpdateUser(empId);
employeeService.save(employee);
return R.success("新增员工成功");
}
/**
* 员工信息分页查询
* @return
*/
@GetMapping("/page")
public R<Page<Employee>> page(long page, long pageSize, String name){
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.hasLength(name), Employee::getName, name);
Page<Employee> employeePage = employeeService.page(new Page<>(page, pageSize), queryWrapper);
for (Employee employee : employeePage.getRecords()) {
employee.setPassword(null);
}
return R.success(employeePage);
}
/**
* 根据id修改员工信息
* @param employee
* @return
*/
@PutMapping
public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
// Long empId = (Long) request.getSession().getAttribute("employee");
// employee.setUpdateUser(empId);
// employee.setUpdateTime(LocalDateTime.now());
employeeService.updateById(employee);
return R.success("员工信息修改成功");
}
/**
* 根据id查询员工信息
* @param id
* @return
*/
@GetMapping("/{id}")
public R<Employee> getById(@PathVariable long id) {
Employee employee = employeeService.getById(id);
if (employee != null) {
return R.success(employee);
}
return R.error("没有查询到对应员工信息");
}
}

View File

@ -0,0 +1,17 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.service.OrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:49
*/
@RestController
@RequestMapping("/orderDetail")
public class OrderDetailController {
@Autowired
private OrderDetailService orderDetailService;
}

View File

@ -0,0 +1,100 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.OrderDetail;
import cn.czyx007.reggie.bean.Orders;
import cn.czyx007.reggie.bean.ShoppingCart;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.dto.OrdersDto;
import cn.czyx007.reggie.service.OrderDetailService;
import cn.czyx007.reggie.service.OrdersService;
import cn.czyx007.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:49
*/
@RestController
@RequestMapping("/order")
public class OrdersController {
@Autowired
private OrdersService ordersService;
@Autowired
private OrderDetailService orderDetailService;
@Autowired
private ShoppingCartService shoppingCartService;
@PostMapping("/submit")
public R<String> submit(@RequestBody Orders orders){
ordersService.submit(orders);
return R.success("下单成功");
}
@GetMapping(value = "/page")
public R<Page<OrdersDto>> backendPageAllCondition(@RequestParam("page") Long page, @RequestParam("pageSize")Long pageSize,
@RequestParam(value = "number", required = false) Long number,
@RequestParam(value = "beginTime", required = false) LocalDateTime beginTime,
@RequestParam(value = "endTime", required = false) LocalDateTime endTime){
LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
lqw.eq(number != null, Orders::getNumber, number);
lqw.ge(beginTime != null, Orders::getOrderTime, beginTime);
lqw.le(endTime != null, Orders::getOrderTime, endTime);
lqw.orderByDesc(Orders::getOrderTime);
return R.success(ordersService.getPage(page, pageSize, lqw));
}
// @GetMapping(value = "/page", params = "!number")
// public R<Page<OrdersDto>> backendPageWithTime(@RequestParam("page") Long page, @RequestParam("pageSize")Long pageSize,
// @RequestParam(value = "beginTime", required = false) LocalDateTime beginTime,
// @RequestParam(value = "endTime", required = false) LocalDateTime endTime){
// LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
// lqw.ge(beginTime != null, Orders::getOrderTime, beginTime);
// lqw.le(endTime != null, Orders::getOrderTime, endTime);
// lqw.orderByDesc(Orders::getOrderTime);
//
// return R.success(ordersService.getPage(page, pageSize, lqw));
// }
@GetMapping("/userPage")
public R<Page<OrdersDto>> frontendPage(long page, long pageSize){
LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
lqw.orderByDesc(Orders::getOrderTime);
return R.success(ordersService.getPage(page, pageSize, lqw));
}
@PostMapping("/again")
public R<String> again(@RequestBody Map<String,Long> map){
shoppingCartService.clean();
Long id = map.get("id");
LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
lqw.eq(OrderDetail::getOrderId, id);
List<OrderDetail> details = orderDetailService.list(lqw);
Long userId = BaseContext.getCurrentId();
List<ShoppingCart> list = details.stream().map((item) -> {
ShoppingCart cart = new ShoppingCart();
BeanUtils.copyProperties(item, cart);
cart.setUserId(userId);
cart.setCreateTime(LocalDateTime.now());
return cart;
}).collect(Collectors.toList());
shoppingCartService.saveBatch(list);
return R.success("喜欢吃就再来一单!");
}
}

View File

@ -0,0 +1,141 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.Category;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.bean.SetmealDish;
import cn.czyx007.reggie.common.CustomException;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.dto.DishDto;
import cn.czyx007.reggie.dto.SetmealDto;
import cn.czyx007.reggie.service.CategoryService;
import cn.czyx007.reggie.service.DishService;
import cn.czyx007.reggie.service.SetmealDishService;
import cn.czyx007.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 11:51
*/
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
@Autowired
private CategoryService categoryService;
@Autowired
private SetmealService setmealService;
@Autowired
private DishService dishService;
@Autowired
private SetmealDishService setmealDishService;
@PostMapping
public R<String> save(@RequestBody SetmealDto setmealDto){
setmealService.saveWithDish(setmealDto);
return R.success("新增套餐成功");
}
@GetMapping("/list")
public R<List<Setmeal>> list(Setmeal setmeal){
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
List<Setmeal> list = setmealService.list(queryWrapper);
return R.success(list);
}
@GetMapping("/page")
public R<Page<SetmealDto>> page(long page, long pageSize, String name){
LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
lqw.like(StringUtils.hasLength(name), Setmeal::getName, name);
lqw.orderByDesc(Setmeal::getUpdateTime);
Page<Setmeal> pageInfo = setmealService.page(new Page<>(page, pageSize), lqw);
Page<SetmealDto> dtoPage = new Page<>();
BeanUtils.copyProperties(pageInfo, dtoPage, "records");
List<Setmeal> records = pageInfo.getRecords();
List<SetmealDto> list = records.stream().map((item) -> {
SetmealDto setmealDto = new SetmealDto();
BeanUtils.copyProperties(item, setmealDto);
Category category = categoryService.getById(item.getCategoryId());
if(category != null){
setmealDto.setCategoryName(category.getName());
}
return setmealDto;
}).collect(Collectors.toList());
dtoPage.setRecords(list);
return R.success(dtoPage);
}
@GetMapping("/{id}")
public R<SetmealDto> get(@PathVariable long id){
return R.success(setmealService.getByIdWithDishes(id));
}
@PutMapping
public R<String> update(@RequestBody SetmealDto setmealDto){
setmealService.updateWithDishes(setmealDto);
return R.success("修改套餐成功");
}
@PostMapping("/status/{status}")
public R<String> updateStatus(@PathVariable int status, @RequestParam("ids") List<Long> ids){
ids.forEach((id) -> {
Setmeal setmeal = setmealService.getById(id);
setmeal.setStatus(status);
setmealService.updateById(setmeal);
});
return R.success("套餐状态已经更改成功!");
}
@Transactional
@DeleteMapping
public R<String> delete(@RequestParam("ids") List<Long> ids){
LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
qw.in(Setmeal::getId, ids);
qw.eq(Setmeal::getStatus, 1);
if (setmealService.count(qw)>0) {
throw new CustomException("套餐正在售卖中,不能删除");
}
setmealService.removeByIds(ids);
LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
lqw.in(SetmealDish::getSetmealId, ids);
setmealDishService.remove(lqw);
return R.success("套餐删除成功");
}
@GetMapping("/dish/{id}")
public R<List<DishDto>> showImageDetail(@PathVariable long id){
LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
lqw.eq(SetmealDish::getSetmealId, id);
List<SetmealDish> records = setmealDishService.list(lqw);
List<DishDto> list = records.stream().map((item) -> {
DishDto dishDto = new DishDto();
BeanUtils.copyProperties(item, dishDto);
Long dishId = item.getDishId();
Dish dish = dishService.getById(dishId);
BeanUtils.copyProperties(dish, dishDto);
return dishDto;
}).collect(Collectors.toList());
return R.success(list);
}
}

View File

@ -0,0 +1,98 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.ShoppingCart;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.CustomException;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 19:23
*/
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
@Autowired
private ShoppingCartService shoppingCartService;
@GetMapping("/list")
public R<List<ShoppingCart>> list(){
LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
lqw.orderByDesc(ShoppingCart::getCreateTime);
return R.success(shoppingCartService.list(lqw));
}
@PostMapping("/add")
public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
shoppingCart.setUserId(BaseContext.getCurrentId());
LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
lqw.eq(ShoppingCart::getUserId, shoppingCart.getUserId());
if (shoppingCart.getDishId() != null){
//菜品
lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
} else {
//套餐
lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
}
ShoppingCart cartServiceOne = shoppingCartService.getOne(lqw);
if (cartServiceOne != null) {//已存在重复的数量+1
cartServiceOne.setNumber(cartServiceOne.getNumber()+1);
shoppingCartService.updateById(cartServiceOne);
} else {
shoppingCart.setNumber(1);
shoppingCart.setCreateTime(LocalDateTime.now());
shoppingCartService.save(shoppingCart);
cartServiceOne = shoppingCart;
}
return R.success(cartServiceOne);
}
@PostMapping("/sub")
public R<String> sub(@RequestBody ShoppingCart shoppingCart){
shoppingCart.setUserId(BaseContext.getCurrentId());
LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
lqw.eq(ShoppingCart::getUserId, shoppingCart.getUserId());
if (shoppingCart.getDishId() != null){
//菜品
lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
} else {
//套餐
lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
}
ShoppingCart cartServiceOne = shoppingCartService.getOne(lqw);
if(cartServiceOne == null){
throw new CustomException("未知错误");
}
if(cartServiceOne.getNumber() > 1){
cartServiceOne.setNumber(cartServiceOne.getNumber()-1);
shoppingCartService.updateById(cartServiceOne);
} else {
shoppingCartService.removeById(cartServiceOne);
}
return R.success("购物车减少成功");
}
@DeleteMapping("/clean")
public R<String> clean(){
shoppingCartService.clean();
return R.success("购物车清空成功");
}
}

View File

@ -0,0 +1,85 @@
package cn.czyx007.reggie.controller;
import cn.czyx007.reggie.bean.User;
import cn.czyx007.reggie.common.R;
import cn.czyx007.reggie.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 16:00
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 发送验证码
* @param user
* @return
*/
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
//获取手机号/邮箱
String phone = user.getPhone();
if (StringUtils.hasLength(phone)) {
//生成随机的4位验证码
//String code = ValidateCodeUtils.generateValidateCode4String(4);
//发送邮件验证码
//SendEmailUtils.sendAuthCodeEmail(phone, code);
//将生成的验证码保存到session用于校验
// session.setAttribute(phone, code);
session.setAttribute(phone, "1234");
return R.success("验证码发送成功");
}
return R.error("验证码发送失败");
}
@PostMapping("/login")
public R<User> login(@RequestBody Map<String, String> map, HttpSession session){
//获取手机号
String phone = map.get("phone");
//获取验证码
String code = map.get("code");
//从session中获取保存的验证码
String codeInSession = (String) session.getAttribute(phone);
codeInSession = "1234";
//将两个验证码进行比对
if(StringUtils.hasLength(codeInSession) && codeInSession.equals(code)){
//若比对成功则登录成功
//若数据库中无对应的手机号/邮箱则进行注册
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
lqw.eq(User::getPhone, phone);
User user = userService.getOne(lqw);
if (user == null) {
user = new User();
user.setPhone(phone);
user.setStatus(1);
userService.save(user);
}
session.setAttribute("user", user.getId());
return R.success(user);
}
return R.error("登录失败");
}
@PostMapping("/loginout")
public R<String> logout(HttpSession session){
session.removeAttribute("user");
return R.success("退出成功");
}
}

View File

@ -0,0 +1,17 @@
package cn.czyx007.reggie.dto;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.bean.DishFlavor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class DishDto extends Dish {
private List<DishFlavor> flavors = new ArrayList<>();
private String categoryName;
private Integer copies;
}

View File

@ -0,0 +1,16 @@
package cn.czyx007.reggie.dto;
import cn.czyx007.reggie.bean.OrderDetail;
import cn.czyx007.reggie.bean.Orders;
import lombok.Data;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 22:33
*/
@Data
public class OrdersDto extends Orders {
private List<OrderDetail> orderDetails;
}

View File

@ -0,0 +1,14 @@
package cn.czyx007.reggie.dto;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.bean.SetmealDish;
import lombok.Data;
import java.util.List;
@Data
public class SetmealDto extends Setmeal {
private List<SetmealDish> setmealDishes;
private String categoryName;
}

View File

@ -0,0 +1,64 @@
package cn.czyx007.reggie.filter;
import cn.czyx007.reggie.bean.Employee;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 检查用户是否完成登录
* @author : 张宇轩
* @createTime : 2022/12/20 - 17:38
*/
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
public static final String[] urls = {"/employee/login", "/employee/logout", "/backend/**", "/front/**",
"/user/sendMsg", "/user/login"};
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestURI = request.getRequestURI();
boolean check = false;
for (String url : urls) {
if(PATH_MATCHER.match(url, requestURI)){
check = true;
break;
}
}
if (check) {
chain.doFilter(request, response);
return;
}
if (request.getSession().getAttribute("employee") != null) {
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
chain.doFilter(request, response);
return;
}
if (request.getSession().getAttribute("user") != null) {
Long userId = (Long) request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
chain.doFilter(request, response);
return;
}
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
}
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.AddressBook;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 17:56
*/
@Mapper
public interface AddressBookMapper extends BaseMapper<AddressBook> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.Category;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 10:48
*/
@Mapper
public interface CategoryMapper extends BaseMapper<Category> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.DishFlavor;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 13:48
*/
@Mapper
public interface DishFlavorMapper extends BaseMapper<DishFlavor> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.Dish;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:49
*/
@Mapper
public interface DishMapper extends BaseMapper<Dish> {
}

View File

@ -0,0 +1,14 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.Employee;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:25
*/
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.OrderDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:46
*/
@Mapper
public interface OrderDetailMapper extends BaseMapper<OrderDetail> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.Orders;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:46
*/
@Mapper
public interface OrdersMapper extends BaseMapper<Orders> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.SetmealDish;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 11:49
*/
@Mapper
public interface SetmealDishMapper extends BaseMapper<SetmealDish> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.Setmeal;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:49
*/
@Mapper
public interface SetmealMapper extends BaseMapper<Setmeal> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.ShoppingCart;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 20:35
*/
@Mapper
public interface ShoppingCartMapper extends BaseMapper<ShoppingCart> {
}

View File

@ -0,0 +1,13 @@
package cn.czyx007.reggie.mapper;
import cn.czyx007.reggie.bean.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 15:29
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.AddressBook;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 17:57
*/
public interface AddressBookService extends IService<AddressBook> {
}

View File

@ -0,0 +1,12 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.Category;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 10:49
*/
public interface CategoryService extends IService<Category> {
void remove(long id);
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.DishFlavor;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 13:48
*/
public interface DishFlavorService extends IService<DishFlavor> {
}

View File

@ -0,0 +1,18 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.dto.DishDto;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:50
*/
public interface DishService extends IService<Dish> {
//新增菜品同时插入对应的口味数据
void saveWithFlavor(DishDto dishDto);
//根据id查询菜品信息和口味信息
DishDto getByIdWithFlavor(long id);
//更新菜品信息同时更新口味信息
void updateWithFlavor(DishDto dishDto);
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.Employee;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:25
*/
public interface EmployeeService extends IService<Employee> {
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.OrderDetail;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:47
*/
public interface OrderDetailService extends IService<OrderDetail> {
}

View File

@ -0,0 +1,23 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.Orders;
import cn.czyx007.reggie.dto.OrdersDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:47
*/
public interface OrdersService extends IService<Orders> {
/**
* 用户下单
* @param orders
*/
void submit(Orders orders);
Page<OrdersDto> getPage(long page, long pageSize, LambdaQueryWrapper<Orders> lqw);
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.SetmealDish;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 11:49
*/
public interface SetmealDishService extends IService<SetmealDish> {
}

View File

@ -0,0 +1,21 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.dto.SetmealDto;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:50
*/
public interface SetmealService extends IService<Setmeal> {
/**
* 新增套餐同时保存套餐和菜品的关联关系
* @param setmealDto
*/
void saveWithDish(SetmealDto setmealDto);
SetmealDto getByIdWithDishes(long id);
void updateWithDishes(SetmealDto setmealDto);
}

View File

@ -0,0 +1,12 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.ShoppingCart;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 20:36
*/
public interface ShoppingCartService extends IService<ShoppingCart> {
void clean();
}

View File

@ -0,0 +1,11 @@
package cn.czyx007.reggie.service;
import cn.czyx007.reggie.bean.User;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 15:30
*/
public interface UserService extends IService<User> {
}

View File

@ -0,0 +1,15 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.AddressBook;
import cn.czyx007.reggie.mapper.AddressBookMapper;
import cn.czyx007.reggie.service.AddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 17:57
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
}

View File

@ -0,0 +1,50 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.Category;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.common.CustomException;
import cn.czyx007.reggie.mapper.CategoryMapper;
import cn.czyx007.reggie.service.CategoryService;
import cn.czyx007.reggie.service.DishService;
import cn.czyx007.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 10:49
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
@Autowired
private DishService dishService;
@Autowired
private SetmealService setmealService;
/**
* 根据id删除分类需要先判断是否关联了菜品或套餐
* @param id
*/
@Override
public void remove(long id) {
//查询是否关联菜品若关联则抛出业务异常
LambdaQueryWrapper<Dish> dish = new LambdaQueryWrapper<>();
dish.eq(Dish::getCategoryId, id);
if (dishService.count(dish) > 0) {
//已关联菜品抛出业务异常
throw new CustomException("当前分类已关联菜品,不能删除");
}
//查询是否关联套餐若关联则抛出业务异常
LambdaQueryWrapper<Setmeal> setmeal = new LambdaQueryWrapper<>();
setmeal.eq(Setmeal::getCategoryId, id);
if (setmealService.count(setmeal) > 0) {
//已关联套餐抛出业务异常
throw new CustomException("当前分类已关联套餐,不能删除");
}
//删除分类
super.removeById(id);
}
}

View File

@ -0,0 +1,15 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.DishFlavor;
import cn.czyx007.reggie.mapper.DishFlavorMapper;
import cn.czyx007.reggie.service.DishFlavorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 13:48
*/
@Service
public class DishFlavorServiceImpl extends ServiceImpl<DishFlavorMapper, DishFlavor> implements DishFlavorService {
}

View File

@ -0,0 +1,79 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.Dish;
import cn.czyx007.reggie.bean.DishFlavor;
import cn.czyx007.reggie.dto.DishDto;
import cn.czyx007.reggie.mapper.DishMapper;
import cn.czyx007.reggie.service.DishFlavorService;
import cn.czyx007.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:51
*/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
@Autowired
private DishFlavorService dishFlavorService;
@Override
@Transactional
public void saveWithFlavor(DishDto dishDto) {
//保存菜品基本信息
this.save(dishDto);
Long dishId = dishDto.getId();
List<DishFlavor> flavors = dishDto.getFlavors();
flavors.stream().map((item) -> {
item.setDishId(dishId);
return item;
}).collect(Collectors.toList());
//保存菜品口味
dishFlavorService.saveBatch(flavors);
}
@Override
public DishDto getByIdWithFlavor(long id) {
//查询菜品基本信息
Dish dish = this.getById(id);
DishDto dishDto = new DishDto();
BeanUtils.copyProperties(dish, dishDto);
//查询菜品口味信息
LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
lqw.eq(DishFlavor::getDishId, dish.getId());
List<DishFlavor> flavors = dishFlavorService.list(lqw);
dishDto.setFlavors(flavors);
return dishDto;
}
@Override
public void updateWithFlavor(DishDto dishDto) {
//更新菜品基本信息
this.updateById(dishDto);
//清理当前菜品的口味信息后重新添加
LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
lqw.eq(DishFlavor::getDishId, dishDto.getId());
dishFlavorService.remove(lqw);
List<DishFlavor> flavors = dishDto.getFlavors();
flavors = flavors.stream().map((item) -> {
item.setDishId(dishDto.getId());
return item;
}).collect(Collectors.toList());
dishFlavorService.saveBatch(flavors);
}
}

View File

@ -0,0 +1,17 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.Employee;
import cn.czyx007.reggie.mapper.EmployeeMapper;
import cn.czyx007.reggie.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2022/12/19 - 23:26
*/
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
}

View File

@ -0,0 +1,15 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.OrderDetail;
import cn.czyx007.reggie.mapper.OrderDetailMapper;
import cn.czyx007.reggie.service.OrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:48
*/
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements OrderDetailService {
}

View File

@ -0,0 +1,121 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.*;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.common.CustomException;
import cn.czyx007.reggie.dto.OrdersDto;
import cn.czyx007.reggie.mapper.OrdersMapper;
import cn.czyx007.reggie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 21:48
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
@Autowired
private ShoppingCartService shoppingCartService;
@Autowired
private UserService userService;
@Autowired
private AddressBookService addressBookService;
@Autowired
private OrderDetailService orderDetailService;
@Override
@Transactional
public void submit(Orders orders) {
//获取当前用户id
Long userId = BaseContext.getCurrentId();
//查询当前用户的购物车数据
LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
lqw.eq(ShoppingCart::getUserId, userId);
List<ShoppingCart> carts = shoppingCartService.list(lqw);
if (carts == null || carts.size() == 0) {
throw new CustomException("购物车为空,不能下单");
}
//查询用户数据
User user = userService.getById(userId);
//查询地址数据
AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
if (addressBook == null) {
throw new CustomException("用户地址信息有误,不能下单");
}
//生成订单号
long orderId = IdWorker.getId();
//计算金额
AtomicInteger amount = new AtomicInteger(0);
List<OrderDetail> orderDetails = carts.stream().map((item) -> {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setOrderId(orderId);
orderDetail.setNumber(item.getNumber());
orderDetail.setDishFlavor(item.getDishFlavor());
orderDetail.setDishId(item.getDishId());
orderDetail.setSetmealId(item.getSetmealId());
orderDetail.setName(item.getName());
orderDetail.setImage(item.getImage());
orderDetail.setAmount(item.getAmount());
amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
return orderDetail;
}).collect(Collectors.toList());
//向订单表插入数据一条数据
orders.setId(orderId);
orders.setOrderTime(LocalDateTime.now());
orders.setCheckoutTime(LocalDateTime.now());
orders.setStatus(2);
orders.setAmount(new BigDecimal(amount.get()));//总金额
orders.setUserId(userId);
orders.setNumber(String.valueOf(orderId));
orders.setUserName(user.getName());
orders.setConsignee(addressBook.getConsignee());
orders.setPhone(addressBook.getPhone());
orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
+ (addressBook.getCityName() == null ? "" : addressBook.getCityName())
+ (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
+ (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
this.save(orders);
//向订单明细表插入数据多条数据
orderDetailService.saveBatch(orderDetails);
//清空购物车
shoppingCartService.remove(lqw);
}
@Override
public Page<OrdersDto> getPage(long page, long pageSize, LambdaQueryWrapper<Orders> lqw) {
Page<Orders> pageInfo = this.page(new Page<>(page, pageSize), lqw);
List<OrdersDto> list = pageInfo.getRecords().stream().map((item) -> {
OrdersDto ordersDto = new OrdersDto();
Long orderId = item.getId();
LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderDetail::getOrderId, orderId);
List<OrderDetail> details = orderDetailService.list(wrapper);
BeanUtils.copyProperties(item, ordersDto);
ordersDto.setOrderDetails(details);
return ordersDto;
}).collect(Collectors.toList());
Page<OrdersDto> dtoPage = new Page<>();
BeanUtils.copyProperties(pageInfo, dtoPage, "records");
dtoPage.setRecords(list);
return dtoPage;
}
}

View File

@ -0,0 +1,15 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.SetmealDish;
import cn.czyx007.reggie.mapper.SetmealDishMapper;
import cn.czyx007.reggie.service.SetmealDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 11:49
*/
@Service
public class SetmealDishServiceImpl extends ServiceImpl<SetmealDishMapper, SetmealDish> implements SetmealDishService {
}

View File

@ -0,0 +1,75 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.DishFlavor;
import cn.czyx007.reggie.bean.Setmeal;
import cn.czyx007.reggie.bean.SetmealDish;
import cn.czyx007.reggie.dto.SetmealDto;
import cn.czyx007.reggie.mapper.SetmealMapper;
import cn.czyx007.reggie.service.SetmealDishService;
import cn.czyx007.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import kotlin.jvm.internal.Lambda;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : 张宇轩
* @createTime : 2023/1/18 - 11:51
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
@Autowired
private SetmealDishService setmealDishService;
@Transactional
@Override
public void saveWithDish(SetmealDto setmealDto) {
//保存套餐基本信息
this.save(setmealDto);
//保存关联信息
List<SetmealDish> dishes = setmealDto.getSetmealDishes();
dishes.stream().map((item) -> {
item.setSetmealId(setmealDto.getId());
return item;
}).collect(Collectors.toList());
setmealDishService.saveBatch(dishes);
}
@Override
public SetmealDto getByIdWithDishes(long id) {
Setmeal setmeal = this.getById(id);
SetmealDto setmealDto = new SetmealDto();
BeanUtils.copyProperties(setmeal, setmealDto);
LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
lqw.eq(SetmealDish::getSetmealId, id);
setmealDto.setSetmealDishes(setmealDishService.list(lqw));
return setmealDto;
}
@Override
public void updateWithDishes(SetmealDto setmealDto) {
//更新套餐基本信息
this.updateById(setmealDto);
//清理当前套餐的菜品信息后重新添加
LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
lqw.eq(SetmealDish::getSetmealId, setmealDto.getId());
setmealDishService.remove(lqw);
List<SetmealDish> dishes = setmealDto.getSetmealDishes();
dishes = dishes.stream().map((item) -> {
item.setSetmealId(setmealDto.getId());
return item;
}).collect(Collectors.toList());
setmealDishService.saveBatch(dishes);
}
}

View File

@ -0,0 +1,23 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.ShoppingCart;
import cn.czyx007.reggie.common.BaseContext;
import cn.czyx007.reggie.mapper.ShoppingCartMapper;
import cn.czyx007.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 20:36
*/
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
@Override
public void clean() {
LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
this.remove(lqw);
}
}

View File

@ -0,0 +1,15 @@
package cn.czyx007.reggie.service.impl;
import cn.czyx007.reggie.bean.User;
import cn.czyx007.reggie.mapper.UserMapper;
import cn.czyx007.reggie.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 15:30
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

View File

@ -0,0 +1,57 @@
package cn.czyx007.reggie.utils;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author : 张宇轩
* @createTime : 2023/1/19 - 15:43
*/
@Component
public class SendEmailUtils {
private static String userName;
private static String password;
@Value("${email.userName}")
public void setUserName(String userName) {
SendEmailUtils.userName = userName;
}
@Value("${email.password}")
public void setPassword(String password) {
SendEmailUtils.password = password;
}
/**
* 发送验证码
* @param email 接收邮箱
* @param code 验证码
*/
public static void sendAuthCodeEmail(String email,String code) {
try {
HtmlEmail mail = new HtmlEmail();
/*发送邮件的服务器 126邮箱为smtp.126.com,163邮箱为163.smtp.comQQ为smtp.qq.com*/
mail.setHostName("smtp.qq.com");
/*不设置发送的消息有可能是乱码*/
mail.setCharset("UTF-8");
/*IMAP/SMTP服务的密码 username为你开启发送验证码功能的邮箱号 password为你在qq邮箱获取到的一串字符串*/
mail.setAuthentication(userName, password);
/*发送邮件的邮箱和发件人*/
mail.setFrom(userName, "瑞吉外卖");
/*使用安全链接*/
mail.setSSLOnConnect(true);
/*接收的邮箱*/
mail.addTo(email);
/*设置邮件的主题*/
mail.setSubject("登录验证码");
/*设置邮件的内容*/
mail.setMsg("尊敬的用户:你好! 登录验证码为:" + code + "(有效期为一分钟)");
mail.send();//发送
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,43 @@
package cn.czyx007.reggie.utils;
import java.util.Random;
/**
* 随机生成验证码工具类
*/
public class ValidateCodeUtils {
/**
* 随机生成验证码
* @param length 长度为4位或者6位
* @return
*/
public static Integer generateValidateCode(int length){
Integer code =null;
if(length == 4){
code = new Random().nextInt(9999);//生成随机数最大为9999
if(code < 1000){
code = code + 1000;//保证随机数为4位数字
}
}else if(length == 6){
code = new Random().nextInt(999999);//生成随机数最大为999999
if(code < 100000){
code = code + 100000;//保证随机数为6位数字
}
}else{
throw new RuntimeException("只能生成4位或6位数字验证码");
}
return code;
}
/**
* 随机生成指定长度字符串验证码
* @param length 长度
* @return
*/
public static String generateValidateCode4String(int length){
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
String capstr = hash1.substring(0, length);
return capstr;
}
}

View File

@ -0,0 +1,18 @@
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai
username: root
password:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
reggie:
path:
email:
userName:
password:

View File

@ -0,0 +1,43 @@
// 查询列表接口
const getCategoryPage = (params) => {
return $axios({
url: '/category/page',
method: 'get',
params
})
}
// 编辑页面反查详情接口
const queryCategoryById = (id) => {
return $axios({
url: `/category/${id}`,
method: 'get'
})
}
// 删除当前列的接口
const deleCategory = (ids) => {
return $axios({
url: '/category',
method: 'delete',
params: { ids }
})
}
// 修改接口
const editCategory = (params) => {
return $axios({
url: '/category',
method: 'put',
data: { ...params }
})
}
// 新增接口
const addCategory = (params) => {
return $axios({
url: '/category',
method: 'post',
data: { ...params }
})
}

View File

@ -0,0 +1,52 @@
// 查询列表数据
const getSetmealPage = (params) => {
return $axios({
url: '/setmeal/page',
method: 'get',
params
})
}
// 删除数据接口
const deleteSetmeal = (ids) => {
return $axios({
url: '/setmeal',
method: 'delete',
params: { ids }
})
}
// 修改数据接口
const editSetmeal = (params) => {
return $axios({
url: '/setmeal',
method: 'put',
data: { ...params }
})
}
// 新增数据接口
const addSetmeal = (params) => {
return $axios({
url: '/setmeal',
method: 'post',
data: { ...params }
})
}
// 查询详情接口
const querySetmealById = (id) => {
return $axios({
url: `/setmeal/${id}`,
method: 'get'
})
}
// 批量起售禁售
const setmealStatusByStatus = (params) => {
return $axios({
url: `/setmeal/status/${params.status}`,
method: 'post',
params: { ids: params.ids }
})
}

View File

@ -0,0 +1,82 @@
// 查询列表接口
const getDishPage = (params) => {
return $axios({
url: '/dish/page',
method: 'get',
params
})
}
// 删除接口
const deleteDish = (ids) => {
return $axios({
url: '/dish',
method: 'delete',
params: { ids }
})
}
// 修改接口
const editDish = (params) => {
return $axios({
url: '/dish',
method: 'put',
data: { ...params }
})
}
// 新增接口
const addDish = (params) => {
return $axios({
url: '/dish',
method: 'post',
data: { ...params }
})
}
// 查询详情
const queryDishById = (id) => {
return $axios({
url: `/dish/${id}`,
method: 'get'
})
}
// 获取菜品分类列表
const getCategoryList = (params) => {
return $axios({
url: '/category/list',
method: 'get',
params
})
}
// 查菜品列表的接口
const queryDishList = (params) => {
return $axios({
url: '/dish/list',
method: 'get',
params
})
}
// 文件down预览
const commonDownload = (params) => {
return $axios({
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
url: '/common/download',
method: 'get',
params
})
}
// 起售停售---批量起售停售接口
const dishStatusByStatus = (params) => {
return $axios({
url: `/dish/status/${params.status}`,
method: 'post',
params: { ids: params.id }
})
}

View File

@ -0,0 +1,14 @@
function loginApi(data) {
return $axios({
'url': '/employee/login',
'method': 'post',
data
})
}
function logoutApi(){
return $axios({
'url': '/employee/logout',
'method': 'post',
})
}

View File

@ -0,0 +1,42 @@
function getMemberList (params) {
return $axios({
url: '/employee/page',
method: 'get',
params
})
}
// 修改---启用禁用接口
function enableOrDisableEmployee (params) {
return $axios({
url: '/employee',
method: 'put',
data: { ...params }
})
}
// 新增---添加员工
function addEmployee (params) {
return $axios({
url: '/employee',
method: 'post',
data: { ...params }
})
}
// 修改---添加员工
function editEmployee (params) {
return $axios({
url: '/employee',
method: 'put',
data: { ...params }
})
}
// 修改页面反查详情接口
function queryEmployeeById (id) {
return $axios({
url: `/employee/${id}`,
method: 'get'
})
}

View File

@ -0,0 +1,25 @@
// 查询列表页接口
const getOrderDetailPage = (params) => {
return $axios({
url: '/order/page',
method: 'get',
params
})
}
// 查看接口
const queryOrderDetailById = (id) => {
return $axios({
url: `/orderDetail/${id}`,
method: 'get'
})
}
// 取消,派送,完成接口
const editOrderDetail = (params) => {
return $axios({
url: '/order',
method: 'put',
data: { ...params }
})
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 425 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 837 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 938 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,214 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>瑞吉外卖管理端</title>
<link rel="shortcut icon" href="favicon.ico">
<!-- 引入样式 -->
<link rel="stylesheet" href="plugins/element-ui/index.css" />
<link rel="stylesheet" href="styles/common.css" />
<link rel="stylesheet" href="styles/index.css" />
<link rel="stylesheet" href="styles/icon/iconfont.css" />
<style>
.body{
min-width: 1366px;
}
.app-main{
height: calc(100% - 64px);
}
.app-main .divTmp{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="app" id="app">
<div class="app-wrapper openSidebar clearfix">
<!-- sidebar -->
<div class="sidebar-container">
<div class="logo">
<!-- <img src="images/logo.png" width="122.5" alt="" /> -->
<img src="images/login/login-logo.png" alt="" style="width: 117px; height: 32px" />
</div>
<el-scrollbar wrap-class="scrollbar-wrapper">
<el-menu
:default-active="defAct"
:unique-opened="false"
:collapse-transition="false"
background-color="#343744"
text-color="#bfcbd9"
active-text-color="#f4f4f5"
>
<div v-for="item in menuList" :key="item.id">
<el-submenu :index="item.id" v-if="item.children && item.children.length>0">
<template slot="title">
<i class="iconfont" :class="item.icon"></i>
<span>{{item.name}}</span>
</template>
<el-menu-item
v-for="sub in item.children"
:index="sub.id"
:key="sub.id"
@click="menuHandle(sub,false)"
>
<i :class="iconfont" :class="sub.icon"></i>
<span slot="title">{{sub.name}}</span>
</el-menu-item
>
</el-submenu>
<el-menu-item v-else :index="item.id" @click="menuHandle(item,false)">
<i class="iconfont" :class="item.icon"></i>
<span slot="title">{{item.name}}</span>
</el-menu-item>
</div>
</el-menu>
</el-scrollbar>
</div>
<div class="main-container">
<!-- <navbar /> -->
<div class="navbar">
<div class="head-lable">
<span v-if="goBackFlag" class="goBack" @click="goBack()"
><img src="images/icons/btn_back@2x.png" alt="" /> 返回</span
>
<span>{{headTitle}}</span>
</div>
<div class="right-menu">
<div class="avatar-wrapper">{{ userInfo.name }}</div>
<!-- <div class="logout" @click="logout">退出</div> -->
<img src="images/icons/btn_close@2x.png" class="outLogin" alt="退出" @click="logout" />
</div>
</div>
<div class="app-main" v-loading="loading">
<div class="divTmp" v-show="loading"></div>
<iframe
id="cIframe"
class="c_iframe"
name="cIframe"
:src="iframeUrl"
width="100%"
height="auto"
frameborder="0"
v-show="!loading"
></iframe>
</div>
</div>
</div>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="plugins/axios/axios.min.js"></script>
<script src="js/request.js"></script>
<script src="./api/login.js"></script>
<script>
new Vue({
el: '#app',
data() {
return {
defAct: '2',
menuActived: '2',
userInfo: {},
menuList: [
// {
// id: '1',
// name: '门店管理',
// children: [
{
id: '2',
name: '员工管理',
url: 'page/member/list.html',
icon: 'icon-member'
},
{
id: '3',
name: '分类管理',
url: 'page/category/list.html',
icon: 'icon-category'
},
{
id: '4',
name: '菜品管理',
url: 'page/food/list.html',
icon: 'icon-food'
},
{
id: '5',
name: '套餐管理',
url: 'page/combo/list.html',
icon: 'icon-combo'
},
{
id: '6',
name: '订单明细',
url: 'page/order/list.html',
icon: 'icon-order'
}
// ],
// },
],
iframeUrl: 'page/member/list.html',
headTitle: '员工管理',
goBackFlag: false,
loading: true,
timer: null
}
},
computed: {},
created() {
const userInfo = window.localStorage.getItem('userInfo')
if (userInfo) {
this.userInfo = JSON.parse(userInfo)
}
this.closeLoading()
},
beforeDestroy() {
this.timer = null
clearTimeout(this.timer)
},
mounted() {
window.menuHandle = this.menuHandle
},
methods: {
logout() {
logoutApi().then((res)=>{
if(res.code === 1){
localStorage.removeItem('userInfo')
window.location.href = '/backend/page/login/login.html'
}
})
},
goBack() {
// window.location.href = 'javascript:history.go(-1)'
const menu = this.menuList.find(item=>item.id===this.menuActived)
// this.goBackFlag = false
// this.headTitle = menu.name
this.menuHandle(menu,false)
},
menuHandle(item, goBackFlag) {
this.loading = true
this.menuActived = item.id
this.iframeUrl = item.url
this.headTitle = item.name
this.goBackFlag = goBackFlag
this.closeLoading()
},
closeLoading(){
this.timer = null
this.timer = setTimeout(()=>{
this.loading = false
},1000)
}
}
})
</script>
</body>
</html>

View File

@ -0,0 +1 @@
var web_prefix = '/backend'

View File

@ -0,0 +1,18 @@
/* 自定义trim */
function trim (str) { //删除左右两端的空格,自定义的trim()方法
return str == undefined ? "" : str.replace(/(^\s*)|(\s*$)/g, "")
}
//获取url地址上面的参数
function requestUrlParam(argname){
var url = location.href
var arrStr = url.substring(url.indexOf("?")+1).split("&")
for(var i =0;i<arrStr.length;i++)
{
var loc = arrStr[i].indexOf(argname+"=")
if(loc!=-1){
return arrStr[i].replace(argname+"=","").replace("?","")
}
}
return ""
}

View File

@ -0,0 +1,76 @@
(function (win) {
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项表示请求URL公共部分
baseURL: '/',
// 超时
timeout: 1000000
})
// request拦截器
service.interceptors.request.use(config => {
// 是否需要设置 token
// const isToken = (config.headers || {}).isToken === false
// if (getToken() && !isToken) {
// config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
// }
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') {// 返回登录页面
console.log('---/backend/page/login/login.html---')
localStorage.removeItem('userInfo')
window.top.location.href = '/backend/page/login/login.html'
} else {
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
window.ELEMENT.Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
 win.$axios = service
})(window);

View File

@ -0,0 +1,62 @@
function isValidUsername (str) {
return ['admin', 'editor'].indexOf(str.trim()) >= 0;
}
function isExternal (path) {
return /^(https?:|mailto:|tel:)/.test(path);
}
function isCellPhone (val) {
if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
return false
} else {
return true
}
}
//校验账号
function checkUserName (rule, value, callback){
if (value == "") {
callback(new Error("请输入账号"))
} else if (value.length > 20 || value.length <3) {
callback(new Error("账号长度应是3-20"))
} else {
callback()
}
}
//校验姓名
function checkName (rule, value, callback){
if (value == "") {
callback(new Error("请输入姓名"))
} else if (value.length > 12) {
callback(new Error("账号长度应是1-12"))
} else {
callback()
}
}
function checkPhone (rule, value, callback){
// let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
if (value == "") {
callback(new Error("请输入手机号"))
} else if (!isCellPhone(value)) {//引入methods中封装的检查手机格式的方法
callback(new Error("请输入正确的手机号!"))
} else {
callback()
}
}
function validID (rule,value,callback) {
// 身份证号码为15位或者18位15位时全为数字18位前17位为数字最后一位是校验位可能为数字或字符X
let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
if(value == '') {
callback(new Error('请输入身份证号码'))
} else if (reg.test(value)) {
callback()
} else {
callback(new Error('身份证号码不正确'))
}
}

Some files were not shown because too many files have changed in this diff Show More