历史记录后端

main
liulianbuqu 2 months ago
parent dbdd037ed7
commit 4d9b5a2e69

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

@ -0,0 +1,112 @@
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.service.WxReviewService;
import com.learning.newdemo.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("api/review")
public class ReviewHistoryController {
private final WxReviewService wxReviewService;
private final DebateHistoryService historyService;
private final JwtUtil jwtUtil;
@PostMapping("/auto-save")
public Result<Map<String, Object>> autoSaveReview(
@RequestBody Map<String, String> params,
@RequestHeader("Authorization") String token) {
log.info("自动保存复盘请求: {}", params);
Integer userId = parseUserId(token);
if (userId == null) return Result.error(401, "认证失败");
String content = params.get("content");
String topic = params.get("topic");
String stance = params.get("stance");
if (content == null || content.isEmpty()) {
return Result.error("内容不能为空");
}
try {
String review = wxReviewService.GetReview(content);
if (review == null) return Result.error("复盘生成失败");
DebateHistory history = new DebateHistory();
history.setUserId(userId);
history.setTopic(topic);
history.setStance(stance);
history.setContent(content);
history.setReview(review);
history.setRounds(0); // 默认0轮可根据实际情况调整
historyService.saveDebateHistory(history);
Map<String, Object> data = new HashMap<>();
data.put("review", review);
data.put("historyId", history.getId());
return Result.success(data);
} catch (Exception e) {
log.error("复盘保存失败", e);
return Result.error("处理失败: " + e.getMessage());
}
}
@PostMapping("/save-only")
public Result<Map<String, Object>> saveOnly(
@RequestBody Map<String, String> params,
@RequestHeader("Authorization") String token) {
Integer userId = parseUserId(token);
if (userId == null) return Result.error(401, "认证失败");
String content = params.get("content");
String review = params.get("review");
String topic = params.get("topic");
String stance = params.get("stance");
if (content == null || review == null) {
return Result.error("内容和复盘结果不能为空");
}
try {
DebateHistory history = new DebateHistory();
history.setUserId(userId);
history.setTopic(topic);
history.setStance(stance);
history.setContent(content);
history.setReview(review);
history.setRounds(0);
historyService.saveDebateHistory(history);
Map<String, Object> data = new HashMap<>();
data.put("review", review);
data.put("historyId", history.getId());
return Result.success(data);
} catch (Exception e) {
log.error("保存失败", e);
return Result.error("保存失败: " + e.getMessage());
}
}
private Integer parseUserId(String token) {
try {
return jwtUtil.getUserIdFromToken(token);
} catch (Exception e) {
log.warn("Token解析失败", e);
return null;
}
}
}

