package com.stylefeng.guns.core.intercept;
|
|
import com.stylefeng.guns.modular.system.dao.TravelCardMapper;
|
import com.stylefeng.guns.modular.system.dao.UserInfoMapper;
|
import com.stylefeng.guns.modular.system.model.UserInfo;
|
import com.stylefeng.guns.modular.system.model.vo.BalanceModifyRecordVo;
|
import org.apache.ibatis.javassist.bytecode.analysis.Executor;
|
import org.apache.ibatis.mapping.BoundSql;
|
import org.apache.ibatis.mapping.MappedStatement;
|
import org.apache.ibatis.mapping.SqlCommandType;
|
import org.apache.ibatis.plugin.Interceptor;
|
import org.apache.ibatis.plugin.Intercepts;
|
import org.apache.ibatis.plugin.Invocation;
|
import org.apache.ibatis.plugin.Signature;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
|
import java.lang.reflect.Field;
|
import java.util.Map;
|
import java.util.Objects;
|
import java.util.Properties;
|
|
/**
|
* 用户余额变更拦截器
|
* @author sky
|
* @version 1.0.0
|
* @since 2026/7/3 12:03
|
*/
|
@Component
|
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
|
public class BalanceUpdateInterceptor implements Interceptor {
|
|
@Autowired
|
private UserInfoMapper userInfoMapper;
|
|
@Autowired
|
private TravelCardMapper travelCardMapper;
|
|
@Override
|
public Object intercept(Invocation invocation) throws Throwable {
|
|
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
|
Object param = invocation.getArgs()[1];
|
|
// 获取SQL类型
|
SqlCommandType sqlCommandType = ms.getSqlCommandType();
|
|
if (sqlCommandType != SqlCommandType.UPDATE) {
|
return invocation.proceed();
|
}
|
BoundSql boundSql = ms.getBoundSql(param);
|
String sql = boundSql.getSql().toLowerCase();
|
|
// 只处理 user 表
|
if (!sql.contains("t_user")) {
|
return invocation.proceed();
|
}
|
|
// 关键:先执行前查旧值(需要拿 userId)
|
Long userId = extractUserId(param);
|
// 查询旧的用户
|
UserInfo oldUser = userInfoMapper.selectById(userId);
|
// 执行更新
|
Object result = invocation.proceed();
|
// 查新的用户
|
UserInfo newUser = userInfoMapper.selectById(userId);
|
|
// 新增余额的变更记录(所有余额的变更记录都需要存)
|
if(Objects.nonNull(oldUser) && Objects.nonNull(newUser)) {
|
travelCardMapper.insertBalanceModifyRecord(BalanceModifyRecordVo.convert(oldUser, newUser));
|
}
|
return result;
|
}
|
|
@Override
|
public Object plugin(Object target) {
|
return null;
|
}
|
|
@Override
|
public void setProperties(Properties properties) {
|
|
}
|
|
/**
|
* 获取用户id
|
*/
|
private Long extractUserId(Object param) {
|
// 兼容 Map / entity / wrapper
|
if (param instanceof Map) {
|
Object id = ((Map<?, ?>) param).get("id");
|
return id == null ? null : Long.valueOf(id.toString());
|
}
|
|
try {
|
Field f = param.getClass().getDeclaredField("id");
|
f.setAccessible(true);
|
return (Long) f.get(param);
|
} catch (Exception e) {
|
return null;
|
}
|
}
|
|
}
|