更新了商品管理模块

This commit is contained in:
chen-xin-zhi 2024-11-22 19:47:14 +08:00
parent 1ed5d1f77b
commit c9af504c46
21 changed files with 802 additions and 307 deletions

View File

@ -18,6 +18,7 @@ public class BookingDateConfig {
@Resource
private BookingDateService bookingDateService;
// 写真预约日期初始化
@Bean
public Boolean initBookingDate() {
System.out.println("这是Config");
@ -35,4 +36,5 @@ public class BookingDateConfig {
}
return true;
}
}

View File

@ -0,0 +1,13 @@
package com.cultural.heritage.constant;
public interface CouponStatus {
String IS_NOT_ENABLED = "未启用";
String IS_ENABLED = "可使用";
String IS_OVERDUE = "已过期";
}

View File

@ -40,13 +40,13 @@ public class BookingDateController {
/**
* 初始化未来一天的预约日期
* (写真预约)初始化未来一天的预约日期
*/
// @Scheduled(cron = "*/5 * * * * ?")
// 每天00:00-00:00调用
@Scheduled(cron = "0 0 0 * * ?")
@Transactional(rollbackFor = Exception.class)
@GetMapping("/init")
@PostMapping("/init")
@Operation(summary = "(自动调用)初始化未来一天的预约日期", description = "参数权限自动调用方法名initCurrentBookingDate")
public void initCurrentBookingDate() {
// 初始化预约日期

View File

@ -1,26 +1,32 @@
package com.cultural.heritage.controller.good;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cultural.heritage.annotation.AuthCheck;
import com.cultural.heritage.common.BaseResponse;
import com.cultural.heritage.common.ErrorCode;
import com.cultural.heritage.common.ResultUtils;
import com.cultural.heritage.constant.CouponStatus;
import com.cultural.heritage.constant.UserConstant;
import com.cultural.heritage.exception.BusinessException;
import com.cultural.heritage.exception.ThrowUtils;
import com.cultural.heritage.model.dto.CommonRequest;
import com.cultural.heritage.model.dto.coupon.CouponAddRequest;
import com.cultural.heritage.model.dto.coupon.CouponQueryRequest;
import com.cultural.heritage.model.dto.coupon.CouponShelvesUpdateRequest;
import com.cultural.heritage.model.dto.coupon.CouponUpdateRequest;
import com.cultural.heritage.model.dto.exchange.ExchangeAddRequest;
import com.cultural.heritage.model.entity.Coupon;
import com.cultural.heritage.model.entity.Exchange;
import com.cultural.heritage.model.entity.User;
import com.cultural.heritage.model.entity.UserCoupon;
import com.cultural.heritage.model.vo.coupon.CouponVO;
import com.cultural.heritage.model.vo.exchange.ExchangeVO;
import com.cultural.heritage.service.good.CouponService;
import com.cultural.heritage.service.good.ExchangeService;
import com.cultural.heritage.service.good.UserCouponService;
import com.cultural.heritage.service.user.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@ -29,10 +35,10 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
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 org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@ -49,10 +55,6 @@ public class CouponController {
private UserService userService;
@Resource
private UserCouponService userCouponService;
@Resource
private ExchangeService exchangeService;
@ -141,71 +143,71 @@ public class CouponController {
return ResultUtils.success(page);
}
/**
* 积分兑换优惠券
* @param exchangeAddRequest 兑换记录添加请求体
* @return 是否兑换成功
*/
@PostMapping("/exchange")
@Transactional(rollbackFor = Exception.class)
@Operation(summary = "小程序端用户积分兑换优惠券", description = "参数:兑换记录添加请求体,权限:管理员(admin, boss)方法名pointsExchangeCoupon")
public BaseResponse<Boolean> pointsExchangeCoupon(@RequestBody ExchangeAddRequest exchangeAddRequest, HttpServletRequest request) {
if (exchangeAddRequest == null) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
// 更新用户积分
User loginUser = userService.getLoginUser(request);
Long userId = loginUser.getId();
Integer requirePoints = exchangeAddRequest.getRequirePoints();
Integer quantity = exchangeAddRequest.getQuantity();
if (userId <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
User user = userService.getById(userId);
ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
int residual = user.getPoints() - requirePoints * quantity;
if (residual < 0) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "积分不足");
}
user.setPoints(residual);
boolean save = userService.updateById(user);
ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
// 更新优惠券的库存量
Long couponId = exchangeAddRequest.getCouponId();
Coupon coupon = couponService.getById(couponId);
if (coupon.getTotalNum() - quantity < 0) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "优惠券数量不足");
}
coupon.setResidueNum(coupon.getTotalNum() - quantity);
boolean updateCoupon = couponService.updateById(coupon);
ThrowUtils.throwIf(!updateCoupon, ErrorCode.OPERATION_ERROR);
// 校验用户限领量是否已达到上限
Integer currentNum = couponService.verifyIsReachTheUpperLimit(userId, couponId);
int limitNum = 0;
if (currentNum == null) {
limitNum = quantity;
} else {
limitNum = currentNum + quantity;
}
if ( limitNum > coupon.getLimitNum()) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户限领量已达到上限");
}
// 插入一条兑换记录
Exchange exchange = new Exchange();
BeanUtils.copyProperties(exchangeAddRequest, exchange);
boolean result = exchangeService.save(exchange);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
// 给当前用户添加优惠券
UserCoupon userCoupon = new UserCoupon();
BeanUtils.copyProperties(exchangeAddRequest, userCoupon);
boolean couponResult = userCouponService.save(userCoupon);
ThrowUtils.throwIf(!couponResult, ErrorCode.OPERATION_ERROR);
return ResultUtils.success(true, "兑换成功");
}
//
// /**
// * 积分兑换优惠券
// * @param exchangeAddRequest 兑换记录添加请求体
// * @return 是否兑换成功
// */
// @PostMapping("/exchange")
// @Transactional(rollbackFor = Exception.class)
// @Operation(summary = "小程序端用户积分兑换优惠券", description = "参数:兑换记录添加请求体,权限:管理员(admin, boss)方法名pointsExchangeCoupon")
// public BaseResponse<Boolean> pointsExchangeCoupon(@RequestBody ExchangeAddRequest exchangeAddRequest, HttpServletRequest request) {
// if (exchangeAddRequest == null) {
// throw new BusinessException(ErrorCode.PARAMS_ERROR);
// }
// // 更新用户积分
// User loginUser = userService.getLoginUser(request);
// Long userId = loginUser.getId();
// Integer requirePoints = exchangeAddRequest.getRequirePoints();
// Integer quantity = exchangeAddRequest.getQuantity();
// if (userId <= 0) {
// throw new BusinessException(ErrorCode.PARAMS_ERROR);
// }
// User user = userService.getById(userId);
// ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
// int residual = user.getPoints() - requirePoints * quantity;
// if (residual < 0) {
// throw new BusinessException(ErrorCode.OPERATION_ERROR, "积分不足");
// }
// user.setPoints(residual);
// boolean save = userService.updateById(user);
// ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
//
// // 更新优惠券的库存量
// Long couponId = exchangeAddRequest.getCouponId();
// Coupon coupon = couponService.getById(couponId);
// if (coupon.getTotalNum() - quantity < 0) {
// throw new BusinessException(ErrorCode.OPERATION_ERROR, "优惠券数量不足");
// }
// coupon.setResidueNum(coupon.getTotalNum() - quantity);
// boolean updateCoupon = couponService.updateById(coupon);
// ThrowUtils.throwIf(!updateCoupon, ErrorCode.OPERATION_ERROR);
//
// // 校验用户限领量是否已达到上限
// Integer currentNum = couponService.verifyIsReachTheUpperLimit(userId, couponId);
// int limitNum = 0;
// if (currentNum == null) {
// limitNum = quantity;
// } else {
// limitNum = currentNum + quantity;
// }
// if ( limitNum > coupon.getLimitNum()) {
// throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户限领量已达到上限");
// }
// // 插入一条兑换记录
// Exchange exchange = new Exchange();
// BeanUtils.copyProperties(exchangeAddRequest, exchange);
// boolean result = exchangeService.save(exchange);
// ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//
// // 给当前用户添加优惠券
// UserCoupon userCoupon = new UserCoupon();
// BeanUtils.copyProperties(exchangeAddRequest, userCoupon);
// boolean couponResult = userCouponService.save(userCoupon);
// ThrowUtils.throwIf(!couponResult, ErrorCode.OPERATION_ERROR);
// return ResultUtils.success(true, "兑换成功");
// }
@ -228,4 +230,143 @@ public class CouponController {
}
/**
* 小程序端用户积分兑换优惠券
* @param exchangeAddRequest 兑换记录添加请求体
* @return
*/
@PostMapping("/exchange")
@Operation(summary = "小程序端用户积分兑换优惠券", description = "参数兑换记录添加请求体权限所有人方法名pointsExchangeCoupon")
@Transactional(rollbackFor = Exception.class)
public BaseResponse<Boolean> pointsExchangeCoupon(@RequestBody ExchangeAddRequest exchangeAddRequest, HttpServletRequest request) {
// 获取当前用户信息
User loginUser = userService.getLoginUser(request);
Long userId = loginUser.getId();
Integer points = loginUser.getPoints();
// 获取当前优惠券信息
Long couponId = exchangeAddRequest.getCouponId();
Integer quantity = exchangeAddRequest.getQuantity();
Coupon coupon = couponService.getById(couponId);
ThrowUtils.throwIf(coupon == null, ErrorCode.OPERATION_ERROR, "优惠券不存在");
Integer limitNum = coupon.getLimitNum();
Integer residueNum = coupon.getResidueNum();
// 判断优惠券库存是否足够
if (quantity > residueNum) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "库存不足");
}
// 判断用户限领量是否已达标
QueryWrapper<Exchange> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("userId", userId).eq("couponId", couponId);
List<Exchange> exchangeList = exchangeService.list(queryWrapper);
int sum = 0;
for (int i = 0; i < exchangeList.size(); i ++ ) {
Exchange exchange = exchangeList.get(i);
sum += exchange.getQuantity();
}
if (sum + quantity > limitNum) {
throw new BusinessException(ErrorCode.PARAMS_ERROR, "当前优惠券的限领量已达标");
}
// 判断用户积分是否充足
Integer requirePoints = coupon.getRequirePoints();
if (points < quantity * requirePoints) throw new BusinessException(ErrorCode.OPERATION_ERROR, "积分不足");
// 更新优惠券库存量
coupon.setResidueNum(coupon.getResidueNum() - quantity);
boolean result = couponService.updateById(coupon);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新优惠券库存失败");
// 插入一条兑换记录
CouponVO couponVO = new CouponVO();
BeanUtils.copyProperties(coupon, couponVO);
Exchange exchange = new Exchange();
exchange.setUserId(userId);
exchange.setQuantity(quantity);
exchange.setRestNum(quantity);
exchange.setRequirePoints(requirePoints);
exchange.setCouponId(couponId);
exchange.setCouponDetail(couponVO);
boolean save = exchangeService.save(exchange);
ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "兑换记录插入失败");
// 更新用户积分
loginUser.setPoints(loginUser.getPoints() - quantity * requirePoints);
boolean isSuccess = userService.updateById(loginUser);
ThrowUtils.throwIf(!isSuccess, ErrorCode.OPERATION_ERROR, "更新用户积分信息失败");
return ResultUtils.success(true, "兑换成功");
}
/**
* 小程序端用户查看优惠券
* @return 兑换记录列表
*/
@GetMapping("/list/my")
@Operation(summary = "小程序端用户查看优惠券", description = "参数权限所有人方法名pointsExchangeCoupon")
public BaseResponse<List<ExchangeVO>> listMyCoupon(HttpServletRequest request) {
User loginUser = userService.getLoginUser(request);
Long userId = loginUser.getId();
QueryWrapper<Exchange> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("userId", userId);
List<Exchange> exchangeList = exchangeService.list(queryWrapper);
List<ExchangeVO> exchangeVOS = exchangeList.stream().map(exchange -> {
ExchangeVO exchangeVO = new ExchangeVO();
BeanUtils.copyProperties(exchange, exchangeVO);
String startTime = exchange.getCouponDetail().getStartTime();
String endTime = exchange.getCouponDetail().getEndTime();
DateTime start = DateUtil.parse(startTime);
DateTime end = DateUtil.parse(endTime);
DateTime current = DateUtil.date();
boolean isBefore = current.isBefore(start);
boolean isAfter = current.isAfter(end);
boolean isInRange = current.isAfterOrEquals(start) && current.isBeforeOrEquals(end);
if (isBefore) exchangeVO.setCouponStatus(CouponStatus.IS_NOT_ENABLED);
if (isAfter) exchangeVO.setCouponStatus(CouponStatus.IS_OVERDUE);
if (isInRange) exchangeVO.setCouponStatus(CouponStatus.IS_ENABLED);
return exchangeVO;
}).toList();
List<ExchangeVO> exchangeVOList = exchangeVOS.stream().filter(exchangeVO -> exchangeVO.getRestNum() != 0)
.collect(Collectors.toList());
return ResultUtils.success(exchangeVOList);
}
/**
* Web端管理员上()架优惠券
* @param couponShelvesUpdateRequest 优惠券上架状态更新请求体
* @return 是否更新成功
*/
@PostMapping("/shelves")
@Operation(summary = "Web端管理员上(下)架优惠券", description = "参数:优惠券上架状态更新请求体,权限:管理员(admin, boss)方法名deleteExchangeRecord")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> updateCouponShelvesStatus(@RequestBody CouponShelvesUpdateRequest couponShelvesUpdateRequest) {
if (couponShelvesUpdateRequest == null || couponShelvesUpdateRequest.getId() <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
Long id = couponShelvesUpdateRequest.getId();
Integer isShelves = couponShelvesUpdateRequest.getIsShelves();
UpdateWrapper<Coupon> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", id);
updateWrapper.set("isShelves", isShelves);
boolean update = couponService.update(updateWrapper);
ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "上架状态更新失败");
return ResultUtils.success(true);
}
}