@ -1,28 +1,24 @@
package com.learning.newdemo.entity; package com.learning.newdemo.entity;
import com.learning.newdemo.enums.Position;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.util.Date;
@Data @Data
public class DebateHistory { public class DebateHistory {
private Integer id; private Integer id;
private Integer userId; // 关联用户ID private Integer userId;
private String topic;
private Integer argumentId; // 关联立论记录ID private String stance; // "正方"或"反方"
private String content; // 辩论内容JSON
private String topic; // 辩题 private String review; // AI复盘内容
private Integer rounds;
private Position position; // 用户持方 private Date createTime;
private Short totalRounds; // 总回合数 // 注意setStance方法应该验证输入
public void setStance(String stance) {
private String debateContent; // 所有辩论内容JSON格式 if (!"正方".equals(stance) && !"反方".equals(stance)) {
throw new IllegalArgumentException("持方必须是'正方'或'反方'");
private String reviewResult; // 复盘分析内容 }
this.stance = stance;
private Date createTime; // 创建时间 }
private ArgumentHistory argumentHistory; //关联的立论记录
} }

@ -5,90 +5,31 @@ import org.apache.ibatis.annotations.*;
import java.util.List; import java.util.List;
/** @Mapper
* 访
*
*/
public interface DebateHistoryMapper { public interface DebateHistoryMapper {
/** @Insert("INSERT INTO debate_history(user_id, topic, stance, content, review, rounds) " +
* "VALUES(#{userId}, #{topic}, #{stance}, #{content}, #{review}, #{rounds})")
* @param debateHistory @Options(useGeneratedKeys = true, keyProperty = "id")
* @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); int insert(DebateHistory debateHistory);
/**
* ID
* @param userId
* @return
*/
@Select("SELECT * FROM debate_history WHERE user_id = #{userId} ORDER BY create_time DESC") @Select("SELECT * FROM debate_history WHERE user_id = #{userId} ORDER BY create_time DESC")
List<DebateHistory> selectByUserId(@Param("userId") Integer userId); List<DebateHistory> selectByUserId(@Param("userId") Integer userId);
/**
*
* @param userId ID
* @param limit
* @return
*/
@Select("SELECT * FROM debate_history WHERE user_id = #{userId} ORDER BY create_time DESC LIMIT #{limit}") @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); List<DebateHistory> selectLatestByUserId(@Param("userId") Integer userId, @Param("limit") Integer limit);
/**
* ID
* @param argumentId ID
* @return
*/
@Select("SELECT * FROM debate_history WHERE argument_id = #{argumentId} ORDER BY create_time DESC")
List<DebateHistory> selectByArgumentId(@Param("argumentId") Integer argumentId);
/**
* ID
* @param id ID
* @return
*/
@Select("SELECT * FROM debate_history WHERE id = #{id}") @Select("SELECT * FROM debate_history WHERE id = #{id}")
DebateHistory selectByPrimaryKey(@Param("id") Integer id); DebateHistory selectByPrimaryKey(@Param("id") Integer id);
/** @Update("UPDATE debate_history SET review = #{review} WHERE id = #{id}")
* int updateReview(@Param("id") Integer id, @Param("review") String review);
* @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
*/
@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 " + @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} " + "(SELECT id FROM (SELECT id FROM debate_history WHERE user_id = #{userId} " +
"ORDER BY create_time DESC LIMIT 10) t)") "ORDER BY create_time DESC LIMIT 10) t)")
int cleanOverflowHistories(@Param("userId") Integer userId); 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},'%') " + @Select("SELECT * FROM debate_history WHERE user_id = #{userId} AND topic LIKE CONCAT('%',#{keyword},'%') " +
"ORDER BY create_time DESC") "ORDER BY create_time DESC")
List<DebateHistory> searchByKeyword(@Param("userId") Integer userId, @Param("keyword") String keyword); List<DebateHistory> searchByKeyword(@Param("userId") Integer userId, @Param("keyword") String keyword);

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learning.newdemo.mapper.ArgumentHistoryMapper">
<resultMap id="BaseResultMap" type="com.learning.newdemo.entity.ArgumentHistory">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="topic" property="topic" jdbcType="VARCHAR"/>
<result column="argument_content" property="argumentContent" jdbcType="LONGVARCHAR"/>
<result column="position" property="position"
typeHandler="org.apache.ibatis.type.EnumTypeHandler"
jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List">
id, user_id, topic, argument_content, position, create_time
</sql>
<!-- 插入立论记录 -->
<insert id="insert" parameterType="com.learning.newdemo.entity.ArgumentHistory"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO argument_history (
user_id, topic, argument_content, position
)
VALUES (
#{userId,jdbcType=INTEGER},
#{topic,jdbcType=VARCHAR},
#{argumentContent,jdbcType=LONGVARCHAR},
#{position,jdbcType=VARCHAR, typeHandler=org.apache.ibatis.type.EnumTypeHandler}
)
</insert>
<!-- 根据用户ID查询 -->
<select id="selectByUserId" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE user_id = #{userId,jdbcType=INTEGER}
ORDER BY create_time DESC
</select>
<!-- 根据用户ID和持方查询 -->
<select id="selectByUserAndPosition" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE user_id = #{userId,jdbcType=INTEGER}
AND position = #{position,jdbcType=VARCHAR, typeHandler=org.apache.ibatis.type.EnumTypeHandler}
ORDER BY create_time DESC
</select>
<!-- 根据主键查询 -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE id = #{id,jdbcType=INTEGER}
</select>
<!-- 获取用户最新立论记录 -->
<select id="selectLatestByUserId" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE user_id = #{userId,jdbcType=INTEGER}
ORDER BY create_time DESC
LIMIT 1
</select>
<!-- 根据用户ID查询最新的i条记录 -->
<select id="selectLatestByUserIdWithLimit" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE user_id = #{userId,jdbcType=INTEGER}
ORDER BY create_time DESC
LIMIT #{limit,jdbcType=INTEGER}
</select>
<!-- 根据用户ID和持方查询最新的i条记录 -->
<select id="selectLatestByUserAndPositionWithLimit" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM argument_history
WHERE user_id = #{userId,jdbcType=INTEGER}
<if test="position != null">
AND position = #{position,jdbcType=VARCHAR,
typeHandler=org.apache.ibatis.type.EnumTypeHandler}
</if>
ORDER BY create_time DESC
LIMIT #{limit,jdbcType=INTEGER}
</select>
</mapper>

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learning.newdemo.mapper.DebateHistoryMapper">
<resultMap id="BaseResultMap" type="com.learning.newdemo.entity.DebateHistory">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="argument_id" property="argumentId" jdbcType="INTEGER"/>
<result column="topic" property="topic" jdbcType="VARCHAR"/>
<result column="position" property="position"
typeHandler="org.apache.ibatis.type.EnumTypeHandler"
jdbcType="VARCHAR"/>
<result column="total_rounds" property="totalRounds" jdbcType="SMALLINT"/>
<result column="debate_content" property="debateContent" jdbcType="LONGVARCHAR"/>
<result column="review_result" property="reviewResult" jdbcType="LONGVARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
</resultMap>
<!-- 包含关联立论记录的结果映射 -->
<resultMap id="WithArgumentResultMap" type="com.learning.newdemo.entity.DebateHistory" extends="BaseResultMap">
<association property="argumentHistory" javaType="com.learning.newdemo.entity.ArgumentHistory">
<id column="arg_id" property="id"/>
<result column="arg_user_id" property="userId"/>
<result column="arg_topic" property="topic"/>
<result column="arg_content" property="argumentContent"/>
<result column="arg_position" property="position"
typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
<result column="arg_create_time" property="createTime"/>
</association>
</resultMap>
<sql id="Base_Column_List">
id, user_id, argument_id, topic, position, total_rounds, debate_content, review_result, create_time
</sql>
<sql id="WithArgument_Column_List">
dh.id, dh.user_id, dh.argument_id, dh.topic, dh.position, dh.total_rounds,
dh.debate_content, dh.review_result, dh.create_time,
ah.id as arg_id, ah.user_id as arg_user_id, ah.topic as arg_topic,
ah.argument_content as arg_content, ah.position as arg_position,
ah.create_time as arg_create_time
</sql>
<!-- 插入辩论记录 -->
<insert id="insert" parameterType="com.learning.newdemo.entity.DebateHistory"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO debate_history (
user_id, argument_id, topic, position, total_rounds, debate_content
)
VALUES (
#{userId,jdbcType=INTEGER},
#{argumentId,jdbcType=INTEGER},
#{topic,jdbcType=VARCHAR},
#{position,jdbcType=VARCHAR, typeHandler=org.apache.ibatis.type.EnumTypeHandler},
#{totalRounds,jdbcType=SMALLINT},
#{debateContent,jdbcType=LONGVARCHAR}
)
</insert>
<!-- 根据用户ID查询 -->
<select id="selectByUserId" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM debate_history
WHERE user_id = #{userId,jdbcType=INTEGER}
ORDER BY create_time DESC
</select>
<!-- 根据用户ID查询最新的i条记录 -->
<select id="selectLatestByUserId" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM debate_history
WHERE user_id = #{userId,jdbcType=INTEGER}
ORDER BY create_time DESC
LIMIT #{limit,jdbcType=INTEGER}
</select>
<!-- 根据立论记录ID查询 -->
<select id="selectByArgumentId" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM debate_history
WHERE argument_id = #{argumentId,jdbcType=INTEGER}
ORDER BY create_time DESC
</select>
<!-- 根据主键查询 -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM debate_history
WHERE id = #{id,jdbcType=INTEGER}
</select>
<!-- 更新复盘分析内容 -->
<update id="updateReviewResult">
UPDATE debate_history
SET review_result = #{reviewResult,jdbcType=LONGVARCHAR}
WHERE id = #{id,jdbcType=INTEGER}
</update>
<!-- 查询辩论记录及其关联的立论内容 -->
<select id="selectWithArgument" resultMap="WithArgumentResultMap">
SELECT <include refid="WithArgument_Column_List"/>
FROM debate_history dh
JOIN argument_history ah ON dh.argument_id = ah.id
WHERE dh.id = #{id,jdbcType=INTEGER}
</select>
</mapper>

@ -19,7 +19,7 @@ CREATE TABLE IF NOT EXISTS `wx_user` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信用户表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信用户表';
-- 在现有database.sql文件末尾添加不要删除原有内容
CREATE TABLE IF NOT EXISTS `debate_history` ( CREATE TABLE IF NOT EXISTS `debate_history` (
`id` int(11) NOT NULL AUTO_INCREMENT, `id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '关联用户ID', `user_id` int(11) NOT NULL COMMENT '关联用户ID',

Loading…
Cancel
Save