branch_wangheng
wangheng 7 months ago
parent 8328fa6167
commit 5869978929

@ -0,0 +1,30 @@
package com.sky;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
@SpringBootApplication() // 启用Spring Boot的自动配置和组件扫描
@EnableTransactionManagement // 开启注解方式的事务管理
@Slf4j // 启用Lombok日志功能自动生成log对象
@EnableConfigurationProperties // 允许@ConfigurationProperties注解使用用于从配置文件加载属性
@EnableCaching // 启用Spring的缓存机制
@EnableScheduling // 启用定时任务功能
public class SkyServerApplication {
// 程序的入口点启动Spring Boot应用
public static void main(String[] args) {
SpringApplication.run(SkyServerApplication.class, args); // 启动Spring Boot应用
log.info("server started"); // 输出应用启动的日志信息
}
}

@ -0,0 +1,33 @@
package com.sky.annotation;
import com.sky.enumeration.OperationType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* AutoFill
*
*
* -
* - AOP
*
* 使
*
*
* {@code @AutoFill(OperationType.INSERT)}
*/
@Target(ElementType.METHOD) // 指定该注解只能应用于方法上
@Retention(RetentionPolicy.RUNTIME) // 指定该注解在运行时可用(用于运行时动态处理)
public @interface AutoFill {
/**
*
* {@link OperationType} INSERT UPDATE
*
* @return
*/
OperationType value();
}

@ -0,0 +1,29 @@
package com.sky.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocketConfiguration Spring WebSocket
* @Configuration Spring WebSocket Bean
*/
@Configuration
public class WebSocketConfiguration {
/**
* ServerEndpointExporter Bean Bean WebSocket
*
*
* ServerEndpointExporter Spring WebSocket 使 @ServerEndpoint WebSocket
*
* Spring WebSocket
*
* @return ServerEndpointExporter Bean
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
// 返回 ServerEndpointExporter 实例Spring 会自动注册 WebSocket 端点
return new ServerEndpointExporter();
}
}

@ -0,0 +1,166 @@
package com.sky.controller.admin;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
/**
*
*
* 使 Swagger API
*/
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {
@Autowired
private EmployeeService employeeService; // 注入员工服务类,用于处理员工相关业务
@Autowired
private JwtProperties jwtProperties; // 注入 JWT 配置类,用于生成 JWT 令牌
/**
*
* JWT
*
* @param employeeLoginDTO
* @return JWT
*/
@PostMapping("/login")
@ApiOperation(value = "员工登录")
public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
log.info("员工登录:{}", employeeLoginDTO); // 记录登录请求日志
// 调用员工服务进行登录验证
Employee employee = employeeService.login(employeeLoginDTO);
// 登录成功后,生成 JWT 令牌
Map<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.EMP_ID, employee.getId()); // 将员工ID放入JWT的claims部分
String token = JwtUtil.createJWT(
jwtProperties.getAdminSecretKey(), // 获取密钥
jwtProperties.getAdminTtl(), // 获取有效期
claims); // 设置 JWT claims
// 将登录者的 ID 设置到当前线程上下文中,以便其他地方使用
BaseContext.setCurrentId(employee.getId());
// 构造员工登录响应对象
EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
.id(employee.getId())
.userName(employee.getUsername())
.name(employee.getName())
.token(token)
.build();
return Result.success(employeeLoginVO); // 返回成功结果
}
/**
* 退
* 退退
*
* @return 退
*/
@PostMapping("/logout")
@ApiOperation("员工退出")
public Result<String> logout() {
return Result.success(); // 直接返回成功
}
/**
*
*
*
* @param employeeDTO
* @return
*/
@PostMapping
@ApiOperation("新增员工")
public Result save(@RequestBody EmployeeDTO employeeDTO) {
log.info("新增员工:{}", employeeDTO); // 记录新增员工请求日志
employeeService.save(employeeDTO); // 调用服务层保存员工数据
return Result.success(); // 返回成功结果
}
/**
*
*
*
* @param employeePageQueryDTO
* @return
*/
@GetMapping("/page")
@ApiOperation("员工分页查询")
public Result<PageResult> pageQuery(EmployeePageQueryDTO employeePageQueryDTO){
log.info("员工分页查询,参数为:{}", employeePageQueryDTO); // 记录分页查询请求日志
PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO); // 调用服务层进行分页查询
return Result.success(pageResult); // 返回分页查询结果
}
/**
*
*
*
* @param status 10
* @param id ID
* @return
*/
@PostMapping("/status/{status}")
@ApiOperation("启用或禁用员工账号")
public Result startOrStop(@PathVariable Integer status, Long id) {
log.info("启用禁用员工账号{},{}", status, id); // 记录启用禁用请求日志
employeeService.startOrStop(status, id); // 调用服务层启用或禁用员工账号
return Result.success(); // 返回成功结果
}
/**
* ID
*
*
* @param id ID
* @return
*/
@GetMapping("/{id}")
@ApiOperation("通过id查询员工信息")
public Result<Employee> getById(@PathVariable Long id) {
Employee employee = employeeService.getById(id); // 调用服务层查询员工
return Result.success(employee); // 返回查询结果
}
/**
*
*
*
* @param employeeDTO
* @return
*/
@PutMapping
@ApiOperation("编辑员工信息")
public Result update(@RequestBody EmployeeDTO employeeDTO) {
log.info("编辑员工信息:{}", employeeDTO); // 记录编辑员工信息请求日志
employeeService.update(employeeDTO); // 调用服务层更新员工信息
return Result.success(); // 返回成功结果
}
}

