之前在做项目时有个需求是需要记录用户每次操作单据后单据每个字段的变更情况,最开始想的是通过反射机制纯后端来实现,但是后来发现在某些复杂的情况下如字段的值为JSON时,纯靠后端比较不准确,所以后面想了一下还是得由前端辅助来实现,现记录一下实现方法,该方法可能不是最简便的方法,如果觉得这个方法有问题或者有更简便的思路欢迎各位大佬探讨
这是接口接收的数据结构
@Data
public class EventDTO {
@ApiModelProperty(value = "修改之前的字段集合")
private List<EventDetailDTO> before;
@ApiModelProperty(value = "修改之后的字段集合")
private List<EventDetailDTO> after;
}
@Data
public class EventDetailDTO {
private String key;
private String value;
}
这部分是日志生成的代码
@Slf4j
public class EventUtil {
public static List<EventResultDTO> eventRecord(List<EventDTO> events, Boolean eventFlag){
List<EventResultDTO> result = new ArrayList<>();
for (EventDTO event : events){
if(null == event.getBefore()){
event.setBefore(new ArrayList<>());
}
if(null == event.getAfter()){
event.setAfter(new ArrayList<>());
}
EventResultDTO dto = new EventResultDTO();
List<String> contents = new ArrayList<>();
dto.setModelName(event.getModelName());
Iterator<EventDetailDTO> after = event.getAfter().iterator();
while (after.hasNext()){
EventDetailDTO afterDetail = after.next();
// 根据key匹配修改前的事件记录集合
EventDetailDTO match = event.getBefore().stream()
.filter(e->e.getKey().equals(afterDetail.getKey()))
.findFirst().orElse(new EventDetailDTO());
// 比较value值生成事件记录
String content = eventCreate(afterDetail.getKey(), match.getValue(), afterDetail.getValue(),eventFlag);
contents.add(content);
after.remove();
event.getBefore().remove(match);
}
if (CollUtil.isEmpty(event.getAfter())){
for (EventDetailDTO beforeDetail : event.getBefore()){
// 比较value值生成事件记录
String content = eventCreate(beforeDetail.getKey(), beforeDetail.getValue(),null,eventFlag);
contents.add(content);
}
}
dto.setContents(contents);
result.add(dto);
}
return result;
}
private static String eventCreate(String title, String before, String after, Boolean eventFlag){
String content = "";
String s1 = "";
String s2 = "";
String s3 = "";
String s4 = "";
title = title.split("_")[0];
if (StrUtil.isNotBlank(before) && StrUtil.isBlank(after)){
content = "删除"+title+"\"{}"+before+"{}\"";
if (!eventFlag){
s1 = "<span style='text-decoration: line-through;'>";
s2 = "</span>";
}
}else if (StrUtil.isNotBlank(after) && StrUtil.isBlank(before)){
content = "新增"+title+"\"{}"+after+"{}\"";
if (!eventFlag){
s1 = "<span style='color:rgba(112, 182, 3, 0.901960784313726);'>";
s2 = "</span>";
}
}else {
content = title+"由"+"\"{}"+before+"{}\""+"变更为"+"{}\""+after+"{}\"";
if (!eventFlag){
s1 = "<span style='color:rgba(217, 0, 27, 0.901960784313726);'>";
s2 = "</span>";
s3 = "<span style='color:rgba(112, 182, 3, 0.901960784313726);'>";
s4 = "</span>";
}
}
content = StrUtil.format(content,s1,s2,s3,s4);
return content;
}
}