View File

@ -1,6 +1,7 @@
package com.cultural.heritage.controller.good;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cultural.heritage.annotation.AuthCheck;
@ -21,22 +22,30 @@ import com.cultural.heritage.model.dto.good.service.ServiceGoodAddRequest;
import com.cultural.heritage.model.dto.good.service.ServiceGoodUpdateRequest;
import com.cultural.heritage.model.entity.AppointmentDate;
import com.cultural.heritage.model.entity.Good;
import com.cultural.heritage.model.vo.appointment.AppointmentDateVO;
import com.cultural.heritage.model.vo.good.GoodPageVO;
import com.cultural.heritage.model.vo.good.ServiceGoodCardVO;
import com.cultural.heritage.model.vo.good.ServiceGoodVO;
import com.cultural.heritage.service.good.AppointmentDateService;
import com.cultural.heritage.service.good.GoodService;
import com.cultural.heritage.service.user.UserService;
import com.cultural.heritage.utils.AppointmentDateUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
@ -62,12 +71,12 @@ public class GoodController {
/**
* 添加商品
* Web端管理员添加常规类商品
* @param goodAddRequest 商品添加请求体
* @return 是否添加成功
*/
@PostMapping("/add")
@Operation(summary = "Web端管理员添加商品", description = "参数:商品添加请求体,权限:管理员(admin, boss)方法名addGood")
@Operation(summary = "Web端管理员添加常规类商品", description = "参数:商品添加请求体,权限:管理员(admin, boss)方法名addGood")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> addGood(@RequestBody GoodAddRequest goodAddRequest) {
if (goodAddRequest == null) {
@ -86,12 +95,12 @@ public class GoodController {
/**
* 添加服务类商品
* Web端管理员添加服务类商品
* @param serviceGoodAddRequest 服务类商品添加请求体
* @return 是否添加成功
*/
@PostMapping("/add/service")
@Operation(summary = "Web管理员添加服务类商品", description = "参数:服务类商品添加请求体,权限:管理员(admin, boss)方法名addServiceGood")
@Operation(summary = "Web管理员添加服务类商品", description = "参数:服务类商品添加请求体,权限:管理员(admin, boss)方法名addServiceGood")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> addServiceGood(@RequestBody ServiceGoodAddRequest serviceGoodAddRequest) {
if (serviceGoodAddRequest == null) {
@ -105,12 +114,17 @@ public class GoodController {
boolean save = goodService.save(good);
ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
Long id = good.getId();
// 获取当天及未来三天的日期
List<String> dates = AppointmentDateUtil.getDates();
AtomicInteger idx = new AtomicInteger(0);
// 向预约日期表中批量插入服务类商品的预约信息
Long id = good.getId();
List<AppointmentDateAddRequest> appointmentDateAddRequestList = serviceGoodAddRequest.getAppointmentDateAddRequestList();
List<AppointmentDate> appointmentDates = appointmentDateAddRequestList.stream().map(appointmentDateAddRequest -> {
AppointmentDate appointmentDate = new AppointmentDate();
BeanUtils.copyProperties(appointmentDateAddRequest, appointmentDate);
appointmentDate.setSpecificDate(dates.get(idx.getAndIncrement()));
appointmentDate.setGoodId(id);
// 校验
appointmentDateService.validAppointmentDate(appointmentDate, false);
@ -125,12 +139,12 @@ public class GoodController {
/**
* 删除商品
* Web端管理员删除常规类商品
* @param deleteRequest 商品删除请求体
* @return 是否删除成功
*/
@PostMapping("/delete")
@Operation(summary = "Web端管理员删除商品", description = "参数:商品删除请求体,权限:管理员(admin, boss)方法名deleteGood")
@Operation(summary = "Web端管理员删除常规类商品", description = "参数:商品删除请求体,权限:管理员(admin, boss)方法名deleteGood")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> deleteGood(@RequestBody CommonRequest deleteRequest) {
if (deleteRequest == null || deleteRequest.getId() <= 0) {
@ -145,39 +159,71 @@ public class GoodController {
/**
* 删除服务类商品
* Web端管理员删除服务类商品
* @param deleteRequest 服务类商品删除请求体
* @return 是否删除成功
*/
@PostMapping("/delete/service")
@Operation(summary = "Web端管理员删除服务类商品", description = "参数: 商品删除请求体,权限:管理员(admin, boss)方法名deleteServiceGood")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
@Transactional(rollbackFor = Exception.class)
public BaseResponse<Boolean> deleteServiceGood(@RequestBody CommonRequest deleteRequest) {
if (deleteRequest == null || deleteRequest.getId() <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
// 删除商品表中的服务类商品
Long id = deleteRequest.getId();
boolean result = goodService.removeById(id);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
// 删除预约日期表中与该商品关联的记录
QueryWrapper<AppointmentDate> dateQueryWrapper = new QueryWrapper<>();
dateQueryWrapper.eq("goodId", id);
boolean isSuccess = appointmentDateService.remove(dateQueryWrapper);
ThrowUtils.throwIf(!isSuccess, ErrorCode.OPERATION_ERROR);
// 删除商品表中的服务类商品
boolean result = goodService.removeById(id);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
return ResultUtils.success(true);
}
/**
* 更新商品
* Web端用户批量删除服务类商品
* @param ids 服务类商品id列表
* @return 是否删除成功
*/
@PostMapping("/delBatch/service")
@Operation(summary = "Web端用户批量删除服务类商品", description = "服务类商品id列表权限管理员(admin, boss)方法名delBatchServiceGoods")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
@Transactional(rollbackFor = Exception.class)
public BaseResponse<Boolean> delBatchServiceGoods(@RequestBody List<Long> ids) {
if (CollectionUtils.isEmpty(ids)) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
// 删除预约日期表中与该商品关联的记录
QueryWrapper<AppointmentDate> queryWrapper = new QueryWrapper<>();
queryWrapper.in("goodId", ids);
boolean remove = appointmentDateService.remove(queryWrapper);
ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR, "服务类商品预约日期删除失败");
// 删除商品表中的服务类商品
boolean result = goodService.removeBatchByIds(ids);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "服务类商品删除失败");
return ResultUtils.success(true);
}
/**
* Web端管理员更新常规类商品
* @param goodUpdateRequest 商品更新请求体
* @return 是否更新成功
*/
@PostMapping("/update")
@Operation(summary = "Web端管理员更新商品", description = "参数:商品更新请求体,权限:管理员(admin, boss)方法名updateGoods")
@Operation(summary = "Web端管理员更新常规类商品", description = "参数:商品更新请求体,权限:管理员(admin, boss)方法名updateGoods")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> updateGoods(@RequestBody GoodUpdateRequest goodUpdateRequest) {
if (goodUpdateRequest == null || goodUpdateRequest.getId() <= 0) {
@ -196,19 +242,31 @@ public class GoodController {
/**
* 分页获取商品列表
* Web端管理员分页查询常规类商品
* @param goodQueryRequest 查询商品请求体
* @return 商品信息列表
*/
@PostMapping("/list/page")
@Operation(summary = "Web端管理员分页查询商品", description = "参数:商品查询请求体,排序字段 sortField: price inventory id权限管理员(admin, boss)方法名listGoodByPage")
@Operation(summary = "Web端管理员分页查询常规类商品", description = "参数:商品查询请求体,排序字段 sortField: price inventory id权限管理员(admin, boss)方法名listGoodByPage")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Page<Good>> listGoodByPage(@RequestBody GoodQueryRequest goodQueryRequest) {
public BaseResponse<Page<GoodPageVO>> listGoodByPage(@RequestBody GoodQueryRequest goodQueryRequest) {
long current = goodQueryRequest.getCurrent();
long pageSize = goodQueryRequest.getPageSize();
QueryWrapper<Good> goodQueryWrapper = goodService.getGoodQueryWrapper(goodQueryRequest);
Page<Good> page = goodService.page(new Page<>(current, pageSize), goodQueryWrapper);
return ResultUtils.success(page);
List<Good> records = page.getRecords();
List<GoodPageVO> goodPageVOS = records.stream().map(good -> {
GoodPageVO goodPageVO = new GoodPageVO();
BeanUtils.copyProperties(good, goodPageVO);
return goodPageVO;
}).toList();
Page<GoodPageVO> goodPageVOPage = new Page<>();
goodPageVOPage.setRecords(goodPageVOS);
goodPageVOPage.setTotal(page.getTotal());
goodPageVOPage.setSize(page.getSize());
goodPageVOPage.setCurrent(page.getCurrent());
goodPageVOPage.setPages(page.getPages());
return ResultUtils.success(goodPageVOPage);
}
@ -216,12 +274,12 @@ public class GoodController {
/**
* 批量删除商品
* Web端管理员批量删除常规类商品
* @param commonDelBatchRequest 批量删除请求体
* @return 是否批量删除成功
*/
@PostMapping("/delBatch")
@Operation(summary = "Web端管理员批量删除商品", description = "参数:商品批量删除请求体,权限:管理员(admin, boss)方法名delBatchGoods")
@Operation(summary = "Web端管理员批量删除常规类商品", description = "参数:商品批量删除请求体,权限:管理员(admin, boss)方法名delBatchGoods")
@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
public BaseResponse<Boolean> delBatchGoods(@RequestBody CommonDelBatchRequest commonDelBatchRequest) {
List<Long> idList = commonDelBatchRequest.getIdList();
@ -235,27 +293,28 @@ public class GoodController {
/**
* 根据id查询商品
* 小程序端用户根据id查询常规类商品
* @param getByIdRequest 根据id查询请求体
* @return 商品信息
*/
@PostMapping("/getById")
@Operation(summary = "根据id查询商品", description = "参数商品根据id查询请求体权限所有人, 方法名:getGoodById")
public BaseResponse<Good> getGoodById(@RequestBody CommonRequest getByIdRequest, HttpServletRequest request) {
@Operation(summary = "小程序端用户根据id查询常规类商品", description = "参数商品根据id查询请求体权限所有人, 方法名:getGoodById")
public BaseResponse<GoodPageVO> getGoodById(@RequestBody CommonRequest getByIdRequest) {
if (getByIdRequest == null || getByIdRequest.getId() <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
userService.getLoginUser(request);
Long id = getByIdRequest.getId();
Good good = goodService.getById(id);
ThrowUtils.throwIf(good == null, ErrorCode.NOT_FOUND_ERROR);
return ResultUtils.success(good);
GoodPageVO goodPageVO = new GoodPageVO();
BeanUtils.copyProperties(good, goodPageVO);
return ResultUtils.success(goodPageVO);
}
/**
* 分页获取服务类商品列表
* Web端管理员分页查询服务类商品
* @param goodQueryRequest 商品查询请求体
* @return 服务类商品列表
*/
@ -271,14 +330,34 @@ public class GoodController {
QueryWrapper<Good> goodQueryWrapper = goodService.getGoodQueryWrapper(goodQueryRequest);
Page<Good> page = goodService.page(new Page<>(current, pageSize), goodQueryWrapper);
List<Good> records = page.getRecords();
// 获取当天及未来三天的日期
List<String> dates = AppointmentDateUtil.getDates();
// 用map集合存储服务类商品关联的预约日期
List<AppointmentDate> appointmentDateList = appointmentDateService.list();
List<AppointmentDateVO> appointmentDateVOS = appointmentDateList.stream().map(appointmentDate -> {
AppointmentDateVO appointmentDateVO = new AppointmentDateVO();
BeanUtils.copyProperties(appointmentDate, appointmentDateVO);
return appointmentDateVO;
}).toList();
Map<Long, List<AppointmentDateVO>> map = new HashMap<>();
for (AppointmentDateVO appointmentDateVO : appointmentDateVOS) {
Long goodId = appointmentDateVO.getGoodId();
String specificDate = appointmentDateVO.getSpecificDate();
if (!dates.contains(specificDate)) continue;
List<AppointmentDateVO> dateVOList = map.get(goodId) != null ? map.get(goodId) : new ArrayList<>();
dateVOList.add(appointmentDateVO);
map.put(goodId, dateVOList);
}
List<ServiceGoodVO> serviceGoodVOList = records.stream().map(good -> {
ServiceGoodVO serviceGoodVO = new ServiceGoodVO();
BeanUtils.copyProperties(good, serviceGoodVO);
Long id = good.getId();
QueryWrapper<AppointmentDate> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("goodId", id);
List<AppointmentDate> list = appointmentDateService.list(queryWrapper);
serviceGoodVO.setAppointmentDateList(list);
List<AppointmentDateVO> appointmentDateVOList = map.get(id);
serviceGoodVO.setAppointmentDateVOS(appointmentDateVOList);
return serviceGoodVO;
}).toList();
Page<ServiceGoodVO> serviceGoodVOPage = new Page<>();
@ -293,7 +372,7 @@ public class GoodController {
/**
* 根据id查询服务类商品信息
* 小程序端用户根据id查询服务类商品
* @param commonRequest 根据id查询请求体
* @return 服务类商品信息
*/
@ -307,23 +386,31 @@ public class GoodController {
Long id = commonRequest.getId();
Good good = goodService.getById(id);
ThrowUtils.throwIf(good == null, ErrorCode.NOT_FOUND_ERROR, "商品不存在");
Integer isGoodType = good.getIsGoodType();
if (isGoodType == 1) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请求结果不是服务类商品");
}
ServiceGoodVO serviceGoodVO = new ServiceGoodVO();
BeanUtils.copyProperties(good, serviceGoodVO);
// 获取当天及未来三天的日期
List<String> dates = AppointmentDateUtil.getDates();
// 获取当前服务类商品关联的预约日期
QueryWrapper<AppointmentDate> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("goodId", id);
List<AppointmentDate> appointmentDateList = appointmentDateService.list(queryWrapper);
serviceGoodVO.setAppointmentDateList(appointmentDateList);
List<AppointmentDateVO> appointmentDateVOS = appointmentDateList.stream().map(appointmentDate -> {
AppointmentDateVO appointmentDateVO = new AppointmentDateVO();
BeanUtils.copyProperties(appointmentDate, appointmentDateVO);
return appointmentDateVO;
}).toList();
List<AppointmentDateVO> dateVOList = appointmentDateVOS.stream()
.filter(appointmentDateVO -> dates.contains(appointmentDateVO.getSpecificDate())).toList();
serviceGoodVO.setAppointmentDateVOS(dateVOList);
return ResultUtils.success(serviceGoodVO);
}
/**
* 展示服务类商品卡片
* 小程序端展示服务类商品卡片
* @return 服务类商品卡片列表
*/
@GetMapping("/service/list/card")
@ -342,8 +429,11 @@ public class GoodController {
}
/**
* 更新服务类商品
* Web端管理员更新服务类商品
* @param serviceGoodUpdateRequest 服务类商品更新请求体
* @return 是否更新成功
*/
@ -354,54 +444,32 @@ public class GoodController {
if (serviceGoodUpdateRequest == null || serviceGoodUpdateRequest.getId() <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
// 更新商品的基本信息
ServiceGoodVO serviceGoodVO = new ServiceGoodVO();
BeanUtils.copyProperties(serviceGoodUpdateRequest, serviceGoodVO);
// 更新服务类商品的基本信息
Good good = new Good();
BeanUtils.copyProperties(serviceGoodUpdateRequest, good);
good.setIsGoodType(0);
// 校验
goodService.validGood(serviceGoodVO, true);
boolean result = goodService.updateById(serviceGoodVO);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
goodService.validGood(good, true);
boolean result = goodService.updateById(good);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "商品不存在");
// 获取当前商品原有的预约日期列表
Long id = serviceGoodUpdateRequest.getId();
QueryWrapper<AppointmentDate> dateQueryWrapper = new QueryWrapper<>();
dateQueryWrapper.eq("goodId", id);
List<AppointmentDate> appointmentDates = appointmentDateService.list(dateQueryWrapper);
List<Long> dateIds = appointmentDates.stream().map(appointmentDate -> {
Long dateId = appointmentDate.getId();
return dateId;
}).toList();
// 获取当天及未来三天的日期
List<String> dates = AppointmentDateUtil.getDates();
AtomicInteger idx = new AtomicInteger(0);
// 获取需要更新的预约日期列表
// 封装预约日期实体类
List<AppointmentDateUpdateRequest> appointmentDateUpdateRequestList = serviceGoodUpdateRequest.getAppointmentDateUpdateRequestList();
List<Long> updateDateIds = appointmentDateUpdateRequestList.stream().map(appointmentDateUpdateRequest -> {
Long dateId = appointmentDateUpdateRequest.getId();
return dateId;
}).toList();
// 获取需要删除的预约日期id
List<Long> deleteIds = new ArrayList<>();
dateIds.forEach(dateId -> {
if (!updateDateIds.contains(dateId)) {
deleteIds.add(dateId);
}
});
// 如果存在需要删除的预约日期id, 就删除
if (!CollectionUtils.isEmpty(deleteIds)) {
boolean isSuccessDelete = appointmentDateService.removeBatchByIds(deleteIds);
ThrowUtils.throwIf(!isSuccessDelete, ErrorCode.OPERATION_ERROR);
}
// 更新当前商品的预约日期
List<AppointmentDate> appointmentDateList = appointmentDateUpdateRequestList.stream().map(appointmentDateUpdateRequest -> {
AppointmentDate appointmentDate = new AppointmentDate();
BeanUtils.copyProperties(appointmentDateUpdateRequest, appointmentDate);
appointmentDate.setGoodId(id);
appointmentDate.setSpecificDate(dates.get(idx.getAndIncrement()));
appointmentDate.setGoodId(good.getId());
// 校验
appointmentDateService.validAppointmentDate(appointmentDate, true);
return appointmentDate;
}).toList();
// 更新当前服务类商品的预约日期
boolean isSuccess = appointmentDateService.updateBatchById(appointmentDateList);
ThrowUtils.throwIf(!isSuccess, ErrorCode.OPERATION_ERROR);
return ResultUtils.success(true);
@ -410,6 +478,35 @@ public class GoodController {
/**
* (服务类商品)初始化未来一天的预约日期
*/
// @Scheduled(cron = "*/5 * * * * ?")
// 每天00:00-00:00调用
@Scheduled(cron = "0 0 0 * * ?")
@PostMapping("/service/init")
@Operation(summary = "(服务类商品)初始化未来一天的预约日期", description = "参数权限自动调用方法名initServiceGoodBookingDate")
@Transactional(rollbackFor = Exception.class)
public void initServiceGoodBookingDate() {
QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("isGoodType", 0);
List<Good> goodList = goodService.list(queryWrapper);
List<AppointmentDate> appointmentDateList = new ArrayList<>();
goodList.forEach(good -> {
AppointmentDate appointmentDate = new AppointmentDate();
appointmentDate.setGoodId(good.getId());
appointmentDate.setSpecificDate(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), 3)));
appointmentDate.setTimeSlot("00:00-00:00");
appointmentDate.setIsAvailable(0);
appointmentDate.setNumberRange("(0,0)");
appointmentDateList.add(appointmentDate);
});
boolean result = appointmentDateService.saveBatch(appointmentDateList);
ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "初始化失败");
}
}

View File

@ -7,15 +7,15 @@ import java.io.Serial;
import java.io.Serializable;
@Data
@Schema(description = "预约日期请求体", requiredProperties = {"specificDate", "timeSlot", "isAvailable", "minNumber", "maxNumber"})
@Schema(description = "预约日期请求体", requiredProperties = {"timeSlot", "isAvailable", "minNumber", "maxNumber"})
public class AppointmentDateAddRequest implements Serializable {
/**
* 预约具体日期
*/
@Schema(description = "预约具体日期", example = "2024-11-09")
private String specificDate;
// /**
// * 预约具体日期
// */
// @Schema(description = "预约具体日期", example = "2024-11-09")
// private String specificDate;
/**

View File

@ -16,11 +16,11 @@ public class AppointmentDateUpdateRequest implements Serializable {
private Long id;
/**
* 预约具体日期
*/
@Schema(description = "预约具体日期", example = "2024-11-09")
private String specificDate;
// /**
// * 预约具体日期
// */
// @Schema(description = "预约具体日期", example = "2024-11-09")
// private String specificDate;
/**

View File

@ -0,0 +1,30 @@
package com.cultural.heritage.model.dto.coupon;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
@Data
@Schema(description = "优惠券上架状态更新请求体", requiredProperties = {"id", "isShelves"})
public class CouponShelvesUpdateRequest implements Serializable {
/**
* 订单id
*/
@Schema(description = "优惠券id(id > 0)", example = "8")
private Long id;
/**
* 优惠券上架状态
*/
@Schema(description = "优惠券上架状态", example = "1")
private Integer isShelves;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -92,6 +92,13 @@ public class CouponUpdateRequest implements Serializable {
private String description;
/**
* 是否上架
*/
@Schema(description = "是否上架", example = "1")
private Integer isShelves;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -27,12 +27,6 @@ public class ExchangeAddRequest implements Serializable {
@Schema(description = "购买数量", example = "10")
private Integer quantity;
/**
* 优惠券积分价格
*/
@Schema(description = "优惠券积分价格", example = "2000")
private Integer requirePoints;
@Serial
private static final long serialVersionUID = 1L;

View File

@ -7,6 +7,7 @@ import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* 预约日期表
@ -54,6 +55,22 @@ public class AppointmentDate implements Serializable {
private Long goodId;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 是否删除
*/
private Integer isDelete;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -92,6 +92,13 @@ public class Coupon implements Serializable {
*/
private String description;
/**
* 是否上架
*/
private Integer isShelves;
/**
* 创建时间
*/

View File

@ -1,8 +1,11 @@
package com.cultural.heritage.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.cultural.heritage.model.vo.coupon.CouponVO;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@ -15,7 +18,7 @@ import java.util.Date;
* @TableName exchange_record
*/
@Data
@TableName("exchange_record")
@TableName(value = "exchange_record", autoResultMap = true)
public class Exchange implements Serializable {
@ -30,16 +33,31 @@ public class Exchange implements Serializable {
*/
private Long userId;
/**
* 优惠券id
*/
private Long couponId;
/**
* 优惠券信息
*/
@TableField(typeHandler = JacksonTypeHandler.class)
private CouponVO couponDetail;
/**
* 数量
*/
private Integer quantity;
/**
* 剩余数量
*/
private Integer restNum;
/**
* 优惠券积分价格
*/

View File

@ -0,0 +1,49 @@
package com.cultural.heritage.model.vo.appointment;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
@Data
public class AppointmentDateVO implements Serializable {
/**
* 预约日期id
*/
private Long id;
/**
* 预约具体日期
*/
private String specificDate;
/**
* 预约时间段
*/
private String timeSlot;
/**
* 是否可预约
*/
private Integer isAvailable;
/**
* 预约人数范围
*/
private String numberRange;
/**
* 商品id
*/
private Long goodId;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,59 @@
package com.cultural.heritage.model.vo.coupon;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
public class CouponVO implements Serializable {
/**
* 优惠券名称
*/
private String name;
/**
* 满减金额
*/
private BigDecimal conditionAmount;
/**
* 优惠券简介
*/
private String intro;
/**
* 优惠券图片
*/
private String image;
/**
* 有效开始日期
*/
private String startTime;
/**
* 有效截止日期
*/
private String endTime;
/**
* 作用范围
*/
private String useScope;
/**
* 使用说明
*/
private String description;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,69 @@
package com.cultural.heritage.model.vo.exchange;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.cultural.heritage.model.vo.coupon.CouponVO;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
@Data
public class ExchangeVO implements Serializable {
/**
* 兑换记录id
*/
private Long id;
/**
* 优惠券id
*/
private Long couponId;
/**
* 优惠券信息
*/
@TableField(typeHandler = JacksonTypeHandler.class)
private CouponVO couponDetail;
/**
* 数量
*/
private Integer quantity;
/**
* 剩余数量
*/
private Integer restNum;
/**
* 优惠券积分价格
*/
private Integer requirePoints;
/**
* 优惠券状态(未开始可使用已过期)
*/
private String couponStatus;
/**
* 创建时间
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,82 @@
package com.cultural.heritage.model.vo.good;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
public class GoodPageVO implements Serializable {
/**
* 商品编号
*/
private Long id;
/**
* 商品名
*/
private String name;
/**
* 商品类型
*/
private String type;
/**
* 商品价格
*/
private BigDecimal price;
/**
* 商品图片
*/
private String goodImg;
/**
* 商品简介
*/
private String intro;
/**
* 商品详情简介
*/
private String introDetail;
/**
* 商品详情图片
*/
private String detailImg;
/**
* 商品标签
*/
private String label;
/**
* 商品库存量
*/
private Integer inventory;
/**
* 是否是商品类型
*/
private Integer isGoodType;
/**
* 节日限定序号
*/
private Integer festivalOrder;
/**
* 是否上架
*/
private Integer isShelves;
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -1,7 +1,6 @@
package com.cultural.heritage.model.vo.good;
import com.cultural.heritage.model.entity.AppointmentDate;
import com.cultural.heritage.model.entity.Good;
import com.cultural.heritage.model.vo.appointment.AppointmentDateVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@ -10,14 +9,14 @@ import java.io.Serializable;
import java.util.List;
@Data
public class ServiceGoodVO extends Good implements Serializable {
public class ServiceGoodVO extends GoodPageVO implements Serializable {
/**
* 未来几天的预约详情
*/
@Schema(description = "未来几天的预约详情")
private List<AppointmentDate> appointmentDateList;
private List<AppointmentDateVO> appointmentDateVOS;
@Serial

View File

@ -0,0 +1,23 @@
package com.cultural.heritage.utils;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.util.ArrayList;
import java.util.List;
public class AppointmentDateUtil {
// 将当天及未来三天的日期加入到集合中
public static List<String> getDates() {
List<String> dates = new ArrayList<>();
for (int i = 0; i < 4; i ++ ) {
DateTime date = DateUtil.date();
DateTime dateTime = DateUtil.offsetDay(date, i);
String formatDate = DateUtil.formatDate(dateTime);
dates.add(formatDate);
}
return dates;
}
}

View File

@ -1,162 +1,38 @@
package com.cultural.heritage.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 反射处理Bean得到里面的属性值
*
* @author liulinsen
*
*/
public class ReflexObjectUtil {
/**
* 单个对象的所有键值
*
* 单个对象
*
* @return Map<String, Object> map 所有 String键 Object值 ex{pjzyfy=0.00,
* xh=01, zzyl=0.00, mc=住院患者压疮发生率, pjypfy=0.00, rs=0, pjzyts=0.00,
* czydm=0037, lx=921, zssl=0.00}
*/
public static Map<String, Object> getKeyAndValue(Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<>();
// 得到类对象
Class userCla = (Class) obj.getClass();
Class userCla = obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
Object val = new Object();
Object val;
try {
val = f.get(obj);
// 得到此属性的值
map.put(f.getName(), val);// 设置键值
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
/*
* String type = f.getType().toString();//得到此属性的类型 if
* (type.endsWith("String")) {
* System.out.println(f.getType()+"\t是String"); f.set(obj,"12") ;
* //给属性设值 }else if(type.endsWith("int") ||
* type.endsWith("Integer")){
* System.out.println(f.getType()+"\t是int"); f.set(obj,12) ; //给属性设值
* }else{ System.out.println(f.getType()+"\t"); }
*/
}
System.out.println("单个对象的所有键值==反射==" + map.toString());
System.out.println("单个对象的所有键值==反射==" + map);
return map;
}
/**
* 单个对象的某个键的值
*
* 对象
*
* @param key
*
*
* @return Object 键在对象中所对应得值 没有查到时返回空字符串
*/
public static Object getValueByKey(Object obj, String key) {
// 得到类对象
Class userCla = (Class) obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
try {
if (f.getName().endsWith(key)) {
System.out.println("单个对象的某个键的值==反射==" + f.get(obj));
return f.get(obj);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 没有查到时返回空字符串
return "";
}
/**
*
* @param object
* @return
*/
public static List<Map<String, Object>> getKeysAndValues(List<Object> object) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Object obj : object) {
Class userCla;
// 得到类对象
userCla = (Class) obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
Map<String, Object> listChild = new HashMap<String, Object>();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
Object val = new Object();
try {
val = f.get(obj);
// 得到此属性的值
listChild.put(f.getName(), val);// 设置键值
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
list.add(listChild);// 将map加入到list集合中
}
System.out.println("多个(列表)对象的所有键值====" + list.toString());
return list;
}
/**
* 多个列表对象的某个键的值
*
* @param object
* @param key
* @return List<Object> 键在列表中对应的所有值 ex:key为上面方法中的mc字段 那么返回的数据就是 [住院患者压疮发生率,
* 新生儿产伤发生率, 阴道分娩产妇产伤发生率, 输血反应发生率, 剖宫产率]
*/
public static List<Object> getValuesByKey(List<Object> object, String key) {
List<Object> list = new ArrayList<Object>();
for (Object obj : object) {
// 得到类对象
Class userCla = (Class) obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
try {
if (f.getName().endsWith(key)) {
list.add(f.get(obj));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
System.out.println("多个(列表)对象的某个键的值列表====" + list.toString());
return list;
}
}

View File

@ -1,6 +1,7 @@
package com.cultural.heritage.test;
import java.math.BigDecimal;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
public class Test {
public static void main(String[] args) {
@ -24,8 +25,19 @@ public class Test {
// System.out.println(StringUtils.isAnyBlank("333", "333", null, "dfs"));
// System.out.println(StringUtils.isAnyBlank(null));
// System.out.println(ObjectUtils.anyNull(null));
Integer quantity = 10;
BigDecimal bigDecimal = BigDecimal.valueOf(quantity);
System.out.println(bigDecimal);
// Integer quantity = 10;
// BigDecimal bigDecimal = BigDecimal.valueOf(quantity);
// System.out.println(bigDecimal);
DateTime date = DateUtil.date();
System.out.println(date);
String formatDate = DateUtil.formatDate(date);
System.out.println(formatDate);
// String str = "2024-11-21 22:43:33";
// DateTime parse = DateUtil.parse(str);
// System.out.println(parse);
}
}