用户优惠券 代码优化

This commit is contained in:
Jack 2026-02-05 21:15:07 +08:00
parent 8c3e76ab1d
commit 747c68686f
3 changed files with 98 additions and 52 deletions

View File

@ -1,9 +1,6 @@
package com.suisung.mall.common.modules.store; package com.suisung.mall.common.modules.store;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
@ -82,9 +79,9 @@ public class ShopStoreActivityBase implements Serializable {
@TableField(updateStrategy = NOT_EMPTY) @TableField(updateStrategy = NOT_EMPTY)
private Integer activity_state; private Integer activity_state;
@ApiModelProperty(value = "活动规则(json):不检索{rule_id:{}, rule_id:{}}") @ApiModelProperty(value = "活动规则(json):不检索{rule_id:{}, rule_id:{}},统一解析规则{\"requirement\":{\"buy\":{\"item\":[1,2,3],\"subtotal\":\"通过计算修正满足的条件\"}},\"rule\":[{\"total\":100,\"max_num\":1,\"item\":{\"1\":1,\"1200\":3}},{\"total\":200,\"max_num\":1,\"item\":{\"1\":1,\"1200\":3}}]}")
@TableField(updateStrategy = NOT_EMPTY) @TableField(updateStrategy = NOT_EMPTY, fill = FieldFill.INSERT_UPDATE)
private String activity_rule; private String activity_rule = "{}";
@ApiModelProperty(value = "参与类型(ENUM):1-免费参与;2-积分参与;3-购买参与") @ApiModelProperty(value = "参与类型(ENUM):1-免费参与;2-积分参与;3-购买参与")
@TableField(updateStrategy = NOT_EMPTY) @TableField(updateStrategy = NOT_EMPTY)
@ -139,7 +136,6 @@ public class ShopStoreActivityBase implements Serializable {
@TableField(updateStrategy = NOT_EMPTY) @TableField(updateStrategy = NOT_EMPTY)
private String lucky_turn; private String lucky_turn;
@ApiModelProperty(value = "每人限购,0为不限购") @ApiModelProperty(value = "每人限购,0为不限购")
private Integer person_limit; private Integer person_limit;

View File

@ -1453,30 +1453,64 @@ public class ShopStoreBaseServiceImpl extends BaseServiceImpl<ShopStoreBaseMappe
/** /**
* 嵌入店铺信息 * 嵌入店铺信息
* *
* @param rows * @param rows 待处理的数据列表
*/ */
@Override @Override
public void fixStoreData(List<Map> rows) { public void fixStoreData(List<Map> rows) {
// 空值检查
if (CollUtil.isNotEmpty(rows)) { if (CollUtil.isEmpty(rows)) {
List<Integer> store_ids = rows.stream().map(s -> Convert.toInt(s.get("store_id"))).distinct().collect(Collectors.toList()); return;
List<Map> store_rows = gets(store_ids);
for (Map row : rows) {
Integer store_id = Convert.toInt(row.get("store_id"));
Optional<Map> storeOpl = store_rows.stream().filter(s -> ObjectUtil.equal(store_id, Convert.toInt(s.get("store_id")))).findFirst();
if (storeOpl.isPresent()) {
Map store = storeOpl.get();
row.put("store_name", store.get("store_name"));
continue;
} }
row.put("store_name", "(无)"); // 默认值常量
} final String DEFAULT_STORE_NAME = "(无)";
try {
// 提取所有唯一的 store_id
List<Integer> storeIds = rows.stream()
.map(row -> Convert.toInt(row.get("store_id")))
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
// 如果没有有效的 store_id直接填充默认值
if (storeIds.isEmpty()) {
rows.forEach(row -> row.put("store_name", DEFAULT_STORE_NAME));
return;
}
// 批量获取店铺信息异常处理
List<Map> storeRows;
try {
storeRows = gets(storeIds);
} catch (Exception e) {
log.warn("获取店铺信息失败使用默认值填充。storeIds: {}", storeIds, e);
storeRows = Collections.emptyList(); // 异常时返回空列表
}
// 构建 store_id store_name 的映射
Map<Integer, String> storeNameMap = storeRows.stream()
.collect(Collectors.toMap(
row -> Convert.toInt(row.get("store_id")),
row -> Convert.toStr(row.get("store_name"), DEFAULT_STORE_NAME),
(existing, replacement) -> existing // 避免重复键冲突
));
// 填充每行的店铺名称
rows.forEach(row -> {
Integer storeId = Convert.toInt(row.get("store_id"));
String storeName = storeNameMap.getOrDefault(storeId, DEFAULT_STORE_NAME);
row.put("store_name", storeName);
});
} catch (Exception e) {
// 兜底处理如果整个流程出现异常统一填充默认值
log.error("处理店铺信息时发生未知异常,统一填充默认值。", e);
rows.forEach(row -> row.put("store_name", DEFAULT_STORE_NAME));
} }
} }
@Override @Override
public Map getBaseList(QueryWrapper<ShopStoreBase> queryWrapper, Integer pageNum, Integer pageSize) { public Map getBaseList(QueryWrapper<ShopStoreBase> queryWrapper, Integer pageNum, Integer pageSize) {

View File

@ -42,6 +42,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.suisung.mall.common.utils.ContextUtil.getCurrentUser; import static com.suisung.mall.common.utils.ContextUtil.getCurrentUser;
@ -76,6 +77,13 @@ public class ShopUserVoucherServiceImpl extends BaseServiceImpl<ShopUserVoucherM
@Autowired @Autowired
private PayService payService; private PayService payService;
/**
* 获取用户某些指定优惠券的数量
*
* @param activity_ids
* @param user_id
* @return
*/
@Override @Override
public Map getActivityTotalVoucher(List<Integer> activity_ids, Integer user_id) { public Map getActivityTotalVoucher(List<Integer> activity_ids, Integer user_id) {
Map<String, Object> queryMap = new HashMap<>(); Map<String, Object> queryMap = new HashMap<>();
@ -157,59 +165,70 @@ public class ShopUserVoucherServiceImpl extends BaseServiceImpl<ShopUserVoucherM
return data; return data;
} }
/**
* 会员积分日志列表数据
*
* @return
*/
@Override @Override
public Map getList() { public Map getList() {
// 获取当前用户信息
UserDto user = getCurrentUser(); UserDto user = getCurrentUser();
if (user == null) { if (user == null) {
throw new ApiUserException(I18nUtil._("用户信息异常!")); throw new ApiUserException(I18nUtil._("用户信息异常!"));
} }
Integer user_id = user.getId(); Integer userId = user.getId();
Integer page = getParameter("page", 1);
Integer rows = getParameter("rows", 10);
// 分页参数校验与默认值设置
Integer page = Math.max(1, getParameter("page", 1)); // 保证页码 >= 1
Integer rows = Math.min(100, Math.max(1, getParameter("rows", 10))); // 限制每页最大记录数为100
// 构建查询条件
QueryWrapper<ShopUserVoucher> queryWrapper = new QueryWrapper<>(); QueryWrapper<ShopUserVoucher> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", user_id); queryWrapper.eq("user_id", userId);
Integer store_id = getParameter("store_id", Integer.class); // 店铺ID筛选
if (CheckUtil.isNotEmpty(store_id)) { Integer storeId = getParameter("store_id", Integer.class);
queryWrapper.eq("store_id", store_id); if (CheckUtil.isNotEmpty(storeId)) {
queryWrapper.eq("store_id", storeId);
} }
// 处理全部券1线下券2线上券3
// 券类型筛选全部券1线下券2线上券3
String offisonParam = getParameter("offison"); String offisonParam = getParameter("offison");
if (StrUtil.isNotBlank(offisonParam)) { if (StrUtil.isNotBlank(offisonParam)) {
int offison = Convert.toInt(offisonParam); int offison = Convert.toInt(offisonParam);
switch (offison) {
case 2: // 使用 Map 映射券类型对应的筛选条件
queryWrapper.ne("writeoff_code", ""); Map<Integer, Consumer<QueryWrapper<ShopUserVoucher>>> filterMap = new HashMap<>();
break; filterMap.put(2, wrapper -> wrapper.ne("writeoff_code", "")); // 线下券
case 3: filterMap.put(3, wrapper -> wrapper.eq("writeoff_code", "")); // 线上券
queryWrapper.eq("writeoff_code", "");
break; // 根据券类型应用筛选条件
} filterMap.getOrDefault(offison, wrapper -> {
}).accept(queryWrapper);
} }
Integer voucher_state_id = getParameter("voucher_state_id", Integer.class); // 券状态筛选
if (CheckUtil.isNotEmpty(voucher_state_id)) { Integer voucherStateId = getParameter("voucher_state_id", Integer.class);
queryWrapper.eq("voucher_state_id", voucher_state_id); if (CheckUtil.isNotEmpty(voucherStateId)) {
queryWrapper.eq("voucher_state_id", voucherStateId);
} }
// 排序
queryWrapper.orderByDesc("user_voucher_id"); queryWrapper.orderByDesc("user_voucher_id");
// 执行分页查询
Map data = getLists(queryWrapper, page, rows); Map data = getLists(queryWrapper, page, rows);
List<Map> items = (List<Map>) data.get("items"); List<Map> items = (List<Map>) data.get("items");
// 数据后处理
if (CollUtil.isNotEmpty(items)) {
// 嵌入店铺信息
shopStoreBaseService.fixStoreData(items); shopStoreBaseService.fixStoreData(items);
for (Map item : items) {
item.put("id", item.get("user_voucher_id")); // 添加统一ID字段
items.forEach(item -> item.put("id", item.get("user_voucher_id")));
} }
return data; return data;
} }
@Override @Override
public Map getVoucher(Integer activity_id, Integer user_voucher_id) { public Map getVoucher(Integer activity_id, Integer user_voucher_id) {
@ -268,7 +287,6 @@ public class ShopUserVoucherServiceImpl extends BaseServiceImpl<ShopUserVoucherM
// 权限判断 // 权限判断
data = addVoucher(data); data = addVoucher(data);
activity_row.remove("activity_rule"); activity_row.remove("activity_rule");
data.putAll(activity_row); data.putAll(activity_row);
@ -404,7 +422,6 @@ public class ShopUserVoucherServiceImpl extends BaseServiceImpl<ShopUserVoucherM
Date voucher_start_date = Convert.toDate(json_activity_rule.get("voucher_start_date")); Date voucher_start_date = Convert.toDate(json_activity_rule.get("voucher_start_date"));
Date voucher_end_date = Convert.toDate(json_activity_rule.get("voucher_end_date")); Date voucher_end_date = Convert.toDate(json_activity_rule.get("voucher_end_date"));
if (NumberUtil.add(voucher_quantity, voucher_quantity_free).intValue() <= 0) { if (NumberUtil.add(voucher_quantity, voucher_quantity_free).intValue() <= 0) {
throw new ApiException(I18nUtil._("代金券已经被抢完,领取失败!")); throw new ApiException(I18nUtil._("代金券已经被抢完,领取失败!"));
} }
@ -478,7 +495,6 @@ public class ShopUserVoucherServiceImpl extends BaseServiceImpl<ShopUserVoucherM
storeActivityBase.setActivity_state(StateCode.ACTIVITY_STATE_FINISHED); storeActivityBase.setActivity_state(StateCode.ACTIVITY_STATE_FINISHED);
} }
// 优惠券低于库存设定额提醒 // 优惠券低于库存设定额提醒
if (NumberUtil.add(voucher_quantity, _voucher_quantity_free).intValue() <= 5) { if (NumberUtil.add(voucher_quantity, _voucher_quantity_free).intValue() <= 5) {
String message_id = "coupon-is-below-stock-alert"; String message_id = "coupon-is-below-stock-alert";