@ -0,0 +1,67 @@
package com.sky.controller.admin;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
/**
*
*
* 使 Redis 便
*/
@RestController("adminShopController")
@Slf4j
@Api("管理员店铺相关接口")
@RequestMapping("/admin/shop")
public class ShopController {
@Autowired
private RedisTemplate redisTemplate; // 注入 RedisTemplate 用于操作 Redis 数据库
private static final String key = "SHOP_STATUS"; // 定义 Redis 中保存店铺状态的键
/**
*
* 1 0
*
* @param status 1: , 0:
* @return
*/
@PutMapping("/{status}")
@ApiOperation("设置店铺营业状态")
public Result setStatus(@PathVariable Integer status) {
// 记录设置店铺状态的日志信息
log.info("设置店铺营业状态为:{}", status == 1 ? "营业中" : "打烊中");
// 获取 Redis 的 ValueOperations 操作对象
ValueOperations valueOperations = redisTemplate.opsForValue();
// 将店铺状态保存到 Redis 中
valueOperations.set(key, status);
return Result.success(); // 返回成功结果
}
/**
*
* 1 0
*
* @return
*/
@GetMapping("/status")
@ApiOperation("查询店铺营业状态")
public Result<Integer> queryStatus() {
// 获取 Redis 的 ValueOperations 操作对象
ValueOperations valueOperations = redisTemplate.opsForValue();
// 从 Redis 中获取店铺状态
Integer status = (Integer) valueOperations.get(key);
// 记录查询店铺状态的日志信息
log.info("店铺状态为:{}", status == 1 ? "营业中" : "打烊中");
return Result.success(status); // 返回查询结果
}
}

@ -0,0 +1,48 @@
package com.sky.controller.user;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* -
*
*/
@RestController("userCategoryController")
@RequestMapping("/user/category")
@Api(tags = "C端-分类接口")
@Slf4j
public class CategoryController {
@Autowired
private CategoryService categoryService; // 注入 CategoryService 服务,用于查询分类信息
/**
*
* type
*
* @param type
* @return
*/
@GetMapping("/list")
@ApiOperation("查询分类")
public Result<List<Category>> list(Integer type) {
// 记录查询分类操作的日志,输出传入的分类类型参数
log.info("查询分类{}", type);
// 调用 categoryService 查询分类信息
List<Category> list = categoryService.query(type);
// 返回查询结果,封装在 Result 对象中
return Result.success(list);
}
}

