项目框架

This commit is contained in:
2026-10-16 16:28:39 +08:00
commit 071b54d3b3
155 changed files with 10474 additions and 0 deletions
@@ -0,0 +1,71 @@
package com.banben;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 版本资源联合服务系统 —— 后端启动类。
*
* <pre>
* ============================ 一、项目定位 ============================
* 本系统面向 4 家军队院校图书馆,提供「版本资源(纸质书 + 电子书)元数据」的
* 采集、治理、汇聚、检索与统计分析能力。核心是「元数据聚合 + 检索发现」,
* 不存储书籍正文,正文通过「全文地址」跳转到来源资源库获取。
*
* ============================ 二、分层结构 ============================
* com.banben
* ├─ common 通用基础设施:统一响应 Result / 分页 PageResult / 业务异常 / 全局异常处理
* ├─ config 框架配置:MyBatis-Plus、CORS、鉴权拦截器、OpenAPI、自动填充、启动初始化
* └─ modules 业务模块(按招标文件功能一一对应)
* ├─ auth 认证鉴权(JWT 登录)
* ├─ resource 版本资源元数据(CRUD 样板,字段依招标著录标准)
* ├─ search 检索发现(统一/高级检索、分面聚类、年度统计、相似推荐)
* ├─ collect 数据采集(采集任务 + 采集适配器)
* ├─ governance 数据治理(聚同/优化/提示/提纯)
* ├─ deposit 资源呈缴
* ├─ special 特藏版本推荐
* └─ analysis 大数据分析(运行数据统计)
*
* ============================ 三、单模块代码分层 ============================
* 每个业务模块内部统一按下列结构组织(以 resource 为例):
* controller 接收 HTTP 请求、参数校验、返回 Result —— 不写业务逻辑
* service 业务接口(定义能力)
* service.impl 业务实现(事务、业务规则、组装数据)
* mapper MyBatis-Plus Mapper(继承 BaseMapper 即拥有单表 CRUD)
* entity 数据库表映射实体(@TableName)
* dto 入参对象(查询条件/请求体)
* vo 出参对象(聚合返回结构)
*
* ============================ 四、一次请求的完整链路 ============================
* 浏览器
* → Nginx(生产,反代 /api)
* → AuthInterceptor(校验 Bearer Token,写入 UserContext)
* → Controller(取参、校验)
* → Service(业务处理、事务)
* → Mapper(MyBatis-Plus → 瀚高/PostgreSQL)
* → Result 统一包装为 {code, message, data} 返回
*
* ============================ 五、数据库 ============================
* 国产化环境使用「瀚高(HighGo)」,非国产化环境使用「PostgreSQL」。
* 二者协议兼容,代码层通过 Spring Profile 切换数据源即可,无需改代码。
*
* ============================ 六、如何新增一个功能 ============================
* 1) 建表:在 resources/db 下新增 SQL,并同步到目标库;
* 2) 建包:modules/xxx 下按 controller/service/mapper/entity/dto/vo 建文件;
* 3) 实体:加 @TableName 与字段;Mapper 继承 BaseMapper 即可;
* 4) 接口:Controller 上加 @Tag/@Operation,返回 Result.success(...);
* 5) 鉴权:/api/** 默认已被拦截器保护,无需额外配置。
* </pre>
*
* @author banben
*/
@SpringBootApplication
// 扫描所有模块下的 Mapper 接口,省去逐个加 @MapperScan 的麻烦
@MapperScan("com.banben.**.mapper")
public class BanbenApplication {
public static void main(String[] args) {
SpringApplication.run(BanbenApplication.class, args);
}
}
@@ -0,0 +1,26 @@
package com.banben.common;
import lombok.Getter;
/**
* 业务异常,配合 {@link GlobalExceptionHandler} 统一处理。
*/
@Getter
public class BusinessException extends RuntimeException {
private final int code;
public BusinessException(String message) {
super(message);
this.code = ResultCode.BUSINESS_ERROR.getCode();
}
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.code = resultCode.getCode();
}
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
}
@@ -0,0 +1,52 @@
package com.banben.common;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;
/**
* 全局异常处理。
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result<Void> handleBusinessException(BusinessException e) {
log.warn("业务异常: {}", e.getMessage());
return Result.failed(e.getCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleValidException(MethodArgumentNotValidException e) {
String msg = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining("; "));
return Result.failed(ResultCode.VALIDATE_FAILED.getCode(), msg);
}
@ExceptionHandler(BindException.class)
public Result<Void> handleBindException(BindException e) {
String msg = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining("; "));
return Result.failed(ResultCode.VALIDATE_FAILED.getCode(), msg);
}
@ExceptionHandler(ConstraintViolationException.class)
public Result<Void> handleConstraintViolation(ConstraintViolationException e) {
return Result.failed(ResultCode.VALIDATE_FAILED.getCode(), e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
log.error("系统异常", e);
return Result.failed(ResultCode.FAILED);
}
}
@@ -0,0 +1,45 @@
package com.banben.common;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/**
* 分页响应结构。
*
* @param <T> 列表元素类型
*/
@Data
@Schema(description = "分页结果")
public class PageResult<T> implements Serializable {
@Schema(description = "当前页数据")
private List<T> records;
@Schema(description = "总条数")
private long total;
@Schema(description = "当前页码")
private long current;
@Schema(description = "每页条数")
private long size;
public PageResult() {
this.records = Collections.emptyList();
}
public PageResult(List<T> records, long total, long current, long size) {
this.records = records;
this.total = total;
this.current = current;
this.size = size;
}
public static <T> PageResult<T> of(List<T> records, long total, long current, long size) {
return new PageResult<>(records, total, current, size);
}
}
@@ -0,0 +1,64 @@
package com.banben.common;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 统一响应结构。
*
* @param <T> 业务数据类型
*/
@Data
@Schema(description = "统一响应结果")
public class Result<T> implements Serializable {
@Schema(description = "业务状态码,200 表示成功")
private int code;
@Schema(description = "提示信息")
private String message;
@Schema(description = "业务数据")
private T data;
public Result() {
}
public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/** 成功,无数据(用于 删除/更新 这类无返回值的操作)。 */
public static <T> Result<T> success() {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
}
/** 成功,携带业务数据(最常用,如查询结果)。 */
public static <T> Result<T> success(T data) {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
/** 成功,自定义提示语 + 数据(如「登录成功」并返回 token)。 */
public static <T> Result<T> success(String message, T data) {
return new Result<>(ResultCode.SUCCESS.getCode(), message, data);
}
/** 失败,自定义提示语(默认使用 500 状态码)。 */
public static <T> Result<T> failed(String message) {
return new Result<>(ResultCode.FAILED.getCode(), message, null);
}
/** 失败,使用预定义状态码(见 {@link ResultCode})。 */
public static <T> Result<T> failed(ResultCode resultCode) {
return new Result<>(resultCode.getCode(), resultCode.getMessage(), null);
}
/** 失败,完全自定义状态码与提示语。 */
public static <T> Result<T> failed(int code, String message) {
return new Result<>(code, message, null);
}
}
@@ -0,0 +1,37 @@
package com.banben.common;
import lombok.Getter;
/**
* 业务状态码枚举。
*
* <p>约定:与 HTTP 状态码语义保持一致,便于前后端统一理解。
* 前端只需判断 {@code code === 200} 即为成功,其余按错误处理。
* 其中 401 会被前端拦截器特殊处理(清除令牌并跳转登录页)。</p>
*/
@Getter
public enum ResultCode {
/** 成功(唯一表示成功的状态码)。 */
SUCCESS(200, "操作成功"),
/** 系统级失败(未捕获异常兜底)。 */
FAILED(500, "操作失败"),
/** 参数校验失败(@Valid 校验不通过)。 */
VALIDATE_FAILED(400, "参数校验失败"),
/** 未登录或令牌失效 —— 前端据此跳转登录页。 */
UNAUTHORIZED(401, "暂未登录或 Token 已过期"),
/** 已登录但无权限。 */
FORBIDDEN(403, "没有相关权限"),
/** 目标资源不存在。 */
NOT_FOUND(404, "资源不存在"),
/** 业务规则校验不通过(如「该呈缴记录已处理」)。 */
BUSINESS_ERROR(600, "业务处理异常");
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}
@@ -0,0 +1,48 @@
package com.banben.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* 启动初始化:确保存在默认管理员账号。
*
* <p>默认账号:admin / admin123(首次启动自动创建,请尽快修改密码)。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements ApplicationRunner {
private final SysUserMapper sysUserMapper;
private final PasswordEncoder passwordEncoder;
@Override
public void run(ApplicationArguments args) {
try {
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUsername, "admin");
Long count = sysUserMapper.selectCount(wrapper);
if (count != null && count > 0) {
return;
}
SysUser admin = new SysUser();
admin.setUsername("admin");
admin.setPassword(passwordEncoder.encode("admin123"));
admin.setRealName("系统管理员");
admin.setRole("ADMIN");
admin.setOrgName("版本资源联合服务中心");
admin.setStatus(1);
sysUserMapper.insert(admin);
log.info("已创建默认管理员账号:admin / admin123");
} catch (Exception e) {
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
}
}
}
@@ -0,0 +1,38 @@
package com.banben.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 公共字段自动填充。
*
* <p><b>作用:</b>实体里带 {@code @TableField(fill = FieldFill.INSERT/INSERT_UPDATE)}
* 的字段(本项目中是 createTime / updateTime),在执行 insert / update 时由框架自动写入,
* 业务代码不必每次手动 {@code setCreateTime(now())},避免遗漏。</p>
*
* <p><b>使用前提:</b>实体字段上必须标注 fill 属性,例如:
* <pre>
* &#64;TableField(fill = FieldFill.INSERT)
* private LocalDateTime createTime;
* </pre>
* </p>
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/** 新增时:同时填充创建时间与更新时间。 */
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
/** 更新时:只刷新更新时间。 */
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
@@ -0,0 +1,32 @@
package com.banben.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus 配置。
*
* <p><b>为什么用 POSTGRE_SQL 方言?</b>
* 国产化环境要求适配「瀚高(HighGo)」,而瀚高基于 PostgreSQL 内核、协议完全兼容,
* 因此分页 SQL 方言直接使用 PostgreSQL 即可,同一套代码可同时跑瀚高与 PostgreSQL。</p>
*
* <p>分页插件作用:给 {@code Page} 查询自动追加 {@code LIMIT ? OFFSET ?},
* 并在需要时额外执行一次 {@code COUNT} 查询,业务代码无需手写分页 SQL。</p>
*/
@Configuration
public class MybatisPlusConfig {
/**
* 注册 MyBatis-Plus 插件链。
* 若有多个插件(如乐观锁、防全表更新),注意顺序:分页插件建议放最后。
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
return interceptor;
}
}
@@ -0,0 +1,23 @@
package com.banben.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* OpenAPI(Swagger) 文档配置。
*
* <p>访问地址:/swagger-ui/index.html</p>
*/
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI banbenOpenAPI() {
return new OpenAPI().info(new Info()
.title("版本资源联合服务系统 API")
.description("数据集成库 / 数据采集治理 / 检索发现 / 后台管理 / 特藏推荐 / 资源呈缴 / 大数据分析")
.version("v1.0.0"));
}
}
@@ -0,0 +1,18 @@
package com.banben.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 密码编码器配置。
*/
@Configuration
public class SecurityBeanConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,64 @@
package com.banben.config;
import com.banben.modules.auth.interceptor.AuthInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Web MVC 配置:跨域(CORS) + 认证拦截器注册。
*
* <p><b>跨域:</b>仅开发期需要(前端 5173 → 后端 8080 属跨域)。生产环境由 Nginx
* 反向代理统一入口,前后端同源,可放心收紧或关闭此处。</p>
*
* <p><b>拦截器:</b>把 {@link AuthInterceptor} 挂到 {@code /api/**} 上,
* 实现「除白名单外,所有接口都必须携带有效 JWT」。这是本项目唯一的鉴权入口,
* 新增接口会自动受到保护,无需逐个头加注解。</p>
*/
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
/**
* 跨域配置。
* allowCredentials(true) 时不能用 allowedOrigins("*"),必须用 allowedOriginPatterns。
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
/**
* 注册认证拦截器。
*
* <p>拦截范围:/api/**;放行白名单如下:</p>
* <ul>
* <li>{@code /api/auth/login} —— 登录接口本身不能要求登录</li>
* <li>{@code /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
* </ul>
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/api/**")
// 放行:登录、登出、Swagger、健康检查
.excludePathPatterns(
"/api/auth/login",
"/api/auth/logout",
"/swagger-ui/**",
"/v3/api-docs/**",
"/actuator/**"
);
}
}
@@ -0,0 +1,66 @@
package com.banben.modules.analysis.controller;
import com.banben.common.Result;
import com.banben.modules.analysis.service.AnalysisService;
import com.banben.modules.search.vo.FacetItem;
import com.banben.modules.search.vo.YearStat;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 版本资源大数据分析接口。
*
* <p>对应「版本资源大数据分析系统」。</p>
*/
@Tag(name = "大数据分析", description = "运行数据统计分析")
@RestController
@RequestMapping("/api/analysis")
@RequiredArgsConstructor
public class AnalysisController {
private final AnalysisService analysisService;
@Operation(summary = "数据总览(资源总量/纸电/来源单位/今日检索/在线用户)")
@GetMapping("/overview")
public Result<Map<String, Object>> overview() {
return Result.success(analysisService.overview());
}
@Operation(summary = "版本资源综合比例(纸质/电子)")
@GetMapping("/resource-ratio")
public Result<List<FacetItem>> resourceRatio() {
return Result.success(analysisService.resourceRatio());
}
@Operation(summary = "版本资源贡献量(各来源单位)")
@GetMapping("/library-contribution")
public Result<List<FacetItem>> libraryContribution() {
return Result.success(analysisService.libraryContribution());
}
@Operation(summary = "版本资源增量(按年份)")
@GetMapping("/year-distribution")
public Result<List<YearStat>> yearDistribution() {
return Result.success(analysisService.yearDistribution());
}
@Operation(summary = "热门检索词排行")
@GetMapping("/hot-keywords")
public Result<List<FacetItem>> hotKeywords(@RequestParam(defaultValue = "20") int limit) {
return Result.success(analysisService.hotKeywords(limit));
}
@Operation(summary = "用户利用情况(近6个月检索量)")
@GetMapping("/recent-activity")
public Result<List<YearStat>> recentActivity() {
return Result.success(analysisService.recentActivity());
}
}
@@ -0,0 +1,43 @@
package com.banben.modules.analysis.service;
import com.banben.modules.search.vo.FacetItem;
import com.banben.modules.search.vo.YearStat;
import java.util.List;
import java.util.Map;
/**
* 版本资源大数据分析服务。
*/
public interface AnalysisService {
/**
* 总览:资源总量、纸电数量、来源单位数、今日检索量、当前在线数。
*/
Map<String, Object> overview();
/**
* 版本资源综合比例:纸质/电子数量及占比。
*/
List<FacetItem> resourceRatio();
/**
* 版本资源贡献量:各来源单位资源数量。
*/
List<FacetItem> libraryContribution();
/**
* 版本资源增量:按年份统计。
*/
List<YearStat> yearDistribution();
/**
* 热门检索词排行。
*/
List<FacetItem> hotKeywords(int limit);
/**
* 用户利用情况:近 6 个月检索量。
*/
List<YearStat> recentActivity();
}
@@ -0,0 +1,174 @@
package com.banben.modules.analysis.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.banben.modules.analysis.service.AnalysisService;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import com.banben.modules.search.entity.SearchLog;
import com.banben.modules.search.mapper.SearchLogMapper;
import com.banben.modules.search.vo.FacetItem;
import com.banben.modules.search.vo.YearStat;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 版本资源大数据分析服务实现。
*
* <pre>
* 数据来源:
* version_resource —— 资源侧统计(总量、纸电比例、来源单位贡献、年度增量)
* search_log —— 行为侧统计(今日检索量、热门检索词、近 6 个月活跃度、在线人数)
*
* 实现方式:
* 全部通过数据库聚合完成(selectCount / selectMaps + GROUP BY),
* 不把数据捞回内存再计算,保证数据量增长后的性能。
* </pre>
*/
@Service
@RequiredArgsConstructor
public class AnalysisServiceImpl implements AnalysisService {
private final VersionResourceMapper resourceMapper;
private final SearchLogMapper searchLogMapper;
/**
* 总览数据(首页四张卡片 + 两块表格)。
*
* <p>返回字段:totalCount 资源总量 / mediaRatio 纸电比例 / libraryContribution 单位贡献 /
* todaySearchCount 今日检索量 / todayAddCount 今日资源增量 / onlineCount 当前在线。</p>
*/
@Override
public Map<String, Object> overview() {
Map<String, Object> result = new LinkedHashMap<>();
QueryWrapper<VersionResource> total = new QueryWrapper<>();
total.eq("deleted", 0);
result.put("totalCount", resourceMapper.selectCount(total));
result.put("mediaRatio", resourceRatio());
result.put("libraryContribution", libraryContribution());
// 今日检索量
QueryWrapper<SearchLog> todaySearch = new QueryWrapper<>();
todaySearch.apply("create_time >= CURRENT_DATE");
result.put("todaySearchCount", searchLogMapper.selectCount(todaySearch));
// 今日资源增量(按加工日期)
QueryWrapper<VersionResource> todayAdd = new QueryWrapper<>();
todayAdd.apply("to_char(to_date(process_date, 'YYYYMMDD'), 'YYYY-MM-DD') = to_char(CURRENT_DATE, 'YYYY-MM-DD')");
Long todayAddCount;
try {
todayAddCount = resourceMapper.selectCount(todayAdd);
} catch (Exception e) {
todayAddCount = 0L;
}
result.put("todayAddCount", todayAddCount);
// 当前在线(近 5 分钟内有检索行为的去重 IP)
QueryWrapper<SearchLog> online = new QueryWrapper<>();
online.select("COUNT(DISTINCT user_ip) AS cnt")
.apply("create_time >= now() - interval '5 minutes'");
List<Map<String, Object>> onlineMaps = searchLogMapper.selectMaps(online);
long onlineCount = 0L;
if (!onlineMaps.isEmpty() && onlineMaps.get(0).get("cnt") != null) {
onlineCount = ((Number) onlineMaps.get(0).get("cnt")).longValue();
}
result.put("onlineCount", onlineCount);
return result;
}
@Override
public List<FacetItem> resourceRatio() {
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.select("media_type AS name", "COUNT(*) AS cnt")
.eq("deleted", 0)
.groupBy("media_type")
.orderByDesc("cnt");
return toFacets(resourceMapper.selectMaps(wrapper));
}
@Override
public List<FacetItem> libraryContribution() {
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.select("source_library AS name", "COUNT(*) AS cnt")
.eq("deleted", 0)
.isNotNull("source_library")
.ne("source_library", "")
.groupBy("source_library")
.orderByDesc("cnt");
return toFacets(resourceMapper.selectMaps(wrapper));
}
@Override
public List<YearStat> yearDistribution() {
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.select("publish_year AS name", "COUNT(*) AS cnt")
.eq("deleted", 0)
.isNotNull("publish_year")
.ne("publish_year", "")
.groupBy("publish_year")
.orderByAsc("publish_year");
List<YearStat> stats = new ArrayList<>();
for (Map<String, Object> m : resourceMapper.selectMaps(wrapper)) {
Object name = m.get("name");
if (name == null) {
continue;
}
stats.add(new YearStat(String.valueOf(name), toLong(m.get("cnt"))));
}
return stats;
}
@Override
public List<FacetItem> hotKeywords(int limit) {
QueryWrapper<SearchLog> wrapper = new QueryWrapper<>();
wrapper.select("keyword AS name", "COUNT(*) AS cnt")
.isNotNull("keyword")
.ne("keyword", "")
.groupBy("keyword")
.orderByDesc("cnt")
.last("limit " + Math.max(1, limit));
return toFacets(searchLogMapper.selectMaps(wrapper));
}
@Override
public List<YearStat> recentActivity() {
QueryWrapper<SearchLog> wrapper = new QueryWrapper<>();
wrapper.select("to_char(create_time, 'YYYY-MM') AS name", "COUNT(*) AS cnt")
.apply("create_time >= now() - interval '6 months'")
.groupBy("to_char(create_time, 'YYYY-MM')")
.orderByAsc("to_char(create_time, 'YYYY-MM')");
List<YearStat> stats = new ArrayList<>();
for (Map<String, Object> m : searchLogMapper.selectMaps(wrapper)) {
Object name = m.get("name");
if (name == null) {
continue;
}
stats.add(new YearStat(String.valueOf(name), toLong(m.get("cnt"))));
}
return stats;
}
// ==================== 内部方法 ====================
private List<FacetItem> toFacets(List<Map<String, Object>> maps) {
List<FacetItem> items = new ArrayList<>();
for (Map<String, Object> m : maps) {
Object name = m.get("name");
if (name == null) {
continue;
}
items.add(new FacetItem(String.valueOf(name), toLong(m.get("cnt"))));
}
return items;
}
private Long toLong(Object value) {
return value instanceof Number number ? number.longValue() : 0L;
}
}
@@ -0,0 +1,7 @@
package com.banben.modules.auth.context;
/**
* 当前登录用户(线程上下文载体)。
*/
public record LoginUser(Long id, String username, String role) {
}
@@ -0,0 +1,51 @@
package com.banben.modules.auth.context;
/**
* 当前登录用户上下文(基于 ThreadLocal)。
*
* <p><b>为什么用 ThreadLocal?</b>一个 HTTP 请求由单个线程处理,把用户信息存进当前线程,
* 业务层任何位置都能通过 {@link #currentUserId()} 取到当前用户,无需一层层传参。
* 请求结束时由 {@code AuthInterceptor#afterCompletion} 调用 {@link #clear()} 清理。</p>
*
* <p><b>使用示例:</b>
* <pre>
* Long userId = UserContext.currentUserId(); // 谁在操作
* String name = UserContext.currentUsername(); // 操作用户名
* </pre>
* 注意:异步线程 / 线程池中 ThreadLocal 不会自动传递,需手动透传。</p>
*/
public final class UserContext {
private static final ThreadLocal<LoginUser> HOLDER = new ThreadLocal<>();
/** 工具类,禁止实例化。 */
private UserContext() {
}
/** 写入当前用户(由拦截器调用)。 */
public static void set(LoginUser user) {
HOLDER.set(user);
}
/** 获取当前用户对象,未登录时为 null。 */
public static LoginUser get() {
return HOLDER.get();
}
/** 获取当前用户 ID(最常用)。 */
public static Long currentUserId() {
LoginUser user = HOLDER.get();
return user == null ? null : user.id();
}
/** 获取当前用户名。 */
public static String currentUsername() {
LoginUser user = HOLDER.get();
return user == null ? null : user.username();
}
/** 清理(必须在请求结束时调用,避免线程复用串号)。 */
public static void clear() {
HOLDER.remove();
}
}
@@ -0,0 +1,43 @@
package com.banben.modules.auth.controller;
import com.banben.common.Result;
import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
* 认证接口。
*/
@Tag(name = "认证", description = "登录 / 登出 / 当前用户")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthService authService;
@Operation(summary = "登录")
@PostMapping("/login")
public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
return Result.success("登录成功", authService.login(request));
}
@Operation(summary = "当前登录用户")
@GetMapping("/me")
public Result<SysUser> me() {
return Result.success(authService.currentUser());
}
@Operation(summary = "登出")
@PostMapping("/logout")
public Result<Void> logout() {
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
return Result.success();
}
}
@@ -0,0 +1,21 @@
package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 登录请求。
*/
@Data
@Schema(description = "登录请求")
public class LoginRequest {
@NotBlank(message = "账号不能为空")
@Schema(description = "账号", example = "admin")
private String username;
@NotBlank(message = "密码不能为空")
@Schema(description = "密码", example = "admin123")
private String password;
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 登录响应。
*/
@Data
@Schema(description = "登录响应")
public class LoginResponse {
@Schema(description = "访问令牌")
private String token;
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "账号")
private String username;
@Schema(description = "姓名")
private String realName;
@Schema(description = "角色")
private String role;
@Schema(description = "所属单位")
private String orgName;
}
@@ -0,0 +1,55 @@
package com.banben.modules.auth.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 系统用户。
*/
@Data
@TableName("sys_user")
@Schema(description = "系统用户")
public class SysUser implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@Schema(description = "登录账号")
private String username;
@Schema(description = "BCrypt 加密后的密码")
private String password;
@Schema(description = "姓名")
private String realName;
@Schema(description = "角色:ADMIN / USER")
private String role;
@Schema(description = "所属单位")
private String orgName;
@Schema(description = "状态:1启用 0停用")
private Integer status;
@Schema(description = "最近登录时间")
private LocalDateTime lastLoginTime;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,94 @@
package com.banben.modules.auth.interceptor;
import com.banben.common.ResultCode;
import com.banben.modules.auth.context.LoginUser;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.nio.charset.StandardCharsets;
/**
* 认证拦截器。
*
* <pre>
* 职责:
* 1. 从请求头 Authorization 中取出 Bearer Token;
* 2. 解析并校验 JWT(签名、有效期);
* 3. 校验通过 → 把用户信息写入 {@link UserContext},供业务层随时取用;
* 4. 校验失败 → 直接返回 HTTP 401 + JSON 体,请求不再进入 Controller。
*
* 生命周期(每个请求):
* preHandle → 校验令牌(返回 false 则中断)
* Controller/Service
* afterCompletion → 清理 ThreadLocal,防止线程复用导致用户信息串号
* </pre>
*/
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
/** 令牌前缀,前端统一使用 "Bearer {token}" 格式。 */
private static final String BEARER_PREFIX = "Bearer ";
private final JwtUtil jwtUtil;
/**
* 进入 Controller 之前的校验。
*
* @return true 放行;false 中断请求(已写出 401 响应)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 跨域预检请求(OPTIONS)不携带自定义头,必须直接放行,否则浏览器预检会失败
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
return true;
}
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith(BEARER_PREFIX)) {
writeUnauthorized(response, "未登录或缺少令牌");
return false;
}
String token = authorization.substring(BEARER_PREFIX.length()).trim();
try {
Claims claims = jwtUtil.parse(token);
// uid:在 JwtUtil.generate 中写入的自定义声明;sub 中存的是用户名
Long uid = claims.get("uid", Number.class) == null ? null : claims.get("uid", Number.class).longValue();
String role = claims.get("role", String.class);
UserContext.set(new LoginUser(uid, claims.getSubject(), role));
return true;
} catch (Exception e) {
// 令牌过期、签名错误、格式非法等,统一按「登录失效」处理
writeUnauthorized(response, "登录状态已失效,请重新登录");
return false;
}
}
/**
* 请求结束后清理 ThreadLocal。
* Tomcat 线程是复用的,不清理会导致下一个请求读到上一个用户的身份。
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
UserContext.clear();
}
private void writeUnauthorized(HttpServletResponse response, String message) throws Exception {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String body = String.format("{\"code\":%d,\"message\":\"%s\",\"data\":null}",
ResultCode.UNAUTHORIZED.getCode(), message);
response.getWriter().write(body);
}
}
@@ -0,0 +1,12 @@
package com.banben.modules.auth.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.auth.entity.SysUser;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户 Mapper。
*/
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
}
@@ -0,0 +1,21 @@
package com.banben.modules.auth.service;
import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser;
/**
* 认证服务。
*/
public interface AuthService {
/**
* 登录,返回 Token 与用户信息。
*/
LoginResponse login(LoginRequest request);
/**
* 查询当前登录用户完整信息。
*/
SysUser currentUser();
}
@@ -0,0 +1,71 @@
package com.banben.modules.auth.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.auth.service.AuthService;
import com.banben.modules.auth.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
/**
* 认证服务实现。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
private final SysUserMapper sysUserMapper;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
@Override
public LoginResponse login(LoginRequest request) {
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUsername, request.getUsername());
SysUser user = sysUserMapper.selectOne(wrapper);
if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new BusinessException("账号或密码错误");
}
if (user.getStatus() != null && user.getStatus() == 0) {
throw new BusinessException("账号已停用,请联系管理员");
}
user.setLastLoginTime(LocalDateTime.now());
sysUserMapper.updateById(user);
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
LoginResponse response = new LoginResponse();
response.setToken(token);
response.setUserId(user.getId());
response.setUsername(user.getUsername());
response.setRealName(user.getRealName());
response.setRole(user.getRole());
response.setOrgName(user.getOrgName());
return response;
}
@Override
public SysUser currentUser() {
Long userId = UserContext.currentUserId();
if (userId == null) {
throw new BusinessException("未登录");
}
SysUser user = sysUserMapper.selectById(userId);
if (user != null) {
user.setPassword(null);
}
return user;
}
}
@@ -0,0 +1,80 @@
package com.banben.modules.auth.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
/**
* JWT(JSON Web Token)工具类。
*
* <pre>
* 本项目采用「无状态令牌」方案:
* 登录成功 → 服务端签发 JWT(含 uid / 用户名 / 角色 / 过期时间)
* 后续请求 → 前端在请求头携带 Authorization: Bearer {token}
* 服务端 → 只验签名与有效期,无需查库/会话,天然支持多站点部署。
*
* 配置项(application.yml → banben.jwt):
* secret 签名密钥,长度需 >= 32 字节(HS384 要求)
* expire-hours 令牌有效期(小时),默认 12
* </pre>
*/
@Component
public class JwtUtil {
@Value("${banben.jwt.secret}")
private String secret;
@Value("${banben.jwt.expire-hours:12}")
private long expireHours;
/** 由密钥生成 HMAC 签名密钥(HS384)。 */
private SecretKey key() {
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
/**
* 签发 Token。
*
* @param userId 用户 ID(写入自定义声明 uid)
* @param username 用户名(写入标准声明 sub)
* @param role 角色(写入自定义声明 role)
* @return 紧凑格式的 JWT 字符串
*/
public String generate(Long userId, String username, String role) {
Date now = new Date();
Date expiration = new Date(now.getTime() + expireHours * 3600_000L);
return Jwts.builder()
.subject(username)
.claim("uid", userId)
.claim("role", role)
.issuedAt(now)
.expiration(expiration)
.signWith(key())
.compact();
}
/**
* 解析并校验 Token。
*
* @param token 前端传来的令牌(不含 "Bearer " 前缀)
* @return 载荷 Claims
* @throws io.jsonwebtoken.JwtException 签名错误或已过期时抛出,由拦截器捕获转 401
*/
public Claims parse(String token) {
return Jwts.parser()
.verifyWith(key())
.build()
.parseSignedClaims(token)
.getPayload();
}
public long getExpireHours() {
return expireHours;
}
}
@@ -0,0 +1,50 @@
package com.banben.modules.collect.controller;
import com.banben.common.Result;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.service.CollectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 数据采集接口。
*
* <p>对应「数据采集」:从各馆采集纸电版本资源元数据(各馆不低于 20 万条)。</p>
*/
@Tag(name = "数据采集", description = "采集任务创建、执行与进度查询")
@RestController
@RequestMapping("/api/collect")
@RequiredArgsConstructor
public class CollectController {
private final CollectService collectService;
@Operation(summary = "创建采集任务")
@PostMapping("/task")
public Result<Long> createTask(@RequestBody CollectTask task) {
return Result.success(collectService.createTask(task));
}
@Operation(summary = "执行采集任务")
@PostMapping("/task/{id}/start")
public Result<Void> startTask(@PathVariable Long id) {
collectService.startTask(id);
return Result.success();
}
@Operation(summary = "采集任务列表")
@GetMapping("/tasks")
public Result<List<CollectTask>> tasks() {
return Result.success(collectService.listTasks());
}
@Operation(summary = "查询某单位最新采集进度")
@GetMapping("/progress/{libraryCode}")
public Result<CollectTask> progress(@PathVariable String libraryCode) {
return Result.success(collectService.latestByLibrary(libraryCode));
}
}
@@ -0,0 +1,61 @@
package com.banben.modules.collect.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 数据采集任务。
*/
@Data
@TableName("collect_task")
@Schema(description = "数据采集任务")
public class CollectTask implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@Schema(description = "单位编码")
private String libraryCode;
@Schema(description = "单位名称")
private String libraryName;
@Schema(description = "数据源类型:MARC/EXCEL/DB/API")
private String sourceType;
@Schema(description = "目标采集量")
private Integer targetCount;
@Schema(description = "已采集量")
private Integer collectedCount;
@Schema(description = "状态:PENDING/RUNNING/SUCCESS/FAILED")
private String status;
@Schema(description = "信息")
private String message;
@Schema(description = "开始时间")
private LocalDateTime startTime;
@Schema(description = "结束时间")
private LocalDateTime endTime;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,12 @@
package com.banben.modules.collect.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.collect.entity.CollectTask;
import org.apache.ibatis.annotations.Mapper;
/**
* 采集任务 Mapper。
*/
@Mapper
public interface CollectTaskMapper extends BaseMapper<CollectTask> {
}
@@ -0,0 +1,32 @@
package com.banben.modules.collect.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.collect.entity.CollectTask;
import java.util.List;
/**
* 数据采集服务。
*/
public interface CollectService extends IService<CollectTask> {
/**
* 创建采集任务。
*/
Long createTask(CollectTask task);
/**
* 执行采集任务(异步)。
*/
void startTask(Long taskId);
/**
* 查询任务列表。
*/
List<CollectTask> listTasks();
/**
* 按单位查询最近一次采集进度。
*/
CollectTask latestByLibrary(String libraryCode);
}
@@ -0,0 +1,25 @@
package com.banben.modules.collect.service;
import com.banben.modules.collect.entity.CollectTask;
/**
* 采集适配器接口。
*
* <p>不同馆的数据源形态不同(MARC/CNMARC、Excel、数据库、接口),
* 由各自实现类完成解析并写入版本资源元数据表。</p>
*/
public interface Collector {
/**
* 适配的数据源类型:MARC / EXCEL / DB / API。
*/
String sourceType();
/**
* 执行采集。
*
* @param task 采集任务
* @return 实际采集条数
*/
int collect(CollectTask task);
}
@@ -0,0 +1,114 @@
package com.banben.modules.collect.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.mapper.CollectTaskMapper;
import com.banben.modules.collect.service.CollectService;
import com.banben.modules.collect.service.Collector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 数据采集服务实现。
*
* <p><b>任务生命周期:</b>PENDING(已创建) → RUNNING(执行中) → SUCCESS / FAILED。</p>
*
* <p><b>适配器路由机制:</b>各馆数据源形态不同(MARC/CNMARC、Excel、数据库、接口),
* 因此把「怎么采」抽象成 {@link Collector} 接口。Spring 启动时会注入所有实现类,
* 本类按 {@code sourceType} 建立「类型 → 适配器」的映射表,执行任务时自动路由。</p>
*
* <p><b>要新增一种数据源怎么做?</b>只需写一个 {@code @Component} 实现 {@link Collector},
* 返回对应的 {@code sourceType()} 并在 {@code collect()} 里完成解析入库,
* 无需修改本类任何代码 —— 这就是「开闭原则」的落地。</p>
*/
@Slf4j
@Service
public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTask>
implements CollectService {
/** 数据源类型 → 采集适配器 的映射(key 统一大写)。 */
private final Map<String, Collector> collectorMap;
/**
* 构造注入所有 Collector 实现。
* 若当前没有任何实现类,Spring 注入空集合,运行时会提示「未找到适配器」并跳过实际采集。
*/
public CollectServiceImpl(List<Collector> collectors) {
this.collectorMap = collectors.stream()
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
}
/** 创建任务:初始状态 PENDING、已采集量 0,目标量缺省为 20 万条。 */
@Override
public Long createTask(CollectTask task) {
task.setId(null);
task.setStatus("PENDING");
task.setCollectedCount(0);
if (task.getTargetCount() == null) {
task.setTargetCount(200000);
}
this.save(task);
return task.getId();
}
@Override
public void startTask(Long taskId) {
CollectTask task = this.getById(taskId);
if (task == null) {
throw new BusinessException("采集任务不存在");
}
if ("RUNNING".equals(task.getStatus())) {
throw new BusinessException("该任务正在执行中");
}
task.setStatus("RUNNING");
task.setStartTime(LocalDateTime.now());
this.updateById(task);
// TODO 生产环境应改为异步执行(@Async / 线程池 / 消息队列)
try {
String sourceType = task.getSourceType() == null ? "" : task.getSourceType().toUpperCase();
Collector collector = collectorMap.get(sourceType);
int count;
if (collector == null) {
log.warn("未找到数据源类型 [{}] 的采集适配器,任务 {} 跳过实际采集", sourceType, taskId);
count = 0;
} else {
count = collector.collect(task);
}
task.setCollectedCount(count);
task.setStatus("SUCCESS");
task.setMessage("采集完成");
} catch (Exception e) {
log.error("采集任务执行失败: {}", e.getMessage(), e);
task.setStatus("FAILED");
task.setMessage(e.getMessage());
} finally {
task.setEndTime(LocalDateTime.now());
this.updateById(task);
}
}
@Override
public List<CollectTask> listTasks() {
LambdaQueryWrapper<CollectTask> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByDesc(CollectTask::getCreateTime);
return this.list(wrapper);
}
@Override
public CollectTask latestByLibrary(String libraryCode) {
LambdaQueryWrapper<CollectTask> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CollectTask::getLibraryCode, libraryCode)
.orderByDesc(CollectTask::getCreateTime)
.last("limit 1");
return this.getOne(wrapper);
}
}
@@ -0,0 +1,60 @@
package com.banben.modules.deposit.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.deposit.dto.DepositQuery;
import com.banben.modules.deposit.entity.DepositRecord;
import com.banben.modules.deposit.service.DepositService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
* 版本资源呈缴接口。
*
* <p>对应「版本资源呈缴模块」:用户提交呈缴,管理员在后台查看、接收。</p>
*/
@Tag(name = "版本资源呈缴", description = "用户呈缴与管理端接收")
@RestController
@RequestMapping("/api/deposit")
@RequiredArgsConstructor
public class DepositController {
private final DepositService depositService;
@Operation(summary = "提交呈缴")
@PostMapping
public Result<Long> submit(@Valid @RequestBody DepositRecord record) {
return Result.success(depositService.submit(record));
}
@Operation(summary = "管理端查看呈缴列表")
@GetMapping("/page")
public Result<PageResult<DepositRecord>> page(DepositQuery query) {
return Result.success(depositService.pageQuery(query));
}
@Operation(summary = "管理端查看呈缴详情")
@GetMapping("/{id}")
public Result<DepositRecord> detail(@PathVariable Long id) {
return Result.success(depositService.getById(id));
}
@Operation(summary = "管理端接收呈缴")
@PostMapping("/{id}/accept")
public Result<Void> accept(@PathVariable Long id,
@RequestParam(required = false) String auditRemark) {
depositService.audit(id, true, auditRemark);
return Result.success();
}
@Operation(summary = "管理端退回呈缴")
@PostMapping("/{id}/reject")
public Result<Void> reject(@PathVariable Long id,
@RequestParam(required = false) String auditRemark) {
depositService.audit(id, false, auditRemark);
return Result.success();
}
}
@@ -0,0 +1,27 @@
package com.banben.modules.deposit.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 呈缴记录查询条件。
*/
@Data
@Schema(description = "呈缴记录查询条件")
public class DepositQuery {
@Schema(description = "页码", example = "1")
private Long current = 1L;
@Schema(description = "每页条数", example = "20")
private Long size = 20L;
@Schema(description = "单位名称(模糊)")
private String orgName;
@Schema(description = "资源名称(模糊)")
private String resourceTitle;
@Schema(description = "状态:PENDING/ACCEPTED/REJECTED")
private String status;
}
@@ -0,0 +1,78 @@
package com.banben.modules.deposit.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 版本资源呈缴记录。
*/
@Data
@TableName("deposit_record")
@Schema(description = "版本资源呈缴记录")
public class DepositRecord implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@NotBlank(message = "呈缴单位名称不能为空")
@Schema(description = "呈缴单位名称")
private String orgName;
@NotBlank(message = "联系人不能为空")
@Schema(description = "联系人")
private String contact;
@NotBlank(message = "联系方式不能为空")
@Schema(description = "联系方式")
private String phone;
@Schema(description = "邮箱")
private String email;
@NotBlank(message = "版本资源名称不能为空")
@Schema(description = "版本资源名称")
private String resourceTitle;
@Schema(description = "媒体类型:纸质/电子")
private String mediaType;
@Schema(description = "简介")
private String summary;
@Schema(description = "备注")
private String remark;
@Schema(description = "数字版文件地址")
private String fileUrl;
@Schema(description = "状态:PENDING待审核 / ACCEPTED已接收 / REJECTED已退回")
private String status;
@Schema(description = "审核意见")
private String auditRemark;
@Schema(description = "审核时间")
private LocalDateTime auditTime;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "提交时间")
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
private LocalDateTime updateTime;
@TableLogic
@Schema(description = "逻辑删除")
private Integer deleted;
}
@@ -0,0 +1,12 @@
package com.banben.modules.deposit.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.deposit.entity.DepositRecord;
import org.apache.ibatis.annotations.Mapper;
/**
* 呈缴记录 Mapper。
*/
@Mapper
public interface DepositRecordMapper extends BaseMapper<DepositRecord> {
}
@@ -0,0 +1,29 @@
package com.banben.modules.deposit.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.common.PageResult;
import com.banben.modules.deposit.dto.DepositQuery;
import com.banben.modules.deposit.entity.DepositRecord;
/**
* 版本资源呈缴服务。
*/
public interface DepositService extends IService<DepositRecord> {
/**
* 提交呈缴(初始状态 PENDING)。
*/
Long submit(DepositRecord record);
/**
* 管理端分页查看。
*/
PageResult<DepositRecord> pageQuery(DepositQuery query);
/**
* 管理端审核:接收 / 退回。
*
* @param accepted true 接收,false 退回
*/
void audit(Long id, boolean accepted, String auditRemark);
}
@@ -0,0 +1,79 @@
package com.banben.modules.deposit.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException;
import com.banben.common.PageResult;
import com.banben.modules.deposit.dto.DepositQuery;
import com.banben.modules.deposit.entity.DepositRecord;
import com.banben.modules.deposit.mapper.DepositRecordMapper;
import com.banben.modules.deposit.service.DepositService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
/**
* 版本资源呈缴服务实现。
*
* <pre>
* 业务流转:用户提交(PENDING) → 管理员审核 → 接收(ACCEPTED) / 退回(REJECTED)
* 状态只会流转一次:已处理过的记录不允许再次审核(见 audit 方法)。
* </pre>
*/
@Service
public class DepositServiceImpl extends ServiceImpl<DepositRecordMapper, DepositRecord>
implements DepositService {
/** 待审核。 */
private static final String STATUS_PENDING = "PENDING";
/** 已接收。 */
private static final String STATUS_ACCEPTED = "ACCEPTED";
/** 已退回。 */
private static final String STATUS_REJECTED = "REJECTED";
/**
* 提交呈缴。
* 忽略前端传入的 id/status/审核字段,强制置为「待审核」,防止绕过审核流程。
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Long submit(DepositRecord record) {
record.setId(null);
record.setStatus(STATUS_PENDING);
record.setAuditRemark(null);
record.setAuditTime(null);
this.save(record);
return record.getId();
}
@Override
public PageResult<DepositRecord> pageQuery(DepositQuery query) {
LambdaQueryWrapper<DepositRecord> wrapper = new LambdaQueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(query.getOrgName()), DepositRecord::getOrgName, query.getOrgName())
.like(StrUtil.isNotBlank(query.getResourceTitle()), DepositRecord::getResourceTitle, query.getResourceTitle())
.eq(StrUtil.isNotBlank(query.getStatus()), DepositRecord::getStatus, query.getStatus())
.orderByDesc(DepositRecord::getCreateTime);
Page<DepositRecord> page = this.page(Page.of(query.getCurrent(), query.getSize()), wrapper);
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void audit(Long id, boolean accepted, String auditRemark) {
DepositRecord record = this.getById(id);
if (record == null) {
throw new BusinessException("呈缴记录不存在");
}
if (!STATUS_PENDING.equals(record.getStatus())) {
throw new BusinessException("该呈缴记录已处理,请勿重复操作");
}
record.setStatus(accepted ? STATUS_ACCEPTED : STATUS_REJECTED);
record.setAuditRemark(auditRemark);
record.setAuditTime(LocalDateTime.now());
this.updateById(record);
}
}
@@ -0,0 +1,55 @@
package com.banben.modules.governance.controller;
import com.banben.common.Result;
import com.banben.modules.governance.entity.GovernanceJob;
import com.banben.modules.governance.service.GovernanceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 数据治理接口。
*
* <p>对应「数据治理」四动作:聚同、优化、提示、提纯。</p>
*/
@Tag(name = "数据治理", description = "聚同 / 优化 / 提示 / 提纯")
@RestController
@RequestMapping("/api/governance")
@RequiredArgsConstructor
public class GovernanceController {
private final GovernanceService governanceService;
@Operation(summary = "聚同:聚合同一文献的多来源元数据")
@PostMapping("/merge")
public Result<GovernanceJob> merge() {
return Result.success(governanceService.runJob("MERGE"));
}
@Operation(summary = "优化:整合优化元数据描述")
@PostMapping("/optimize")
public Result<GovernanceJob> optimize() {
return Result.success(governanceService.runJob("OPTIMIZE"));
}
@Operation(summary = "提示:生成疑似同一文献/错漏提示清单")
@PostMapping("/hint")
public Result<GovernanceJob> hint() {
return Result.success(governanceService.runJob("HINT"));
}
@Operation(summary = "提纯:提取版本资源数据集")
@PostMapping("/purify")
public Result<GovernanceJob> purify() {
return Result.success(governanceService.runJob("PURIFY"));
}
@Operation(summary = "治理任务历史")
@GetMapping("/jobs")
public Result<List<GovernanceJob>> jobs() {
return Result.success(governanceService.listJobs());
}
}
@@ -0,0 +1,52 @@
package com.banben.modules.governance.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 数据治理任务。
*/
@Data
@TableName("governance_job")
@Schema(description = "数据治理任务")
public class GovernanceJob implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@Schema(description = "治理类型:MERGE聚同 / OPTIMIZE优化 / HINT提示 / PURIFY提纯")
private String jobType;
@Schema(description = "状态:PENDING/RUNNING/SUCCESS/FAILED")
private String status;
@Schema(description = "影响记录数")
private Integer affectedCount;
@Schema(description = "结果摘要")
private String resultSummary;
@Schema(description = "开始时间")
private LocalDateTime startTime;
@Schema(description = "结束时间")
private LocalDateTime endTime;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,12 @@
package com.banben.modules.governance.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.governance.entity.GovernanceJob;
import org.apache.ibatis.annotations.Mapper;
/**
* 治理任务 Mapper。
*/
@Mapper
public interface GovernanceJobMapper extends BaseMapper<GovernanceJob> {
}
@@ -0,0 +1,24 @@
package com.banben.modules.governance.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.governance.entity.GovernanceJob;
import java.util.List;
/**
* 数据治理服务(聚同 / 优化 / 提示 / 提纯)。
*/
public interface GovernanceService extends IService<GovernanceJob> {
/**
* 执行一次治理任务并记录。
*
* @param jobType MERGE / OPTIMIZE / HINT / PURIFY
*/
GovernanceJob runJob(String jobType);
/**
* 治理任务历史。
*/
List<GovernanceJob> listJobs();
}
@@ -0,0 +1,239 @@
package com.banben.modules.governance.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException;
import com.banben.modules.governance.entity.GovernanceJob;
import com.banben.modules.governance.mapper.GovernanceJobMapper;
import com.banben.modules.governance.service.GovernanceService;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.enums.GovernStatus;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 数据治理服务实现(聚同 / 优化 / 提示 / 提纯)。
*
* <pre>
* 【状态流转】每一步都会真实推进 record 的 govern_status:
*
* 采集入库 ──▶ RAW 原始
* │ ① 聚同(MERGE):同组保留 id 最小者 → MERGED 已聚同
* │ 同组其余记录 → MERGED_OUT 已合并(mergedToId 指向主记录)
* ▼
* MERGED 已聚同
* │ ② 优化(OPTIMIZE):无错漏的已聚同记录 → OPTIMIZED 已优化
* ▼
* OPTIMIZED 已优化
* │ ③ 提纯(PURIFY):纸电资源纳入数据集 → FINAL 已提纯
* ▼
* FINAL 已提纯
*
* ④ 提示(HINT):不改变状态,只产出清单,并把命中错漏的记录标记 abnormal_flag=1
* </pre>
*
* <p><b>说明:</b>本实现是可运行的「轻量算法」——聚同以「题名 + 责任者」判定同一文献;
* 生产环境可按需引入 ISBN/CDOI 等多要素判定与相似度算法。批处理逐条提交,
* 任务失败时已处理部分保留、任务记录标记为 FAILED,可重跑(已合并记录不会重复处理)。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, GovernanceJob>
implements GovernanceService {
/** 支持的治理类型。 */
private static final Set<String> JOB_TYPES = Set.of("MERGE", "OPTIMIZE", "HINT", "PURIFY");
private final VersionResourceMapper resourceMapper;
@Override
public GovernanceJob runJob(String jobType) {
if (jobType == null || !JOB_TYPES.contains(jobType.toUpperCase())) {
throw new BusinessException("不支持的治理类型:" + jobType);
}
String type = jobType.toUpperCase();
// 1) 先落一条 RUNNING 的任务记录,便于前端看到「执行中」
GovernanceJob job = new GovernanceJob();
job.setJobType(type);
job.setStatus("RUNNING");
job.setStartTime(LocalDateTime.now());
this.save(job);
try {
// 2) 按类型分派
switch (type) {
case "MERGE" -> runMerge(job);
case "OPTIMIZE" -> runOptimize(job);
case "HINT" -> runHint(job);
case "PURIFY" -> runPurify(job);
default -> job.setResultSummary("未实现");
}
job.setStatus("SUCCESS");
} catch (Exception e) {
log.error("治理任务执行失败: {}", e.getMessage(), e);
job.setStatus("FAILED");
job.setResultSummary(e.getMessage());
} finally {
// 3) 无论成败都回写任务结果
job.setEndTime(LocalDateTime.now());
this.updateById(job);
}
return job;
}
@Override
public List<GovernanceJob> listJobs() {
LambdaQueryWrapper<GovernanceJob> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByDesc(GovernanceJob::getCreateTime);
return this.list(wrapper);
}
// ==================== ① 聚同 ====================
/**
* 聚同:将「不同来源 / 不同媒体类型」的同一文献元数据聚合为一条,并标注来源。
*
* <p>判定规则(轻量版):<b>题名 + 责任者</b> 相同即视为同一文献。
* 同组内按 id 升序取第一条为主记录 → 标记 {@code MERGED};
* 其余记录 → 标记 {@code MERGED_OUT} 并把 {@code merged_to_id} 指向主记录。</p>
*
* <p>已 {@code MERGED_OUT} 的记录不参与再次聚同,因此任务可重复执行而结果稳定。</p>
*/
private void runMerge(GovernanceJob job) {
List<Map<String, Object>> groups = findDuplicateGroups();
int mergedGroups = 0;
int affected = 0;
for (Map<String, Object> group : groups) {
Object title = group.get("title");
Object author = group.get("author");
// 取出该组内仍「有效」的记录(排除已被合并的),按 id 升序
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.eq(VersionResource::getTitle, title)
.eq(author != null, VersionResource::getAuthor, author)
.isNull(author == null, VersionResource::getAuthor)
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode())
.orderByAsc(VersionResource::getId);
List<VersionResource> list = resourceMapper.selectList(query);
if (list.size() < 2) {
continue;
}
// 主记录:保留为「已聚同」
VersionResource master = list.get(0);
master.setGovernStatus(GovernStatus.MERGED.getCode());
master.setMergedToId(null);
resourceMapper.updateById(master);
affected++;
// 从记录:标记「已合并」并指向主记录
for (int i = 1; i < list.size(); i++) {
VersionResource slave = list.get(i);
slave.setGovernStatus(GovernStatus.MERGED_OUT.getCode());
slave.setMergedToId(master.getId());
resourceMapper.updateById(slave);
affected++;
}
mergedGroups++;
}
job.setAffectedCount(affected);
job.setResultSummary(String.format(
"聚同 %d 组、影响 %d 条(组内 id 最小者保留为「已聚同」,其余标记「已合并」并指向主记录)",
mergedGroups, affected));
}
// ==================== ② 优化 ====================
/**
* 优化:把「已聚同」且无错漏的元数据推进为「已优化」。
*
* <p>真正的字段级整合优化(多来源描述合并、要素补全)可在此基础上扩展,
* 当前实现负责状态推进与统计。</p>
*/
private void runOptimize(GovernanceJob job) {
LambdaUpdateWrapper<VersionResource> update = new LambdaUpdateWrapper<>();
update.set(VersionResource::getGovernStatus, GovernStatus.OPTIMIZED.getCode())
.eq(VersionResource::getGovernStatus, GovernStatus.MERGED.getCode())
.eq(VersionResource::getAbnormalFlag, 0);
int rows = resourceMapper.update(null, update);
job.setAffectedCount(rows);
job.setResultSummary("已将 " + rows + " 条「已聚同」且无错漏的元数据推进为「已优化」");
}
// ==================== ③ 提示 ====================
/**
* 提示:生成「疑似同一文献」与「疑似元数据错漏」清单。
*
* <p>这是唯一<b>不改变治理状态</b>的动作:它把命中错漏的记录标记
* {@code abnormal_flag = 1},供人工核验;清单本身体现在任务的 resultSummary 中。</p>
*/
private void runHint(GovernanceJob job) {
// 疑似同一文献:题名 + 责任者 相同且多于 1 条
int dupGroups = findDuplicateGroups().size();
// 疑似错漏:必备字段缺失(中图分类 / 摘要)→ 标记 abnormal_flag = 1
LambdaUpdateWrapper<VersionResource> missUpdate = new LambdaUpdateWrapper<>();
missUpdate.set(VersionResource::getAbnormalFlag, 1)
.and(x -> x.isNull(VersionResource::getClcCode)
.or().eq(VersionResource::getClcCode, "")
.or().isNull(VersionResource::getSummary)
.or().eq(VersionResource::getSummary, ""));
int missCount = resourceMapper.update(null, missUpdate);
job.setAffectedCount(dupGroups + missCount);
job.setResultSummary(String.format(
"疑似同一文献 %d 组;疑似元数据错漏 %d 条(已标记 abnormalFlag=1,请人工核验)",
dupGroups, missCount));
}
// ==================== ④ 提纯 ====================
/**
* 提纯:将相关纸电图书数据提取出来,形成版本资源数据集。
*
* <p>把媒体类型为「纸质 / 电子」且已聚同或已优化的记录标记为 {@code FINAL},
* 即「已纳入版本资源数据集」。</p>
*/
private void runPurify(GovernanceJob job) {
LambdaUpdateWrapper<VersionResource> update = new LambdaUpdateWrapper<>();
update.set(VersionResource::getGovernStatus, GovernStatus.FINAL.getCode())
.in(VersionResource::getMediaType, List.of("纸质", "电子"))
.in(VersionResource::getGovernStatus,
List.of(GovernStatus.MERGED.getCode(), GovernStatus.OPTIMIZED.getCode()));
int rows = resourceMapper.update(null, update);
job.setAffectedCount(rows);
job.setResultSummary("已将 " + rows + " 条纸电版本资源纳入版本资源数据集(标记为「已提纯」)");
}
// ==================== 公共方法 ====================
/**
* 查询「疑似同一文献」的重复组(题名 + 责任者 相同且多于 1 条)。
* 排除已被合并的记录,保证重复执行时不重复处理。
*/
private List<Map<String, Object>> findDuplicateGroups() {
QueryWrapper<VersionResource> dupWrapper = new QueryWrapper<>();
dupWrapper.select("title", "author")
.isNotNull("title")
.ne("govern_status", GovernStatus.MERGED_OUT.getCode())
.groupBy("title", "author")
.having("COUNT(*) > 1");
return resourceMapper.selectMaps(dupWrapper);
}
}
@@ -0,0 +1,76 @@
package com.banben.modules.resource.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.service.VersionResourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
* 版本资源元数据管理接口。
*
* <p>对应招标文件「版本资源数据集成库」的元数据维护能力。</p>
*
* <p><b>Controller 的写法约定(其他模块同理):</b></p>
* <ul>
* <li>只做「取参 → 调 Service → 包 Result」,不写业务逻辑;</li>
* <li>返回值统一为 {@code Result<T>},前端拿到的永远是
* {@code {code, message, data}};</li>
* <li>用 {@code @Tag/@Operation} 写接口文档,启动后可在 /swagger-ui.html 直接调试。</li>
* </ul>
*
* <p><b>调用示例(除登录外都需带 Token):</b></p>
* <pre>
* # 1. 先登录拿 token
* curl -X POST http://localhost:8080/api/auth/login \
* -H "Content-Type: application/json" \
* -d '{"username":"admin","password":"admin123"}'
*
* # 2. 分页查询(带 token)
* curl "http://localhost:8080/api/resource/page?current=1&size=20&title=版本" \
* -H "Authorization: Bearer {token}"
*
* # 3. 新增
* curl -X POST http://localhost:8080/api/resource \
* -H "Authorization: Bearer {token}" -H "Content-Type: application/json" \
* -d '{"title":"书名","mediaType":"纸质","clcCode":"G250"}'
* </pre>
*/
@Tag(name = "版本资源管理", description = "版本资源元数据 CRUD")
@RestController
@RequestMapping("/api/resource")
@RequiredArgsConstructor
public class VersionResourceController {
private final VersionResourceService versionResourceService;
@Operation(summary = "分页查询版本资源")
@GetMapping("/page")
public Result<PageResult<VersionResource>> page(VersionResourceQuery query) {
return Result.success(versionResourceService.pageQuery(query));
}
@Operation(summary = "查询单条版本资源")
@GetMapping("/{id}")
public Result<VersionResource> detail(@PathVariable Long id) {
return Result.success(versionResourceService.getById(id));
}
@Operation(summary = "新增或更新版本资源")
@PostMapping
public Result<Long> save(@Valid @RequestBody VersionResource resource) {
return Result.success(versionResourceService.saveOrUpdateResource(resource));
}
@Operation(summary = "删除版本资源")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
versionResourceService.removeById(id);
return Result.success();
}
}
@@ -0,0 +1,39 @@
package com.banben.modules.resource.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 版本资源分页查询条件。
*/
@Data
@Schema(description = "版本资源查询条件")
public class VersionResourceQuery {
@Schema(description = "页码,从1开始", example = "1")
private Long current = 1L;
@Schema(description = "每页条数", example = "50")
private Long size = 50L;
@Schema(description = "正题名(模糊)")
private String title;
@Schema(description = "责任者(模糊)")
private String author;
@Schema(description = "中图分类号")
private String clcCode;
@Schema(description = "媒体类型:纸质/电子")
private String mediaType;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "出版年份")
private String publishYear;
@Schema(description = "治理状态:RAW原始 / MERGED已聚同 / OPTIMIZED已优化 / FINAL已提纯 / MERGED_OUT已合并")
private String governStatus;
}
@@ -0,0 +1,157 @@
package com.banben.modules.resource.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 版本资源元数据。
*
* <p>字段依据询价文件「单条版本资源元数据采集要素及存储标准」设计:
* 必备字段 + 有则必备字段,原始数据为空或错指的保留空值。</p>
*/
@Data
@TableName("version_resource")
@Schema(description = "版本资源元数据")
public class VersionResource implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键ID")
private Long id;
// ==================== 必备字段 ====================
@Schema(description = "加工编号(必备)")
private String processNo;
@Schema(description = "正题名(必备)")
private String title;
@Schema(description = "中图分类号(必备,CLC第五版)")
private String clcCode;
@Schema(description = "主题词或关键词(必备,CCT标引,分隔符;)")
private String keywords;
@Schema(description = "摘要(必备,不少于100字)")
private String summary;
@Schema(description = "出版年份(必备,yyyy)")
private String publishYear;
@Schema(description = "加工日期(必备,yyyyMMdd)")
private String processDate;
@Schema(description = "内容形式(必备,GB/T 3469-2013)")
private String contentForm;
@Schema(description = "媒体类型(必备:纸质/电子)")
private String mediaType;
@Schema(description = "格式(必备,英文大写,如 TIF;PDF)")
private String format;
@Schema(description = "页码(必备)")
private String pageCount;
@Schema(description = "语种(必备,3位语种代码)")
private String language;
@Schema(description = "数据提交单位(必备)")
private String submitOrg;
@Schema(description = "所属任务年份(必备)")
private String taskYear;
@Schema(description = "来源馆(必备)")
private String sourceLibrary;
@Schema(description = "来源馆地址(必备,IP:端口或域名)")
private String sourceLibraryAddr;
@Schema(description = "全文地址(必备,根据CDOI生成)")
private String fulltextUrl;
// ==================== 有则必备字段 ====================
@Schema(description = "其他题名(有则必备)")
private String otherTitle;
@Schema(description = "责任者名称(有则必备)")
private String author;
@Schema(description = "责任方式(有则必备)")
private String responsibility;
@Schema(description = "附注(有则必备)")
private String note;
@Schema(description = "出版者名称(有则必备)")
private String publisher;
@Schema(description = "出版地(有则必备)")
private String publishPlace;
@Schema(description = "出版日期(有则必备)")
private String publishDate;
@Schema(description = "关联(有则必备)")
private String relation;
@Schema(description = "时间范围(有则必备)")
private String timeRange;
@Schema(description = "空间范围(有则必备)")
private String spaceRange;
@Schema(description = "版本/版次(有则必备)")
private String edition;
@Schema(description = "ISBN(有则必备)")
private String isbn;
@Schema(description = "统一书号(有则必备)")
private String unifiedBookNo;
@Schema(description = "CDOI(有则必备)")
private String cdoi;
@Schema(description = "发布地址(有则必备)")
private String publishUrl;
// ==================== 治理与系统字段 ====================
// 注意:以下字段均【不是】招标文件要求的著录要素,
// 而是系统为跟踪治理进度 / 做统计分析而增加的辅助字段。
/**
* 数据治理状态,取值见 {@link com.banben.modules.resource.enums.GovernStatus}。
* 流转:RAW 原始 → MERGED 已聚同 → OPTIMIZED 已优化 → FINAL 已提纯;
* MERGED_OUT 表示本条已被聚同合并到主记录(见 {@link #mergedToId})。
*/
@Schema(description = "数据治理状态:RAW原始 / MERGED已聚同 / OPTIMIZED已优化 / FINAL已提纯 / MERGED_OUT已合并")
private String governStatus;
@Schema(description = "聚同后指向的主记录ID(仅 MERGED_OUT 记录有值)")
private Long mergedToId;
@Schema(description = "疑似错漏标记:0正常 1疑似(由「提示」治理任务标记,待人工核验)")
private Integer abnormalFlag;
@Schema(description = "数据密级/敏感词标记:0正常 1敏感")
private Integer sensitiveFlag;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
private LocalDateTime updateTime;
@TableLogic
@Schema(description = "逻辑删除:0未删 1已删")
private Integer deleted;
}
@@ -0,0 +1,82 @@
package com.banben.modules.resource.enums;
import lombok.Getter;
import java.util.Arrays;
/**
* 数据治理状态。
*
* <pre>
* ⚠️ 说明:本字段<b>不是招标文件要求的著录要素</b>,而是系统为跟踪治理进度
* 自行增加的辅助字段(与 sensitive_flag / deleted 同类)。
*
* 状态流转(与招标「数据治理」四动作对齐):
*
* 数据采集
* ↓
* RAW 原始 ──聚同──▶ MERGED 已聚同 ──优化──▶ OPTIMIZED 已优化 ──提纯──▶ FINAL 已提纯
* │
* └─ 同组中被合并掉的记录 → MERGED_OUT 已合并(mergedToId 指向主记录)
*
* 「提示」动作不改变上述状态,它产出的是"疑似同一文献/疑似错漏"清单,
* 命中错漏的记录由 abnormal_flag 字段标记(见 {@link com.banben.modules.resource.entity.VersionResource#abnormalFlag})。
* </pre>
*
* <p><b>为什么数据库存英文码值?</b>码值稳定、便于代码判断与索引;
* 中文名称由 {@link #getLabel()} 提供或前端字典映射,仅用于展示。</p>
*/
@Getter
public enum GovernStatus {
/** 原始:刚采集入库,未做任何治理。 */
RAW("原始", "刚采集入库,未做任何治理"),
/** 已聚同:同一文献已聚合为一条数据,并标注来源。 */
MERGED("已聚同", "同一文献已聚合为一条,并标注来源"),
/** 已优化:元数据描述已整合优化。 */
OPTIMIZED("已优化", "元数据描述已整合优化,质量更完整"),
/** 已提纯:已纳入版本资源数据集。 */
FINAL("已提纯", "已纳入版本资源数据集"),
/** 已合并:本条记录已被聚同合并到主记录(见 mergedToId)。 */
MERGED_OUT("已合并", "本条已被聚同合并到主记录");
/** 中文名称(用于展示)。 */
private final String label;
/** 状态说明。 */
private final String description;
GovernStatus(String label, String description) {
this.label = label;
this.description = description;
}
/**
* 码值(即枚举名,如 RAW)。
* 数据库存储、前后端传输都用它,避免直接依赖 enum 类型。
*/
public String getCode() {
return name();
}
/**
* 按码值取中文名称(前端若无法解析枚举时使用)。
*
* @param code 状态码(如 RAW)
* @return 中文名称;未匹配时原样返回 code
*/
public static String labelOf(String code) {
if (code == null) {
return null;
}
return Arrays.stream(values())
.filter(s -> s.name().equalsIgnoreCase(code))
.map(GovernStatus::getLabel)
.findFirst()
.orElse(code);
}
}
@@ -0,0 +1,12 @@
package com.banben.modules.resource.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.resource.entity.VersionResource;
import org.apache.ibatis.annotations.Mapper;
/**
* 版本资源 Mapper。
*/
@Mapper
public interface VersionResourceMapper extends BaseMapper<VersionResource> {
}
@@ -0,0 +1,22 @@
package com.banben.modules.resource.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.common.PageResult;
import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource;
/**
* 版本资源服务接口。
*/
public interface VersionResourceService extends IService<VersionResource> {
/**
* 分页查询版本资源元数据。
*/
PageResult<VersionResource> pageQuery(VersionResourceQuery query);
/**
* 保存或更新版本资源。
*/
Long saveOrUpdateResource(VersionResource resource);
}
@@ -0,0 +1,74 @@
package com.banben.modules.resource.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.PageResult;
import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import com.banben.modules.resource.service.VersionResourceService;
import org.springframework.stereotype.Service;
/**
* 版本资源服务实现 —— <b>本项目 CRUD 的样板实现</b>。
*
* <pre>
* 关键点:
* 1. 继承 ServiceImpl&lt;Mapper, Entity&gt; 即可获得 save/updateById/removeById/getById/list/page
* 等常用方法,无需自己写 SQL;
* 2. 继承 IService,Controller 只依赖接口,便于替换实现或做单元测试;
* 3. 条件查询使用 LambdaQueryWrapper —— 用方法引用(如 VersionResource::getTitle)
* 代替字符串列名,编译器可校验,重构安全;
* 4. 每个条件都带「是否为空判断」,因此同一个方法能支撑所有组合查询。
* </pre>
*/
@Service
public class VersionResourceServiceImpl
extends ServiceImpl<VersionResourceMapper, VersionResource>
implements VersionResourceService {
/**
* 分页 + 多条件查询版本资源。
*
* <p>所有条件都是「有值才生效」:例如只传 title,就只按题名过滤;
* 全部不传则等价于查询全部(配合分页)。</p>
*
* @param query 查询条件(页码、每页条数、题名、作者、分类、媒体类型、来源馆、年份)
* @return 统一分页结构(含当前页数据与总数)
*/
@Override
public PageResult<VersionResource> pageQuery(VersionResourceQuery query) {
// 1) 拼装动态条件:StrUtil.isNotBlank(x) 为 false 时该条件不会进入 SQL
LambdaQueryWrapper<VersionResource> wrapper = new LambdaQueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(query.getTitle()), VersionResource::getTitle, query.getTitle())
.like(StrUtil.isNotBlank(query.getAuthor()), VersionResource::getAuthor, query.getAuthor())
.eq(StrUtil.isNotBlank(query.getClcCode()), VersionResource::getClcCode, query.getClcCode())
.eq(StrUtil.isNotBlank(query.getMediaType()), VersionResource::getMediaType, query.getMediaType())
.eq(StrUtil.isNotBlank(query.getSourceLibrary()), VersionResource::getSourceLibrary, query.getSourceLibrary())
.eq(StrUtil.isNotBlank(query.getPublishYear()), VersionResource::getPublishYear, query.getPublishYear())
.eq(StrUtil.isNotBlank(query.getGovernStatus()), VersionResource::getGovernStatus, query.getGovernStatus())
// 2) 默认按入库时间倒序,最新数据在前
.orderByDesc(VersionResource::getCreateTime);
// 3) 执行分页查询(分页插件自动追加 LIMIT/OFFSET 与 COUNT)
Page<VersionResource> page = this.page(
Page.of(query.getCurrent(), query.getSize()), wrapper);
// 4) 转换成与前端约定的 PageResult 结构
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
}
/**
* 新增或更新。
*
* <p>MyBatis-Plus 的 {@code saveOrUpdate}:主键为空 → INSERT;主键存在 → UPDATE。
* 返回主键,便于前端拿到新记录 ID。</p>
*/
@Override
public Long saveOrUpdateResource(VersionResource resource) {
this.saveOrUpdate(resource);
return resource.getId();
}
}
@@ -0,0 +1,91 @@
package com.banben.modules.search.controller;
import com.banben.common.Result;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.search.dto.SearchQuery;
import com.banben.modules.search.service.SearchService;
import com.banben.modules.search.vo.SearchResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 版本资源检索发现接口。
*
* <p>对应招标文件「版本资源联合服务站点 - 检索发现模块」。</p>
*
* <p><b>接口用法:</b></p>
* <ul>
* <li><b>统一检索</b> {@code GET /api/search/unified?keyword=xxx}:
* 适合单框检索,返回「结果 + 分面 + 年度发文量」。</li>
* <li><b>高级检索</b> {@code GET /api/search/advanced}:
* 支持 title/author/publisher/clcCode/mediaType/publishYearStart|End/
* matchType(EQ|LEFT|RIGHT|LIKE) 等组合条件。</li>
* <li><b>分页检索</b> {@code POST /api/search/page}:
* POST 传 JSON,适合「多来源多选」等数组条件。</li>
* <li><b>细览</b> {@code GET /api/search/detail/{id}}、
* <b>相似文献</b> {@code GET /api/search/similar/{id}}。</li>
* <li><b>导出数据</b> {@code POST /api/search/list}:返回最多 1 万条,供前端生成 Excel。</li>
* </ul>
*
* <p>说明:每次检索都会写入 search_log,用于「热门检索词」与「用户活跃度」统计。</p>
*/
@Tag(name = "检索发现", description = "统一检索 / 高级检索 / 细览 / 相似推荐 / 导出")
@RestController
@RequestMapping("/api/search")
@RequiredArgsConstructor
public class SearchController {
private final SearchService searchService;
@Operation(summary = "统一检索(初级检索,含分面与年度统计)")
@GetMapping("/unified")
public Result<SearchResultVO> unified(SearchQuery query, HttpServletRequest request) {
return Result.success(searchService.search(query, clientIp(request)));
}
@Operation(summary = "高级检索(多字段 + 多精度 + 多逻辑)")
@GetMapping("/advanced")
public Result<SearchResultVO> advanced(SearchQuery query, HttpServletRequest request) {
return Result.success(searchService.advancedSearch(query, clientIp(request)));
}
@Operation(summary = "分页检索结果(简洁版,仅返回列表)")
@PostMapping("/page")
public Result<SearchResultVO> page(@RequestBody SearchQuery query, HttpServletRequest request) {
return Result.success(searchService.search(query, clientIp(request)));
}
@Operation(summary = "文献细览")
@GetMapping("/detail/{id}")
public Result<VersionResource> detail(@PathVariable Long id) {
return Result.success(searchService.detail(id));
}
@Operation(summary = "相似文献推荐")
@GetMapping("/similar/{id}")
public Result<List<VersionResource>> similar(@PathVariable Long id,
@RequestParam(defaultValue = "10") int limit) {
return Result.success(searchService.similar(id, limit));
}
@Operation(summary = "检索结果列表(用于导出/批量处理,最多 10000 条)")
@PostMapping("/list")
public Result<List<VersionResource>> list(@RequestBody SearchQuery query) {
return Result.success(searchService.exportList(query, 10000));
}
private String clientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isBlank()) {
ip = request.getRemoteAddr();
} else {
ip = ip.split(",")[0].trim();
}
return ip;
}
}
@@ -0,0 +1,72 @@
package com.banben.modules.search.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 统一检索/高级检索查询条件。
*
* <p>对应询价文件「统一检索工具」:多类型、多途径、多来源、多逻辑、多精度、多语种、限定出版时段。</p>
*/
@Data
@Schema(description = "检索查询条件")
public class SearchQuery {
@Schema(description = "页码,从1开始", example = "1")
private Long current = 1L;
@Schema(description = "每页条数", example = "50")
private Long size = 50L;
/** ---------------- 多途径(字段) ---------------- */
@Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)")
private String keyword;
@Schema(description = "题名")
private String title;
@Schema(description = "责任者")
private String author;
@Schema(description = "出版者")
private String publisher;
@Schema(description = "ISBN")
private String isbn;
@Schema(description = "CDOI")
private String cdoi;
@Schema(description = "中图分类号(前方一致)")
private String clcCode;
/** ---------------- 多类型/多来源 ---------------- */
@Schema(description = "媒体类型:纸质/电子")
private String mediaType;
@Schema(description = "来源馆(多选)")
private List<String> sourceLibraries;
/** ---------------- 限定出版时段 ---------------- */
@Schema(description = "出版年份起(含)", example = "2000")
private String publishYearStart;
@Schema(description = "出版年份止(含)", example = "2026")
private String publishYearEnd;
/** ---------------- 多精度 ---------------- */
@Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)")
private String matchType = "LIKE";
@Schema(description = "多字段逻辑:AND(默认) / OR")
private String logic = "AND";
/** ---------------- 排序 ---------------- */
@Schema(description = "排序字段:publishYear / createTime / relevance(默认)")
private String orderBy;
@Schema(description = "排序方向:asc / desc(默认)")
private String orderDir = "desc";
}
@@ -0,0 +1,43 @@
package com.banben.modules.search.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 检索行为日志(用于热门检索词、用户行为分析)。
*/
@Data
@TableName("search_log")
@Schema(description = "检索行为日志")
public class SearchLog implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@Schema(description = "检索关键词")
private String keyword;
@Schema(description = "用户IP")
private String userIp;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "命中结果数")
private Integer resultCount;
@Schema(description = "耗时(ms)")
private Long costMs;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -0,0 +1,12 @@
package com.banben.modules.search.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.search.entity.SearchLog;
import org.apache.ibatis.annotations.Mapper;
/**
* 检索日志 Mapper。
*/
@Mapper
public interface SearchLogMapper extends BaseMapper<SearchLog> {
}
@@ -0,0 +1,38 @@
package com.banben.modules.search.service;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.search.dto.SearchQuery;
import com.banben.modules.search.vo.SearchResultVO;
import java.util.List;
/**
* 检索发现服务。
*/
public interface SearchService {
/**
* 统一检索(初级检索),返回结果 + 分面 + 年度统计。
*/
SearchResultVO search(SearchQuery query, String userIp);
/**
* 高级检索(多字段组合、多精度、多逻辑)。
*/
SearchResultVO advancedSearch(SearchQuery query, String userIp);
/**
* 文献细览。
*/
VersionResource detail(Long id);
/**
* 相似文献推荐(按中图分类号 + 关键词共现)。
*/
List<VersionResource> similar(Long id, int limit);
/**
* 导出检索结果(上限 {@code limit} 条)。
*/
List<VersionResource> exportList(SearchQuery query, int limit);
}
@@ -0,0 +1,286 @@
package com.banben.modules.search.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.PageResult;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import com.banben.modules.search.dto.SearchQuery;
import com.banben.modules.search.entity.SearchLog;
import com.banben.modules.search.mapper.SearchLogMapper;
import com.banben.modules.search.service.SearchService;
import com.banben.modules.search.vo.FacetItem;
import com.banben.modules.search.vo.SearchResultVO;
import com.banben.modules.search.vo.YearStat;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 检索发现服务实现。
*
* <p>基于瀚高/PostgreSQL 的元数据表实现统一检索、分面聚类、年度统计。
* 数据量级为元数据(≤ 百万级),无需引入独立检索引擎即可满足;
* 后续若需复杂相关度排序,可平滑替换为瀚高全文检索或 Easysearch。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements SearchService {
/** 分面最多返回的类目数 */
private static final int FACET_TOP = 20;
private final VersionResourceMapper resourceMapper;
private final SearchLogMapper searchLogMapper;
@Override
public SearchResultVO search(SearchQuery query, String userIp) {
long start = System.currentTimeMillis();
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
applyOrder(wrapper, query);
Page<VersionResource> page = resourceMapper.selectPage(
Page.of(query.getCurrent(), query.getSize()), wrapper);
SearchResultVO vo = new SearchResultVO();
vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize()));
vo.setMediaTypeFacets(facet(query, "media_type"));
vo.setSourceLibraryFacets(facet(query, "source_library"));
vo.setClcFacets(facet(query, "clc_code"));
vo.setYearStats(yearStats(query));
long cost = System.currentTimeMillis() - start;
vo.setCostMs(cost);
saveSearchLog(query, userIp, (int) page.getTotal(), cost);
return vo;
}
@Override
public SearchResultVO advancedSearch(SearchQuery query, String userIp) {
// 高级检索与统一检索共用条件构造器,区别在于前端传入更细的字段条件
return search(query, userIp);
}
@Override
public VersionResource detail(Long id) {
return resourceMapper.selectById(id);
}
@Override
public List<VersionResource> similar(Long id, int limit) {
VersionResource current = resourceMapper.selectById(id);
if (current == null) {
return Collections.emptyList();
}
String clcPrefix = StrUtil.isNotBlank(current.getClcCode())
? StrUtil.subPre(current.getClcCode(), 3) : null;
String keyword = firstKeyword(current.getKeywords());
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.eq("deleted", 0).ne("id", id);
if (clcPrefix != null || keyword != null) {
wrapper.and(x -> {
boolean appended = false;
if (clcPrefix != null) {
x.likeRight("clc_code", clcPrefix);
appended = true;
}
if (keyword != null) {
if (appended) {
x.or();
}
x.like("keywords", keyword);
}
});
}
wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper);
}
@Override
public List<VersionResource> exportList(SearchQuery query, int limit) {
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
applyOrder(wrapper, query);
wrapper.last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper);
}
// ==================== 内部方法 ====================
/**
* 构造查询条件(多途径 / 多类型 / 多来源 / 多精度 / 限定出版时段)。
*/
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) {
QueryWrapper<VersionResource> w = new QueryWrapper<>();
w.eq("deleted", 0);
// 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者
if (StrUtil.isNotBlank(q.getKeyword())) {
String kw = q.getKeyword().trim();
w.and(x -> x.like("title", kw).or().like("author", kw).or()
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw));
}
applyMatch(w, "title", q.getTitle(), q.getMatchType());
applyMatch(w, "author", q.getAuthor(), q.getMatchType());
applyMatch(w, "publisher", q.getPublisher(), q.getMatchType());
applyMatch(w, "isbn", q.getIsbn(), q.getMatchType());
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
if (StrUtil.isNotBlank(q.getClcCode())) {
w.likeRight("clc_code", q.getClcCode().trim());
}
if (StrUtil.isNotBlank(q.getMediaType())) {
w.eq("media_type", q.getMediaType());
}
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
w.in("source_library", q.getSourceLibraries());
}
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
w.ge("publish_year", q.getPublishYearStart().trim());
}
if (StrUtil.isNotBlank(q.getPublishYearEnd())) {
w.le("publish_year", q.getPublishYearEnd().trim());
}
return w;
}
/**
* 多精度匹配:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊。
*/
private void applyMatch(QueryWrapper<VersionResource> w, String column, String value, String matchType) {
if (StrUtil.isBlank(value)) {
return;
}
String v = value.trim();
String type = matchType == null ? "LIKE" : matchType.toUpperCase();
switch (type) {
case "EQ" -> w.eq(column, v);
case "LEFT" -> w.likeRight(column, v);
case "RIGHT" -> w.likeLeft(column, v);
default -> w.like(column, v);
}
}
/**
* 排序:精确检索默认按发行时间降序,支持自定义排序字段。
*/
private void applyOrder(QueryWrapper<VersionResource> w, SearchQuery q) {
boolean asc = "asc".equalsIgnoreCase(q.getOrderDir());
String by = q.getOrderBy();
if ("publishYear".equalsIgnoreCase(by)) {
w.orderBy(true, asc, "publish_year");
} else if ("createTime".equalsIgnoreCase(by)) {
w.orderBy(true, asc, "create_time");
} else {
w.orderByDesc("publish_year");
}
}
/**
* 分面聚类统计(概览页左侧的「资源类型 / 来源院校 / 中图分类」各有多少条)。
*
* <p><b>实现要点:</b>复用与检索同一套 {@link #buildWrapper(SearchQuery)} 条件,
* 因此分面数字始终与当前检索结果一致;再通过 {@code selectMaps} + {@code GROUP BY}
* 让数据库直接做聚合(比查回内存再统计高效得多),结果形如:</p>
* <pre>
* SELECT media_type AS name, COUNT(*) AS cnt
* FROM version_resource
* WHERE deleted=0 AND (…检索条件…)
* GROUP BY media_type ORDER BY cnt DESC LIMIT 20
* </pre>
*
* @param column 参与分组的列(media_type / source_library / clc_code)
*/
private List<FacetItem> facet(SearchQuery query, String column) {
QueryWrapper<VersionResource> w = buildWrapper(query);
w.select(column + " AS name", "COUNT(*) AS cnt")
.isNotNull(column)
.ne(column, "")
.groupBy(column)
.orderByDesc("cnt")
.last("limit " + FACET_TOP);
List<Map<String, Object>> maps = resourceMapper.selectMaps(w);
List<FacetItem> items = new ArrayList<>();
for (Map<String, Object> m : maps) {
Object name = m.get("name");
if (name == null) {
continue;
}
items.add(new FacetItem(String.valueOf(name), toLong(m.get("cnt"))));
}
return items;
}
/**
* 命中文献各年份发文量。
*/
private List<YearStat> yearStats(SearchQuery query) {
QueryWrapper<VersionResource> w = buildWrapper(query);
w.select("publish_year AS name", "COUNT(*) AS cnt")
.isNotNull("publish_year")
.ne("publish_year", "")
.groupBy("publish_year")
.orderByAsc("publish_year");
List<Map<String, Object>> maps = resourceMapper.selectMaps(w);
List<YearStat> stats = new ArrayList<>();
for (Map<String, Object> m : maps) {
Object year = m.get("name");
if (year == null) {
continue;
}
stats.add(new YearStat(String.valueOf(year), toLong(m.get("cnt"))));
}
return stats;
}
private void saveSearchLog(SearchQuery query, String userIp, int resultCount, long cost) {
String keyword = StrUtil.isNotBlank(query.getKeyword()) ? query.getKeyword() : query.getTitle();
if (StrUtil.isBlank(keyword)) {
return;
}
try {
SearchLog entity = new SearchLog();
entity.setKeyword(StrUtil.subPre(keyword.trim(), 500));
entity.setUserIp(userIp);
entity.setResultCount(resultCount);
entity.setCostMs(cost);
searchLogMapper.insert(entity);
} catch (Exception e) {
log.warn("记录检索日志失败:{}", e.getMessage());
}
}
private String firstKeyword(String keywords) {
if (StrUtil.isBlank(keywords)) {
return null;
}
String first = StrUtil.split(keywords, ';').stream()
.filter(StrUtil::isNotBlank)
.findFirst()
.orElse(null);
if (first == null) {
first = StrUtil.split(keywords, ';').stream()
.filter(StrUtil::isNotBlank)
.findFirst()
.orElse(null);
}
return first == null ? null : first.trim();
}
private Long toLong(Object value) {
return value instanceof Number number ? number.longValue() : 0L;
}
}
@@ -0,0 +1,22 @@
package com.banben.modules.search.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 分面聚类项。
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "分面项")
public class FacetItem {
@Schema(description = "分面名称")
private String name;
@Schema(description = "命中数量")
private Long value;
}
@@ -0,0 +1,36 @@
package com.banben.modules.search.vo;
import com.banben.common.PageResult;
import com.banben.modules.resource.entity.VersionResource;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 检索结果聚合返回。
*
* <p>包含结果列表、分面聚类、年度发文量、检索耗时,对应概览页展示要求。</p>
*/
@Data
@Schema(description = "检索结果")
public class SearchResultVO {
@Schema(description = "结果分页")
private PageResult<VersionResource> page;
@Schema(description = "资源类型分面")
private List<FacetItem> mediaTypeFacets;
@Schema(description = "来源院校分面")
private List<FacetItem> sourceLibraryFacets;
@Schema(description = "中图分类分面")
private List<FacetItem> clcFacets;
@Schema(description = "命中文献各年份发文量")
private List<YearStat> yearStats;
@Schema(description = "检索耗时(ms)")
private Long costMs;
}
@@ -0,0 +1,22 @@
package com.banben.modules.search.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 年度发文量统计项(用于检索结果折线图)。
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "年度发文量")
public class YearStat {
@Schema(description = "年份")
private String year;
@Schema(description = "数量")
private Long count;
}
@@ -0,0 +1,58 @@
package com.banben.modules.special.controller;
import com.banben.common.Result;
import com.banben.modules.special.entity.SpecialResource;
import com.banben.modules.special.service.SpecialService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 特藏版本推荐展示接口。
*
* <p>对应「特藏版本推荐展示模块」:首页推荐与细览,管理端可维护。</p>
*/
@Tag(name = "特藏版本推荐", description = "首页推荐与细览")
@RestController
@RequestMapping("/api/special")
@RequiredArgsConstructor
public class SpecialController {
private final SpecialService specialService;
@Operation(summary = "首页推荐特藏列表")
@GetMapping("/recommend")
public Result<List<SpecialResource>> recommend(@RequestParam(defaultValue = "8") int limit) {
return Result.success(specialService.recommend(limit));
}
@Operation(summary = "特藏细览")
@GetMapping("/{id}")
public Result<SpecialResource> detail(@PathVariable Long id) {
return Result.success(specialService.getById(id));
}
@Operation(summary = "管理端特藏列表")
@GetMapping("/admin/list")
public Result<List<SpecialResource>> adminList() {
return Result.success(specialService.adminList());
}
@Operation(summary = "管理端新增/更新特藏")
@PostMapping("/admin")
public Result<Long> save(@Valid @RequestBody SpecialResource resource) {
specialService.saveOrUpdate(resource);
return Result.success(resource.getId());
}
@Operation(summary = "管理端删除特藏")
@DeleteMapping("/admin/{id}")
public Result<Void> remove(@PathVariable Long id) {
specialService.removeById(id);
return Result.success();
}
}
@@ -0,0 +1,57 @@
package com.banben.modules.special.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 特藏版本资源。
*/
@Data
@TableName("special_resource")
@Schema(description = "特藏版本资源")
public class SpecialResource implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@NotBlank(message = "特藏名称不能为空")
@Schema(description = "特藏名称")
private String name;
@Schema(description = "简介")
private String summary;
@Schema(description = "类别")
private String category;
@Schema(description = "图片地址")
private String coverUrl;
@Schema(description = "电子版下载地址")
private String ebookUrl;
@Schema(description = "排序号")
private Integer sortNo;
@Schema(description = "状态:1展示 0隐藏")
private Integer status;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,12 @@
package com.banben.modules.special.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.special.entity.SpecialResource;
import org.apache.ibatis.annotations.Mapper;
/**
* 特藏资源 Mapper。
*/
@Mapper
public interface SpecialResourceMapper extends BaseMapper<SpecialResource> {
}
@@ -0,0 +1,22 @@
package com.banben.modules.special.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.special.entity.SpecialResource;
import java.util.List;
/**
* 特藏版本推荐服务。
*/
public interface SpecialService extends IService<SpecialResource> {
/**
* 首页推荐特藏(仅展示 status=1,按 sort_no 排序)。
*/
List<SpecialResource> recommend(int limit);
/**
* 管理端列表。
*/
List<SpecialResource> adminList();
}
@@ -0,0 +1,36 @@
package com.banben.modules.special.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.modules.special.entity.SpecialResource;
import com.banben.modules.special.mapper.SpecialResourceMapper;
import com.banben.modules.special.service.SpecialService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 特藏版本推荐服务实现。
*/
@Service
public class SpecialServiceImpl extends ServiceImpl<SpecialResourceMapper, SpecialResource>
implements SpecialService {
@Override
public List<SpecialResource> recommend(int limit) {
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SpecialResource::getStatus, 1)
.orderByAsc(SpecialResource::getSortNo)
.orderByDesc(SpecialResource::getCreateTime)
.last("limit " + Math.max(1, limit));
return this.list(wrapper);
}
@Override
public List<SpecialResource> adminList() {
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByAsc(SpecialResource::getSortNo)
.orderByDesc(SpecialResource::getCreateTime);
return this.list(wrapper);
}
}
@@ -0,0 +1,29 @@
# 开发环境:连接 10.1.1.14 上 Docker 部署的瀚高数据库(HighGo,兼容 PostgreSQL 协议)
#
# 说明:
# 1. 瀚高与 PostgreSQL 协议兼容,使用 org.postgresql.Driver 即可连通。
# 2. 数据库信息(已部署):
# host=10.1.1.14 port=5866 database=banben username=highgo password=Highgo@2026
# 3. 表结构已通过 deploy/db/init.sql 导入,故此处不再自动执行建表脚本。
# 4. 如需连接本地 PostgreSQL 开发,可通过环境变量覆盖:
# DB_HOST=localhost DB_PORT=5432 DB_NAME=banben DB_USER=banben DB_PASSWORD=banben123
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://${DB_HOST:10.1.1.14}:${DB_PORT:5866}/${DB_NAME:banben}?stringtype=unspecified
username: ${DB_USER:highgo}
password: ${DB_PASSWORD:Highgo@2026}
hikari:
minimum-idle: 5
maximum-pool-size: 20
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
sql:
init:
# 远端库已导入表结构,避免每次启动重复执行
mode: never
logging:
level:
com.banben: debug
@@ -0,0 +1,31 @@
# 生产环境:国产化信创环境 —— 瀚高数据库(HighGo,兼容 PostgreSQL 协议)
#
# 说明:
# 1. 瀚高与 PostgreSQL 协议兼容,默认可直接使用 org.postgresql.Driver。
# 2. 若使用瀚高官方驱动,请:
# - 在 pom.xml 引入瀚高 JDBC 依赖(com.highgo:HgdbJdbc)
# - 将 driver-class-name 改为 com.highgo.jdbc.Driver
# - 将 url 改为 jdbc:highgo://host:5866/banben (瀚高默认端口 5866)
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://${DB_HOST:127.0.0.1}:${DB_PORT:5432}/${DB_NAME:banben}?stringtype=unspecified
username: ${DB_USER:highgo}
password: ${DB_PASSWORD:highgo}
hikari:
minimum-idle: 10
maximum-pool-size: 50
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
sql:
init:
# 生产环境默认不自动执行脚本,由部署脚本初始化
mode: never
logging:
level:
root: info
com.banben: info
file:
name: /app/logs/banben-backend.log
@@ -0,0 +1,52 @@
server:
port: 8080
servlet:
encoding:
charset: UTF-8
force: true
spring:
application:
name: banben-backend
profiles:
active: dev
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
default-property-inclusion: non_null
servlet:
multipart:
max-file-size: 200MB
max-request-size: 500MB
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
banner: false
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
springdoc:
swagger-ui:
path: /swagger-ui.html
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: always
# 业务自定义配置
banben:
jwt:
# 生产环境请替换为更安全的密钥(长度 >= 32 字节),并通过环境变量注入
secret: ${JWT_SECRET:banben-version-resource-system-jwt-secret-key-2026}
expire-hours: 12
+21
View File
@@ -0,0 +1,21 @@
-- =====================================================================
-- 样例数据(仅开发/演示使用,生产环境不加载)
-- =====================================================================
INSERT INTO version_resource
(id, process_no, title, clc_code, keywords, summary, publish_year, process_date,
content_form, media_type, format, page_count, language, submit_org, task_year,
source_library, source_library_addr, fulltext_url, author, publisher, isbn,
govern_status, sensitive_flag, deleted)
VALUES
(1, 'BB-2026-0001', '版本资源联合服务系统建设实践', 'G250.7',
'版本资源;联合服务;元数据治理', '本书系统阐述了版本资源联合服务系统的建设思路、元数据标准与数据治理方法,涵盖数据采集、聚同优化、检索发现等关键环节,供军队院校图书馆协同建设参考。',
'2026', '20261001', '文本', '纸质', 'PDF', '320', 'chi', '陆军步兵学院', '2026',
'陆军步兵学院图书馆', '10.0.0.11:8080', 'http://cdio.example.org/fulltext/BB-2026-0001',
'张三', '军事科学出版社', '978-7-80237-000-1', 'CLEANED', 0, 0),
(2, 'BB-2026-0002', '军事理论元数据著录规范', 'E0-65',
'军事理论;元数据;著录规范', '本书依据国家与军队相关标准,规范军事理论类文献的元数据著录字段与格式,包含中图分类标引、主题词标引、摘要撰写等具体要求,适用于各馆联合编目工作。',
'2025', '20260915', '文本', '电子', 'PDF', '210', 'chi', '陆军步兵学院', '2026',
'南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002',
'李四', '国防大学出版社', '978-7-5626-000-2', 'MERGED', 0, 0);
+105
View File
@@ -0,0 +1,105 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v2)
-- 兼容 PostgreSQL / 瀚高(HighGo)
-- 包含:资源呈缴、特藏推荐、采集任务、治理任务、检索行为日志
-- 幂等:CREATE TABLE IF NOT EXISTS,可重复执行
-- =====================================================================
-- ---------------- 资源呈缴记录 ----------------
CREATE TABLE IF NOT EXISTS deposit_record
(
id BIGINT NOT NULL PRIMARY KEY,
org_name VARCHAR(256) NOT NULL, -- 呈缴单位名称
contact VARCHAR(128), -- 联系人
phone VARCHAR(64), -- 联系方式
email VARCHAR(128), -- 邮箱
resource_title VARCHAR(512) NOT NULL, -- 版本资源名称
media_type VARCHAR(32), -- 媒体类型:纸质/电子
summary TEXT, -- 简介
remark TEXT, -- 备注
file_url VARCHAR(1024), -- 数字版文件地址
status VARCHAR(32) DEFAULT 'PENDING', -- PENDING/ACCEPTED/REJECTED
audit_remark VARCHAR(512), -- 审核意见
audit_time TIMESTAMP, -- 审核时间
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_dr_status ON deposit_record (status);
CREATE INDEX IF NOT EXISTS idx_dr_org ON deposit_record (org_name);
-- ---------------- 特藏版本资源 ----------------
CREATE TABLE IF NOT EXISTS special_resource
(
id BIGINT NOT NULL PRIMARY KEY,
name VARCHAR(256) NOT NULL, -- 特藏名称
summary TEXT, -- 简介
category VARCHAR(128), -- 类别
cover_url VARCHAR(1024), -- 图片地址
ebook_url VARCHAR(1024), -- 电子版下载地址
sort_no INTEGER DEFAULT 0, -- 排序
status SMALLINT DEFAULT 1, -- 1展示 0隐藏
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sr_status ON special_resource (status);
-- ---------------- 数据采集任务 ----------------
CREATE TABLE IF NOT EXISTS collect_task
(
id BIGINT NOT NULL PRIMARY KEY,
library_code VARCHAR(64) NOT NULL, -- 单位编码
library_name VARCHAR(256), -- 单位名称
source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API
target_count INTEGER DEFAULT 200000, -- 目标采集量
collected_count INTEGER DEFAULT 0, -- 已采集量
status VARCHAR(32) DEFAULT 'PENDING', -- PENDING/RUNNING/SUCCESS/FAILED
message VARCHAR(1024),
start_time TIMESTAMP,
end_time TIMESTAMP,
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_ct_library ON collect_task (library_code);
CREATE INDEX IF NOT EXISTS idx_ct_status ON collect_task (status);
-- ---------------- 数据治理任务 ----------------
CREATE TABLE IF NOT EXISTS governance_job
(
id BIGINT NOT NULL PRIMARY KEY,
job_type VARCHAR(32) NOT NULL, -- MERGE/OPTIMIZE/HINT/PURIFY
status VARCHAR(32) DEFAULT 'PENDING', -- PENDING/RUNNING/SUCCESS/FAILED
affected_count INTEGER DEFAULT 0, -- 影响记录数
result_summary TEXT, -- 结果摘要
start_time TIMESTAMP,
end_time TIMESTAMP,
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_gj_type ON governance_job (job_type);
-- ---------------- 检索行为日志 ----------------
CREATE TABLE IF NOT EXISTS search_log
(
id BIGINT NOT NULL PRIMARY KEY,
keyword VARCHAR(512),
user_ip VARCHAR(64),
source_library VARCHAR(256),
result_count INTEGER,
cost_ms BIGINT,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sl_keyword ON search_log (keyword);
CREATE INDEX IF NOT EXISTS idx_sl_time ON search_log (create_time);
-- ---------------- 特藏样例数据 ----------------
INSERT INTO special_resource (id, name, summary, category, cover_url, ebook_url, sort_no, status, deleted)
VALUES
(1, '珍本古籍数字化特藏', '馆藏珍本古籍的高清影像与元数据,涵盖经史子集多类。', '古籍', NULL, NULL, 1, 1, 0),
(2, '军事理论经典版本', '军事理论领域经典著作的多版本对照与全文检索。', '军事理论', NULL, NULL, 2, 1, 0),
(3, '地方志专题特藏', '区域地方志书版本资源合集,支持按地域检索。', '地方志', NULL, NULL, 3, 1, 0),
(4, '红色文献特藏', '革命历史文献版本资源专题,含珍贵影印本。', '红色文献', NULL, NULL, 4, 1, 0)
ON CONFLICT (id) DO NOTHING;
@@ -0,0 +1,22 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v3)
-- 用户与认证
-- 幂等:CREATE TABLE IF NOT EXISTS,可重复执行
-- =====================================================================
CREATE TABLE IF NOT EXISTS sys_user
(
id BIGINT NOT NULL PRIMARY KEY,
username VARCHAR(64) NOT NULL, -- 登录账号
password VARCHAR(128) NOT NULL, -- BCrypt 加密后的密码
real_name VARCHAR(128), -- 姓名
role VARCHAR(32) DEFAULT 'USER', -- ADMIN / USER
org_name VARCHAR(256), -- 所属单位
status SMALLINT DEFAULT 1, -- 1启用 0停用
last_login_time TIMESTAMP, -- 最近登录时间
deleted SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_sys_user_username UNIQUE (username)
);
CREATE INDEX IF NOT EXISTS idx_su_username ON sys_user (username);
@@ -0,0 +1,32 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v4)
-- 完善「数据治理状态」相关字段
--
-- 背景:govern_status 是系统辅助字段(非招标著录要素),
-- 取值由 RAW/CLEANED/MERGED 调整为对齐招标四动作的:
-- RAW 原始 → MERGED 已聚同 → OPTIMIZED 已优化 → FINAL 已提纯
-- MERGED_OUT 已合并(被聚同合并掉的从记录)
-- 并新增 merged_to_id(聚同指向主记录)、abnormal_flag(疑似错漏标记)。
--
-- 幂等:全部使用 IF NOT EXISTS,可重复执行
-- =====================================================================
-- 1. 新增字段
ALTER TABLE version_resource ADD COLUMN IF NOT EXISTS merged_to_id BIGINT;
ALTER TABLE version_resource ADD COLUMN IF NOT EXISTS abnormal_flag SMALLINT DEFAULT 0;
-- 2. 历史数据兼容:CLEANED 已废弃(语义模糊),归入 RAW(未聚同)
UPDATE version_resource SET govern_status = 'RAW' WHERE govern_status = 'CLEANED';
-- 3. 补齐空值
UPDATE version_resource SET govern_status = 'RAW' WHERE govern_status IS NULL OR govern_status = '';
UPDATE version_resource SET abnormal_flag = 0 WHERE abnormal_flag IS NULL;
-- 4. 字段说明
COMMENT ON COLUMN version_resource.govern_status IS '数据治理状态:RAW原始/MERGED已聚同/OPTIMIZED已优化/FINAL已提纯/MERGED_OUT已合并';
COMMENT ON COLUMN version_resource.merged_to_id IS '聚同后指向的主记录ID(仅 MERGED_OUT 记录有值)';
COMMENT ON COLUMN version_resource.abnormal_flag IS '疑似错漏标记:0正常 1疑似(由「提示」治理任务标记)';
-- 5. 索引
CREATE INDEX IF NOT EXISTS idx_vr_govern_status ON version_resource (govern_status);
CREATE INDEX IF NOT EXISTS idx_vr_merged_to_id ON version_resource (merged_to_id);
+70
View File
@@ -0,0 +1,70 @@
-- =====================================================================
-- 版本资源联合服务系统 - 元数据表结构
-- 依据询价文件「单条版本资源元数据采集要素及存储标准」设计
-- 兼容 PostgreSQL / 瀚高(HighGo)
-- =====================================================================
CREATE TABLE IF NOT EXISTS version_resource
(
id BIGINT NOT NULL PRIMARY KEY,
-- ==================== 必备字段 ====================
process_no VARCHAR(128), -- 加工编号(必备)
title VARCHAR(512) NOT NULL, -- 正题名(必备)
clc_code VARCHAR(64), -- 中图分类(必备)
keywords VARCHAR(512), -- 主题词或关键词(必备)
summary TEXT, -- 摘要(必备,>=100字)
publish_year VARCHAR(8), -- 出版年份 yyyy(必备)
process_date VARCHAR(16), -- 加工日期 yyyyMMdd(必备)
content_form VARCHAR(64), -- 内容形式(必备)
media_type VARCHAR(32), -- 媒体类型:纸质/电子(必备)
format VARCHAR(64), -- 格式,英文大写(必备)
page_count VARCHAR(64), -- 页码(必备)
language VARCHAR(16), -- 语种 3位代码(必备)
submit_org VARCHAR(256), -- 数据提交单位(必备)
task_year VARCHAR(8), -- 所属任务年份(必备)
source_library VARCHAR(256), -- 来源馆(必备)
source_library_addr VARCHAR(256), -- 来源馆地址 IP:端口/域名(必备)
fulltext_url VARCHAR(1024), -- 全文地址,据CDOI生成(必备)
-- ==================== 有则必备字段 ====================
other_title VARCHAR(512), -- 其他题名
author VARCHAR(512), -- 责任者名称
responsibility VARCHAR(256), -- 责任方式
note TEXT, -- 附注
publisher VARCHAR(256), -- 出版者名称
publish_place VARCHAR(128), -- 出版地
publish_date VARCHAR(32), -- 出版日期
relation VARCHAR(512), -- 关联
time_range VARCHAR(256), -- 时间范围
space_range VARCHAR(256), -- 空间范围
edition VARCHAR(128), -- 版本/版次
isbn VARCHAR(64), -- ISBN
unified_book_no VARCHAR(64), -- 统一书号
cdoi VARCHAR(256), -- CDOI
publish_url VARCHAR(1024), -- 发布地址
-- ==================== 治理与系统字段 ====================
govern_status VARCHAR(32) DEFAULT 'RAW',-- 治理状态 RAW/MERGED/OPTIMIZED/FINAL/MERGED_OUT
merged_to_id BIGINT, -- 聚同后指向的主记录ID
abnormal_flag SMALLINT DEFAULT 0, -- 疑似错漏 0正常 1疑似
sensitive_flag SMALLINT DEFAULT 0, -- 敏感标记 0正常 1敏感
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
-- 常用检索/统计索引
CREATE INDEX IF NOT EXISTS idx_vr_title ON version_resource (title);
CREATE INDEX IF NOT EXISTS idx_vr_author ON version_resource (author);
CREATE INDEX IF NOT EXISTS idx_vr_clc_code ON version_resource (clc_code);
CREATE INDEX IF NOT EXISTS idx_vr_media_type ON version_resource (media_type);
CREATE INDEX IF NOT EXISTS idx_vr_source_lib ON version_resource (source_library);
CREATE INDEX IF NOT EXISTS idx_vr_publish_year ON version_resource (publish_year);
CREATE INDEX IF NOT EXISTS idx_vr_cdoi ON version_resource (cdoi);
COMMENT ON TABLE version_resource IS '版本资源元数据表';
COMMENT ON COLUMN version_resource.media_type IS '媒体类型:纸质/电子';
COMMENT ON COLUMN version_resource.govern_status IS '数据治理状态:RAW原始/MERGED已聚同/OPTIMIZED已优化/FINAL已提纯/MERGED_OUT已合并';
COMMENT ON COLUMN version_resource.merged_to_id IS '聚同后指向的主记录ID';
COMMENT ON COLUMN version_resource.abnormal_flag IS '疑似错漏标记:0正常 1疑似';