历史记录后端

main
liulianbuqu 2 months ago
parent 5e2956da8d
commit 81ed1db029

@ -0,0 +1,58 @@
package com.learning.newdemo.controller;
import com.learning.newdemo.common.Result;
import com.learning.newdemo.entity.DebateHistory;
import com.learning.newdemo.service.DebateHistoryService;
import com.learning.newdemo.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* HTTP
*/
@RestController // 标识为RESTful控制器
@RequestMapping("/api/debate-history") // 基础请求路径
@RequiredArgsConstructor // Lombok注解自动生成构造函数注入依赖
public class DebateHistoryController {
// 依赖注入
private final DebateHistoryService historyService;
private final JwtUtil jwtUtil;
/**
*
* @param history
* @param token
* @return
*/
@PostMapping // 处理POST请求
public Result<?> saveHistory(@RequestBody DebateHistory history,
@RequestHeader("Authorization") String token) {
// 从JWT令牌中解析用户ID
Integer userId = jwtUtil.getUserIdFromToken(token);
// 设置记录关联的用户ID
if (userId == null) {
return Result.error(401, "无效的认证令牌");
}
history.setUserId(userId);
// 调用服务层保存记录
historyService.saveDebateHistory(history);
// 返回成功响应
return Result.success();
}
/**
*
* @param token
* @return
*/
@GetMapping // 处理GET请求
public Result<List<DebateHistory>> getHistories(@RequestHeader("Authorization") String token) {
Integer userId = jwtUtil.getUserIdFromToken(token);
// 调用服务层获取记录并包装返回
return Result.success(historyService.getHistoriesByUser(userId));
}
}

@ -1,59 +1,95 @@
package com.learning.newdemo.mapper;
import com.learning.newdemo.entity.DebateHistory;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 访
*
*/
public interface DebateHistoryMapper {
/**
*
* @param debateHistory
* @return
*
* @param debateHistory
* @return 1
*/
@Insert("INSERT INTO debate_history(user_id, argument_id, topic, position, total_rounds, debate_content, review_result) " +
"VALUES(#{userId}, #{argumentId}, #{topic}, #{position}, #{totalRounds}, #{debateContent}, #{reviewResult})")
@Options(useGeneratedKeys = true, keyProperty = "id") // 获取自增主键
int insert(DebateHistory debateHistory);
/**
* ID
* @param userId ID
* @return
* ID
* @param userId
* @return
*/
@Select("SELECT * FROM debate_history WHERE user_id = #{userId} ORDER BY create_time DESC")
List<DebateHistory> selectByUserId(@Param("userId") Integer userId);
/**
* IDi
*
* @param userId ID
* @param limit
* @return i
* @param limit
* @return
*/
@Select("SELECT * FROM debate_history WHERE user_id = #{userId} ORDER BY create_time DESC LIMIT #{limit}")
List<DebateHistory> selectLatestByUserId(@Param("userId") Integer userId, @Param("limit") Integer limit);
/**
* ID
* ID
* @param argumentId ID
* @return
* @return
*/
@Select("SELECT * FROM debate_history WHERE argument_id = #{argumentId} ORDER BY create_time DESC")
List<DebateHistory> selectByArgumentId(@Param("argumentId") Integer argumentId);
/**
*
* @param id ID
* @return
* ID
* @param id ID
* @return
*/
@Select("SELECT * FROM debate_history WHERE id = #{id}")
DebateHistory selectByPrimaryKey(@Param("id") Integer id);
/**
*
* @param id ID
* @param reviewResult
* @return
*
* @param id ID
* @param reviewResult
* @return
*/
@Update("UPDATE debate_history SET review_result = #{reviewResult} WHERE id = #{id}")
int updateReviewResult(@Param("id") Integer id, @Param("reviewResult") String reviewResult);
/**
*
*
* @param id ID
* @return
* @return
*/
@Select("SELECT dh.*, ah.topic AS argument_topic, ah.argument_content " +
"FROM debate_history dh LEFT JOIN argument_history ah ON dh.argument_id = ah.id " +
"WHERE dh.id = #{id}")
DebateHistory selectWithArgument(@Param("id") Integer id);
/**
* 10
* @param userId ID
* @return
*/
@Delete("DELETE FROM debate_history WHERE user_id = #{userId} AND id NOT IN " +
"(SELECT id FROM (SELECT id FROM debate_history WHERE user_id = #{userId} " +
"ORDER BY create_time DESC LIMIT 10) t)")
int cleanOverflowHistories(@Param("userId") Integer userId);
/**
*
* @param userId ID
* @param keyword
* @return
*/
@Select("SELECT * FROM debate_history WHERE user_id = #{userId} AND topic LIKE CONCAT('%',#{keyword},'%') " +
"ORDER BY create_time DESC")
List<DebateHistory> searchByKeyword(@Param("userId") Integer userId, @Param("keyword") String keyword);
}