@ -0,0 +1,48 @@
package com.sky.controller.user;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
/**
* -
*
* 使 Redis 便
*/
@RestController("userShopController")
@Slf4j
@Api("用户店铺相关接口")
@RequestMapping("/user/shop")
public class ShopController {
@Autowired
private RedisTemplate redisTemplate; // 注入 RedisTemplate 用于操作 Redis 数据库
private static final String key = "SHOP_STATUS"; // 定义 Redis 中保存店铺状态的键
/**
*
* 1 0
*
* @return
*/
@GetMapping("/status")
@ApiOperation("查询店铺营业状态")
public Result<Integer> queryStatus() {
// 获取 Redis 的 ValueOperations 操作对象
ValueOperations valueOperations = redisTemplate.opsForValue();
// 从 Redis 中获取店铺状态
Integer status = (Integer) valueOperations.get(key);
// 记录查询店铺状态的日志信息
log.info("店铺状态为:{}", status == 1 ? "营业中" : "打烊中");
// 返回查询结果,封装在 Result 对象中
return Result.success(status);
}
}

@ -0,0 +1,69 @@
package com.sky.interceptor;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* JWT
* JWT
* 401
*/
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
@Autowired
private JwtProperties jwtProperties; // 注入 JWT 配置属性,获取密钥和令牌名称
/**
* JWT
* Controller JWT
*
* @param request
* @param response
* @param handler Controller
* @return true false
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 判断当前拦截到的是 Controller 的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
// 当前拦截到的不是动态方法,直接放行
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 1、从请求头中获取 JWT 令牌
String token = request.getHeader(jwtProperties.getAdminTokenName());
// 2、校验令牌
try {
log.info("JWT 校验: {}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token); // 解析 JWT
Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString()); // 获取员工 ID
BaseContext.setCurrentId(empId); // 设置当前员工 ID 到上下文中
log.info("当前员工 ID: {}", empId);
// 3、校验通过放行请求
return true;
} catch (Exception ex) {
// 4、校验失败返回 401 状态码,表示未授权
log.error(MessageConstant.USER_NOT_LOGIN); // 打印未登录错误日志
response.setStatus(401); // 设置响应状态为 401
return false; // 拦截请求,不继续执行
}
}
}

@ -0,0 +1,115 @@
package com.sky.mapper;
import com.github.pagehelper.Page;
import com.sky.annotation.AutoFill;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.enumeration.OperationType;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Mapper // 标记为 MyBatis 的 Mapper 接口,表明这是 MyBatis 对数据库操作的接口
public interface DishMapper {
/**
*
*
* @param dishPageQueryDTO
* @return
*/
Page<Dish> pageQuery(DishPageQueryDTO dishPageQueryDTO);
/**
*
*
* @param dish
*/
@AutoFill(OperationType.INSERT) // 自动填充操作,标记为插入操作
void save(Dish dish);
/**
*
*
* @param flavors
*/
void insertBatchFlavors(List<DishFlavor> flavors);
/**
*
*
* @param ids ID
*/
void deleteBatch(ArrayList<Long> ids);
/**
* ID
*
* @param ids ID
* @return
*/
ArrayList<Dish> getByIdBatch(ArrayList<Long> ids);
/**
* ID
*
* @param ids ID
* @return
*/
Integer countMealDish(ArrayList<Long> ids);
/**
*
*
* @param dish
*/
@AutoFill(OperationType.UPDATE) // 自动填充操作,标记为更新操作
void updateDish(Dish dish);
/**
*
*
* @param flavors
*/
void deleteBatchFlavors(List<DishFlavor> flavors);
/**
* ID
*
* @param id ID
* @return
*/
ArrayList<DishFlavor> getFlavorById(Long id);
/**
* ID
*
* @param categoryId ID
* @param status
* @return
*/
ArrayList<Dish> getByCategoryId(Long categoryId, Integer status);
/**
* ID
*
* @param id ID
* @return
*/
@Select("select * from dish where id=#{id}")
Dish getById(Long id);
/**
*
*
* @param map
* @return
*/
Integer countByMap(Map map);
}

@ -0,0 +1,73 @@
package com.sky.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
@Mapper // 标记为 MyBatis 的 Mapper 接口,用于与数据库交互
public interface ReportMapper {
/**
*
*
*
* @param map
* @return
*/
@Select("select sum(amount) from orders where status=#{status} and checkout_time>#{begin} and checkout_time<#{end}")
Double sumByMap(HashMap<String, Object> map);
/**
*
*
*
* @param map
* @return
*/
@Select("select count(id) from user where create_time>#{begin} and create_time<#{end}")
Integer sumUserByDay(HashMap<String, Object> map);
/**
*
*
*
* @param map
* @return
*/
@Select("select count(*) from user where create_time<#{end}")
Integer sumUser(HashMap<String, Object> map);
/**
*
*
*
* @param map
* @return
*/
@Select("select count(*) from orders where order_time>#{begin} and order_time<#{end}")
Integer sumNewOrder(HashMap<String, Object> map);
/**
*
*
*
* @param map
* @return
*/
@Select("select count(*) from orders where checkout_time>#{begin} and checkout_time<#{end} and status=#{status}")
Integer sumOrder(HashMap<String, Object> map);
/**
*
*
*
* @param map
* @return
*/
@Select("select od.name name, sum(od.number) number from order_detail od, orders o where od.order_id=o.id and status=#{status} and o.order_time>#{begin} and o.order_time<#{end} " +
"group by name order by number desc")
ArrayList<HashMap<String, Object>> salesTop10Report(HashMap<String, Object> map);
}

@ -0,0 +1,68 @@
package com.sky.service;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.result.PageResult;
import java.util.List;
public interface CategoryService {
/**
*
*
*
*
* @param categoryPageQueryDTO
* @return
*/
PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO);
/**
*
*
*
*
* @param type 1 2
* @return
*/
List<Category> query(Integer type);
/**
*
*
* ID
*
* @param id ID
*/
void delete(Long id);
/**
*
*
* DTO
*
* @param categoryDTO DTO
*/
void updateCategory(CategoryDTO categoryDTO);
/**
*
*
*
*
* @param status 1 0
* @param id ID
*/
void startOrStop(Integer status, Long id);
/**
*
*
* DTO
*
* @param categoryDTO DTO
*/
void save(CategoryDTO categoryDTO);
}

@ -0,0 +1,159 @@
package com.sky.service;
import com.sky.dto.*;
import com.sky.result.PageResult;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import java.util.ArrayList;
public interface OrderService {
/**
*
*
*
*
* @param id ID
*/
void complete(Long id);
/**
*
*
*
*
* @param id ID
*/
void delivery(Long id);
/**
*
*
*
*
* @param ordersCancelDTO ID
* @throws Exception
*/
void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception;
/**
*
*
*
*
* @param ordersRejectionDTO ID
* @throws Exception
*/
void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception;
/**
*
*
*
*
* @param ordersConfirmDTO ID
*/
void confirm(OrdersConfirmDTO ordersConfirmDTO);
/**
*
*
*
*
* @return
*/
OrderStatisticsVO statistics();
/**
*
*
*
*
* @param ordersPageQueryDTO
* @return
*/
PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO);
/**
*
*
*
*
* @param id ID
* @throws Exception
*/
void userCancelById(Long id) throws Exception;
/**
*
*
*
*
* @param id ID
* @return
*/
OrderVO details(Long id);
/**
*
*
*
*
* @param ordersDTO
* @return ID
*/
OrderSubmitVO submit(OrdersDTO ordersDTO);
/**
*
*
*
*
* @param ordersPaymentDTO DTO
* @return
* @throws Exception
*/
OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception;
/**
*
*
*
*
* @param outTradeNo
*/
void paySuccess(String outTradeNo);
/**
*
*
*
*
* @param id ID
*/
void reminder(Long id);
/**
*
*
*
*
* @param page
* @param pageSize
* @param status
* @return
*/
PageResult pageQuery4User(int page, int pageSize, Integer status);
/**
*
*
*
*
* @param id ID
*/
void repetition(Long id);
}

@ -0,0 +1,19 @@
package com.sky.service;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
public interface UserService {
/**
*
*
*
* openid
*
* @param userLoginDTO
* @return
*/
User wxLogin(UserLoginDTO userLoginDTO);
}