@ -0,0 +1,9 @@
package com.learning.newdemo.service;
import com.learning.newdemo.entity.DebateHistory;
import java.util.List;
public interface DebateHistoryService {
void saveDebateHistory(DebateHistory history);
List<DebateHistory> getHistoriesByUser(Integer userId);
}

@ -0,0 +1,31 @@
// DebateHistoryServiceImpl.java
package com.learning.newdemo.service.impl;
import com.learning.newdemo.entity.DebateHistory;
import com.learning.newdemo.mapper.DebateHistoryMapper;
import com.learning.newdemo.service.DebateHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@RequiredArgsConstructor
@Transactional
public class DebateHistoryServiceImpl implements DebateHistoryService {
private final DebateHistoryMapper historyMapper;
@Override
public void saveDebateHistory(DebateHistory history) {
historyMapper.insert(history);
// 清理超出10条的旧记录
historyMapper.cleanOverflowHistories(history.getUserId());
}
@Override
public List<DebateHistory> getHistoriesByUser(Integer userId) {
return historyMapper.selectLatestByUserId(userId, 10);
}
}

@ -109,4 +109,31 @@ public class JwtUtil {
byte[] keyBytes = Decoders.BASE64.decode(secret);
return Keys.hmacShaKeyFor(keyBytes);
}
/**
* TokenClaims
* @param token JWT
* @return Claims
*/
public Claims parseToken(String token) {
// 去除可能的"Bearer "前缀
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7);
}
return getClaimsFromToken(token);
}
/**
* tokenID
* @param token JWT
* @return ID
*/
public Integer getUserIdFromToken(String token) {
try {
Claims claims = parseToken(token);
return claims.get("userId", Integer.class);
} catch (Exception e) {
return null;
}
}
}

@ -1,6 +1,6 @@
create database if not exists wx_miniapp default charset utf8mb4;
create database if not exists wx_miniApp default charset utf8mb4;
use wx_miniapp;
use wx_miniApp;
CREATE TABLE IF NOT EXISTS `wx_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
@ -16,4 +16,20 @@ CREATE TABLE IF NOT EXISTS `wx_user` (
`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_openid` (`openid`) COMMENT 'openid唯一索引'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信用户表';
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信用户表';
-- 在现有database.sql文件末尾添加不要删除原有内容
CREATE TABLE IF NOT EXISTS `debate_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '关联用户ID',
`topic` varchar(255) NOT NULL COMMENT '辩题',
`stance` enum('正方','反方') NOT NULL COMMENT '持方',
`content` text COMMENT '辩论内容JSON',
`review` text COMMENT 'AI复盘内容',
`rounds` smallint(6) DEFAULT 0 COMMENT '辩论轮数',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_user_time` (`user_id`, `create_time`),
CONSTRAINT `fk_user_history` FOREIGN KEY (`user_id`) REFERENCES `wx_user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='辩论历史记录表';

@ -0,0 +1,31 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
projectJDK: 17 #(Applied in CI/CD pipeline)
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-jvm-community:latest
Loading…
Cancel
Save