@ -0,0 +1,94 @@
package com.sky.service.impl;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service // 该注解表示该类是一个服务层的 Bean
@Slf4j // 提供日志功能
public class AddressBookServiceImpl implements AddressBookService {
@Autowired // 自动注入 AddressBookMapper
private AddressBookMapper addressBookMapper;
/**
*
* AddressBook
*
* @param addressBook
* @return
*/
public List<AddressBook> list(AddressBook addressBook) {
return addressBookMapper.list(addressBook); // 调用 mapper 查询数据库
}
/**
*
* ID
*
* @param addressBook
*/
public void save(AddressBook addressBook) {
addressBook.setUserId(BaseContext.getCurrentId()); // 设置当前用户的 ID
addressBook.setIsDefault(0); // 设置地址为非默认地址
addressBookMapper.insert(addressBook); // 调用 mapper 插入新地址
}
/**
* id
* ID
*
* @param id ID
* @return AddressBook
*/
public AddressBook getById(Long id) {
return addressBookMapper.getById(id); // 调用 mapper 根据 ID 查询地址
}
/**
* id
*
*
* @param addressBook
*/
public void update(AddressBook addressBook) {
addressBookMapper.update(addressBook); // 调用 mapper 更新地址
}
/**
*
* 1. `is_default`
* 2. `is_default`
* 使
*
* @param addressBook
*/
@Transactional // 声明事务,确保操作的原子性
public void setDefault(AddressBook addressBook) {
// 1. 将当前用户的所有地址修改为非默认地址
addressBook.setIsDefault(0);
addressBook.setUserId(BaseContext.getCurrentId());
addressBookMapper.updateIsDefaultByUserId(addressBook); // 更新所有地址为非默认
// 2. 将当前地址改为默认地址
addressBook.setIsDefault(1);
addressBookMapper.update(addressBook); // 更新当前地址为默认
}
/**
* id
* ID
*
* @param id ID
*/
public void deleteById(Long id) {
addressBookMapper.deleteById(id); // 调用 mapper 删除地址
}
}

@ -0,0 +1,156 @@
package com.sky.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;
import java.util.List;
@Service // 该类标记为服务层的 Bean
public class EmployeeServiceImpl implements EmployeeService {
@Autowired // 自动注入 EmployeeMapper
private EmployeeMapper employeeMapper;
/**
*
*
*
*
* @param employeeLoginDTO
* @return
* @throws AccountNotFoundException
* @throws PasswordErrorException
* @throws AccountLockedException
*/
public Employee login(EmployeeLoginDTO employeeLoginDTO) {
String username = employeeLoginDTO.getUsername();
String password = employeeLoginDTO.getPassword();
// 1. 根据用户名查询数据库中的员工信息
Employee employee = employeeMapper.getByUsername(username);
// 2. 处理各种异常情况
if (employee == null) {
// 账号不存在
throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
}
// 密码比对
password = DigestUtils.md5DigestAsHex(password.getBytes()); // 对前端传过来的密码进行 md5 加密
if (!password.equals(employee.getPassword())) {
// 密码错误
throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
}
if (employee.getStatus() == StatusConstant.DISABLE) {
// 账号被锁定
throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
}
// 3. 返回员工实体对象
return employee;
}
/**
*
*
* `employeeDTO`
*
* @param employeeDTO
*/
public void save(EmployeeDTO employeeDTO) {
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee); // 将 DTO 中的数据复制到 Employee 实体中
employee.setStatus(StatusConstant.ENABLE); // 设置员工的状态为启用
employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes())); // 设置默认密码
employeeMapper.save(employee); // 调用 Mapper 插入员工数据
}
/**
*
*
* 使 PageHelper
*
* @param employeePageQueryDTO
* @return
*/
public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
// 使用 PageHelper 开启分页
PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
// 执行分页查询
Page<Employee> pageQuery = employeeMapper.pageQuery(employeePageQueryDTO);
// 构建分页结果
PageResult pageResult = new PageResult();
pageResult.setTotal(pageQuery.getTotal()); // 总记录数
pageResult.setRecords(pageQuery.getResult()); // 当前页的记录
return pageResult;
}
/**
*
*
* ID
*
* @param status
* @param id ID
*/
public void startOrStop(Integer status, Long id) {
Employee employee = Employee.builder()
.status(status) // 设置新的账号状态
.id(id) // 设置员工 ID
.build();
employeeMapper.update(employee); // 调用 Mapper 更新员工状态
}
/**
* ID
*
* 使 `*****`
*
* @param id ID
* @return
*/
public Employee getById(Long id) {
Employee employee = employeeMapper.getById(id); // 根据 ID 查询员工信息
employee.setPassword("*****"); // 隐藏密码
return employee;
}
/**
*
*
*
*
* @param employeeDTO
*/
public void update(EmployeeDTO employeeDTO) {
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee); // 将 DTO 转换为实体对象
employeeMapper.update(employee); // 调用 Mapper 更新员工数据
}
}

@ -0,0 +1,128 @@
package com.sky.service.impl;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service // 标记为服务层的 Bean
public class ShoppingCartServiceImpl implements ShoppingCartService {
@Autowired // 自动注入购物车相关的 Mapper
ShoppingCartMapper shoppingCartMapper;
@Autowired
DishMapper dishMapper;
@Autowired
SetmealMapper setmealMapper;
/**
*
*
* DTO
*
* @param shoppingCartDTO
*/
@Override
public void add(ShoppingCartDTO shoppingCartDTO) {
ShoppingCart shoppingCart = new ShoppingCart();
BeanUtils.copyProperties(shoppingCartDTO, shoppingCart); // 将 DTO 中的属性复制到 ShoppingCart 实体中
shoppingCart.setUserId(BaseContext.getCurrentId()); // 设置当前用户 ID
// 如果购物车中已经有该商品,则只需要将该商品的数量加 1
List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
if (shoppingCarts.size() > 0) {
Integer number = shoppingCarts.get(0).getNumber();
shoppingCarts.get(0).setNumber(number + 1); // 增加商品数量
shoppingCartMapper.update(shoppingCarts.get(0)); // 更新购物车
} else {
// 否则,插入一个新的购物车项
Long dishId = shoppingCartDTO.getDishId();
Long setmealId = shoppingCartDTO.getSetmealId();
// 如果是菜品
if (dishId != null) {
Dish dish = dishMapper.getById(dishId); // 根据菜品 ID 查询菜品信息
shoppingCart.setName(dish.getName()); // 设置商品名称
shoppingCart.setAmount(dish.getPrice()); // 设置商品价格
shoppingCart.setImage(dish.getImage()); // 设置商品图片
} else {
// 如果是套餐
Setmeal bySetmealId = setmealMapper.getBySetmealId(setmealId); // 根据套餐 ID 查询套餐信息
shoppingCart.setAmount(bySetmealId.getPrice()); // 设置套餐价格
shoppingCart.setName(bySetmealId.getName()); // 设置套餐名称
shoppingCart.setImage(shoppingCart.getImage()); // 设置套餐图片
}
shoppingCart.setNumber(1); // 设置商品数量为 1
shoppingCart.setCreateTime(LocalDateTime.now()); // 设置创建时间
shoppingCartMapper.insert(shoppingCart); // 插入新商品到购物车
}
}
/**
*
*
* ID
*
* @return
*/
@Override
public List<ShoppingCart> list() {
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.setUserId(BaseContext.getCurrentId()); // 设置当前用户 ID
return shoppingCartMapper.list(shoppingCart); // 返回购物车数据
}
/**
*
*
* DTO 1 1
*
* @param shoppingCartDTO
*/
@Override
public void delete(ShoppingCartDTO shoppingCartDTO) {
ShoppingCart shoppingCart = new ShoppingCart();
BeanUtils.copyProperties(shoppingCartDTO, shoppingCart); // 将 DTO 中的属性复制到 ShoppingCart 实体中
shoppingCart.setUserId(BaseContext.getCurrentId()); // 设置当前用户 ID
// 查询购物车中的商品
List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
Integer number = list.get(0).getNumber(); // 获取商品数量
// 如果数量大于 1则将数量减 1
if (number > 1) {
list.get(0).setNumber(number - 1);
shoppingCartMapper.update(list.get(0)); // 更新购物车
} else {
// 如果数量为 1则从购物车中删除该商品
shoppingCartMapper.delete(list.get(0)); // 删除商品
}
}
/**
*
*
*
*/
@Override
public void clean() {
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.setUserId(BaseContext.getCurrentId()); // 设置当前用户 ID
shoppingCartMapper.delete(shoppingCart); // 删除该用户的所有购物车项
}
}
Loading…
Cancel
Save