Compare commits

..

41 Commits

Author SHA1 Message Date
lmy eb985706c4 推送数据 2026-11-13 16:19:23 +08:00
lmy 37566e9d7e 推送数据 2026-11-13 14:29:03 +08:00
zhaichao f1765c039c 版本资源综合比例 2026-11-04 16:00:07 +08:00
zhaichao 7794716861 二次检索 2026-11-04 15:45:19 +08:00
zhaichao 3d2a3e7766 用户访问数量 2026-11-04 15:28:32 +08:00
zhaichao 5cf7b35a58 日志统计 2026-11-04 15:26:24 +08:00
zhaichao 7438f558e2 日志 2026-11-04 14:50:25 +08:00
zhaichao 0b5c0a40e9 日志 2026-11-04 14:39:25 +08:00
zhaichao 4f3fc578d0 中图法分类 2026-11-04 14:08:14 +08:00
zhaichao 0d8fdbd35a 支持统计筛选 2026-11-04 13:45:57 +08:00
liweijie b76a7ccce4 角色默认为USER 2026-10-30 15:51:10 +08:00
liweijie f4f24398ee 添加对于用户的组织、角色分配 2026-10-30 15:43:03 +08:00
zhaichao 8546afa24e feat: 新增版本资源 32 著录字段数据库迁移脚本(幂等) 2026-10-30 15:29:34 +08:00
zhaichao 3dca829cf3 新增校验 2026-10-30 15:25:03 +08:00
zhaichao a2ea2389e5 Revert "补全字段"
This reverts commit 8bdaafb69b.
2026-10-30 15:01:50 +08:00
zhaichao 8bdaafb69b 补全字段 2026-10-30 14:56:35 +08:00
liweijie 28fd91e46e 1、sql输出调整,否则会占满资源;
2、添加组织角色管理模块;
3、后台管理样式调整,改为左侧边栏
2026-10-30 14:45:39 +08:00
zhaichao f1e68697b5 搜索去除关键字 2026-10-30 14:04:05 +08:00
zhaichao 3a0705692a 馆藏轮播图有封面优先展示封面 2026-10-30 11:25:30 +08:00
zhaichao f02323e350 馆藏轮播图样式调整 2026-10-30 11:23:16 +08:00
zhaichao 7024ad09ac 小字tag移除 2026-10-30 11:20:47 +08:00
zhaichao 4e5eb6ca5b 标题修改 2026-10-30 11:18:29 +08:00
yangbin b24c5e3849 Merge remote-tracking branch 'origin/master' 2026-10-29 09:16:24 +08:00
yangbin 4990a48b2c 元数据模板导出 excel导入 5000条上限取消 2026-10-29 09:16:18 +08:00
liweijie 6998d6c805 首页书脊添加来源 2026-10-26 19:24:28 +08:00
liweijie 7d87511790 检索框右侧改为统计数据 2026-10-26 19:01:11 +08:00
liweijie 72b6804dad 替换掉不清晰的背景图 2026-10-26 18:53:41 +08:00
liweijie e8455c7ba6 首页轮播背景替换为我军 2026-10-26 18:46:10 +08:00
liweijie 66c3b73c3f 轮播图背景文字替换 2026-10-26 18:43:41 +08:00
SUNJIAJINGS 94b7c8010a feat:三张轮播图图片 2026-10-26 18:40:50 +08:00
yangbin 3e3a1b8465 主页背景图更换 2026-10-23 20:28:02 +08:00
yangbin b522734c92 元数据模板导出 excel导入 带五条实例 2026-10-23 19:17:09 +08:00
yangbin ddc0864f06 元数据模板导出 excel导入 2026-10-23 18:45:12 +08:00
SUNJIAJINGS 8b6f00b117 feat: 新增呈缴管理功能与检索筛选优化 2026-10-23 17:33:52 +08:00
lmy 20660da286 页面优化 数据采集 2026-10-23 15:16:27 +08:00
SUNJIAJINGS a68f27f7f2 feat(search): 新增中图法分类树接口及分面优化 2026-10-23 13:53:46 +08:00
SUNJIAJINGS b735c1465a Merge remote-tracking branch 'origin/master'
# Conflicts:
#	frontend/src/views/search/SearchView.vue
2026-10-22 17:35:56 +08:00
SUNJIAJINGS 3626939ccb feat(admin): 添加列表显示字段配置功能
- 新增 list_field_config 表及后端接口,支持查询、保存、恢复默认字段配置
- 管理后台新增“列表字段配置”页签,可增删字段、调整顺序、修改显示名与可见性
- version_resource 表新增作者单位、来源资源库名字段及升级脚本
- 引入 xlsx 依赖以支持列表导出
2026-10-22 17:33:34 +08:00
lmy 09b8a39ec5 页面优化 数据采集 优化 / 提示 / 提纯 2026-10-22 16:51:18 +08:00
SUNJIAJINGS 46be7346a2 feat: 新增后台管理入口与资源新增功能
- 首页齿轮按钮以新标签页打开后台管理,新增 Admin 路由与视图
- 资源列表支持新增版本资源,复用编辑抽屉
- 主页检索按字段映射到检索页途径(题名/关键词/责任者/出版社/综合)
- 检索支持多词分词 OR 匹配,并过滤已屏蔽/下架记录
- 聚同算法改为 ISBN 优先、无 ISBN 时四要素判定,并前后端统一抽取分组逻辑
- 数据库主键改为自增序列,新增敏感词库与院校资源节点表,补充特藏与管理状态字段及样例数据序列同步
2026-10-21 16:25:28 +08:00
SUNJIAJINGS e9c83e0be0 feat: 新增特藏书架与词云热词展示
- 首页快捷入口改为 3D 悬浮书架,拉取特藏推荐并支持点击进入详情
- 热词页改用 wordcloud 渲染词云,支持悬停放大与点击检索
- 导航栏改为半透明绿叠加实景背景,统一首页与内页观感
- 版本资源表新增 is_special 字段及示例数据
2026-10-20 17:33:34 +08:00
215 changed files with 20525 additions and 922 deletions
+30
View File
@@ -63,6 +63,29 @@
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 现场外部库可能是 Oracle / SQL Server,驱动随包提供,连接信息仍从配置表读取 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>23.4.0.24.05</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 南昌总库汇总用 Elasticsearch。连不上时开发配置可改走本地表,避免拖垮已有业务。 -->
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.13.4</version>
</dependency>
<!-- 连接池 -->
<dependency>
@@ -84,6 +107,13 @@
<version>${hutool.version}</version>
</dependency>
<!-- Excel 导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
@@ -1,6 +1,9 @@
package com.banben.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
@@ -21,17 +24,18 @@ import org.springframework.stereotype.Component;
public class DataInitializer implements ApplicationRunner {
private final SysUserMapper sysUserMapper;
private final SysRoleMapper sysRoleMapper;
private final RoleService roleService;
private final PasswordEncoder passwordEncoder;
@Override
public void run(ApplicationArguments args) {
ensureRoles();
try {
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUsername, "admin");
Long count = sysUserMapper.selectCount(wrapper);
if (count != null && count > 0) {
return;
}
if (count == null || count == 0) {
SysUser admin = new SysUser();
admin.setUsername("admin");
admin.setPassword(passwordEncoder.encode("admin123"));
@@ -41,8 +45,35 @@ public class DataInitializer implements ApplicationRunner {
admin.setStatus(1);
sysUserMapper.insert(admin);
log.info("已创建默认管理员账号:admin / admin123");
}
} catch (Exception e) {
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
}
bindAdminRole();
}
private void ensureRoles() {
try {
roleService.ensureBuiltin();
} catch (Exception e) {
log.warn("初始化内置角色失败(可能表未创建):{}", e.getMessage());
}
}
private void bindAdminRole() {
try {
SysRole adminRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, "ADMIN"));
if (adminRole == null) {
return;
}
SysUser admin = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, "admin"));
if (admin != null && admin.getRoleId() == null) {
admin.setRoleId(adminRole.getId());
admin.setRole("ADMIN");
sysUserMapper.updateById(admin);
}
} catch (Exception e) {
log.warn("回填管理员角色失败:{}", e.getMessage());
}
}
}
@@ -0,0 +1,47 @@
package com.banben.config;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.format.DateTimeFormatter;
/**
* 统一 java.time 类型的 JSON 序列化格式。
*
* <p>Spring 的 {@code spring.jackson.date-format} 只作用于 {@code java.util.Date},
* 对 {@code LocalDateTime/LocalDate/LocalTime} 默认序列化为带 T 的 ISO-8601(如 2026-11-04T10:30:00),
* 前端展示与解析都不友好。这里统一改为可读格式:</p>
* <ul>
* <li>LocalDateTime → yyyy-MM-dd HH:mm:ss</li>
* <li>LocalDate → yyyy-MM-dd</li>
* <li>LocalTime → HH:mm:ss</li>
* </ul>
*/
@Configuration
public class JacksonConfig {
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_PATTERN = "yyyy-MM-dd";
private static final String TIME_PATTERN = "HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERN);
DateTimeFormatter tf = DateTimeFormatter.ofPattern(TIME_PATTERN);
return builder -> builder
.serializerByType(java.time.LocalDateTime.class, new LocalDateTimeSerializer(dtf))
.serializerByType(java.time.LocalDate.class, new LocalDateSerializer(df))
.serializerByType(java.time.LocalTime.class, new LocalTimeSerializer(tf))
.deserializerByType(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(dtf))
.deserializerByType(java.time.LocalDate.class, new LocalDateDeserializer(df))
.deserializerByType(java.time.LocalTime.class, new LocalTimeDeserializer(tf));
}
}
@@ -1,6 +1,7 @@
package com.banben.config;
import com.banben.modules.auth.interceptor.AuthInterceptor;
import com.banben.modules.synchub.config.HubTokenInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
@@ -22,6 +23,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class WebMvcConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
private final HubTokenInterceptor hubTokenInterceptor;
/**
* 跨域配置。
@@ -46,6 +48,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
* <li>{@code /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
* <li>{@code /api/hub/**} —— 节点与总库互调用同步口令,不用用户登录令牌</li>
* </ul>
*/
@Override
@@ -58,7 +61,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/api/auth/logout",
"/swagger-ui/**",
"/v3/api-docs/**",
"/actuator/**"
"/actuator/**",
"/api/hub/**"
);
registry.addInterceptor(hubTokenInterceptor)
.addPathPatterns("/api/hub/**");
}
}
@@ -0,0 +1,50 @@
package com.banben.modules.admin.controller;
import com.banben.common.Result;
import com.banben.modules.admin.entity.ListFieldConfig;
import com.banben.modules.admin.service.ListFieldConfigService;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后台管理 - 列表显示字段配置。
*
* <p>控制检索结果列表展示哪些字段、显示名与顺序。</p>
*/
@Tag(name = "后台管理-列表字段配置")
@RestController
@RequestMapping("/api/admin/list-fields")
@RequiredArgsConstructor
public class ListFieldConfigController {
private final ListFieldConfigService listFieldConfigService;
@Operation(summary = "查询场景的展示字段配置(为空时返回并写入默认配置)")
@GetMapping("/{scene}")
public Result<List<ListFieldConfig>> list(@PathVariable String scene) {
return Result.success(listFieldConfigService.listScene(scene));
}
@Operation(summary = "全量覆盖保存展示字段配置")
@PutMapping("/{scene}")
public Result<Void> save(@PathVariable String scene, @RequestBody List<ListFieldConfig> items) {
listFieldConfigService.saveScene(scene, items);
return Result.success();
}
@Operation(summary = "恢复场景默认展示字段")
@PostMapping("/{scene}/reset")
public Result<List<ListFieldConfig>> reset(@PathVariable String scene) {
return Result.success(listFieldConfigService.resetScene(scene));
}
}
@@ -0,0 +1,65 @@
package com.banben.modules.admin.controller;
import com.banben.common.Result;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.admin.support.AdminAccess;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 多层级组织管理。
*/
@Tag(name = "后台管理-组织")
@RestController
@RequestMapping("/api/admin/orgs")
@RequiredArgsConstructor
public class OrgController {
private final OrgService orgService;
private final AdminAccess adminAccess;
@Operation(summary = "组织树")
@GetMapping("/tree")
public Result<List<OrgTreeVO>> tree() {
adminAccess.require();
return Result.success(orgService.tree());
}
@Operation(summary = "新增组织")
@PostMapping
public Result<Void> create(@Valid @RequestBody OrgSaveRequest request) {
adminAccess.require();
orgService.create(request);
return Result.success();
}
@Operation(summary = "修改组织")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody OrgSaveRequest request) {
adminAccess.require();
orgService.update(id, request);
return Result.success();
}
@Operation(summary = "删除组织")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
orgService.remove(id);
return Result.success();
}
}
@@ -0,0 +1,94 @@
package com.banben.modules.admin.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.banben.common.BusinessException;
import com.banben.common.Result;
import com.banben.modules.admin.entity.ResourceNode;
import com.banben.modules.admin.service.ResourceNodeService;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import cn.hutool.core.util.StrUtil;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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;
/**
* 后台管理 - 院校资源节点。
*/
@Tag(name = "后台管理-院校资源节点")
@RestController
@RequestMapping("/api/admin/resource-nodes")
@RequiredArgsConstructor
public class ResourceNodeController {
private final ResourceNodeService resourceNodeService;
private final VersionResourceMapper resourceMapper;
@Operation(summary = "资源节点全量列表(按展示顺序排序)")
@GetMapping("/list")
public Result<List<ResourceNode>> list() {
return Result.success(resourceNodeService.listOrdered());
}
@Operation(summary = "新增资源节点")
@PostMapping
public Result<Void> create(@Valid @RequestBody ResourceNode node) {
resourceNodeService.save(node);
return Result.success();
}
@Operation(summary = "更新资源节点(名称/类型/类别/链接/顺序/状态)")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody ResourceNode node) {
node.setId(id);
resourceNodeService.updateById(node);
return Result.success();
}
@Operation(summary = "删除资源节点(单条,逻辑删除)")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
resourceNodeService.removeById(id);
return Result.success();
}
@Operation(summary = "批量删除资源节点")
@PostMapping("/batch-delete")
public Result<Void> batchRemove(@RequestBody List<Long> ids) {
resourceNodeService.removeBatch(ids);
return Result.success();
}
@Operation(summary = "版本资源分组统计:按来源院校/资源类型/资源名称展示各类资源数量")
@GetMapping("/stats")
public Result<List<Map<String, Object>>> stats(@RequestParam(defaultValue = "sourceLibrary") String dim,
@RequestParam(defaultValue = "20") int limit) {
String column = switch (dim) {
case "sourceLibrary" -> "source_library";
case "mediaType" -> "media_type";
case "title" -> "title";
default -> throw new BusinessException("不支持的统计维度:" + dim);
};
QueryWrapper<VersionResource> w = new QueryWrapper<>();
w.select(column + " AS name", "COUNT(*) AS count")
.eq("deleted", 0)
.isNotNull(column)
.groupBy(column)
.orderByDesc("count")
.last(" LIMIT " + Math.max(1, Math.min(limit, 200)));
return Result.success(resourceMapper.selectMaps(w));
}
}
@@ -0,0 +1,65 @@
package com.banben.modules.admin.controller;
import com.banben.common.Result;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.admin.support.AdminAccess;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 角色管理。
*/
@Tag(name = "后台管理-角色")
@RestController
@RequestMapping("/api/admin/roles")
@RequiredArgsConstructor
public class RoleController {
private final RoleService roleService;
private final AdminAccess adminAccess;
@Operation(summary = "角色列表")
@GetMapping
public Result<List<SysRole>> list() {
adminAccess.require();
return Result.success(roleService.listAll());
}
@Operation(summary = "新增角色")
@PostMapping
public Result<Void> create(@Valid @RequestBody RoleSaveRequest request) {
adminAccess.require();
roleService.create(request);
return Result.success();
}
@Operation(summary = "修改角色")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RoleSaveRequest request) {
adminAccess.require();
roleService.update(id, request);
return Result.success();
}
@Operation(summary = "删除角色")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
roleService.remove(id);
return Result.success();
}
}
@@ -0,0 +1,84 @@
package com.banben.modules.admin.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.Result;
import com.banben.modules.admin.dto.SensitiveActionDTO;
import com.banben.modules.admin.dto.SensitiveHitVO;
import com.banben.modules.admin.entity.SensitiveWord;
import com.banben.modules.admin.service.SensitiveWordService;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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;
/**
* 后台管理 - 敏感词库。
*/
@Tag(name = "后台管理-敏感词库")
@RestController
@RequestMapping("/api/admin/sensitive-words")
@RequiredArgsConstructor
public class SensitiveWordController {
private final SensitiveWordService sensitiveWordService;
@Operation(summary = "分页查询敏感词")
@GetMapping("/page")
public Result<Page<SensitiveWord>> page(@RequestParam(defaultValue = "1") long current,
@RequestParam(defaultValue = "10") long size,
@RequestParam(required = false) String keyword) {
return Result.success(sensitiveWordService.pageWords(current, size, keyword));
}
@Operation(summary = "新增敏感词")
@PostMapping
public Result<Void> create(@Valid @RequestBody SensitiveWord word) {
sensitiveWordService.saveWord(word);
return Result.success();
}
@Operation(summary = "更新敏感词")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody SensitiveWord word) {
sensitiveWordService.updateWord(id, word);
return Result.success();
}
@Operation(summary = "删除敏感词(单条,逻辑删除)")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
sensitiveWordService.removeById(id);
return Result.success();
}
@Operation(summary = "批量删除敏感词")
@PostMapping("/batch-delete")
public Result<Void> batchRemove(@RequestBody List<Long> ids) {
sensitiveWordService.removeBatch(ids);
return Result.success();
}
@Operation(summary = "敏感词命中扫描(元数据含敏感词的版本资源,分页)")
@GetMapping("/hits")
public Result<Page<SensitiveHitVO>> hits(@RequestParam(defaultValue = "1") long current,
@RequestParam(defaultValue = "10") long size) {
return Result.success(sensitiveWordService.hits(current, size));
}
@Operation(summary = "命中处置:MASK屏蔽 / OFFLINE下架 / RESTORE恢复正常 / DELETE删除(支持单条与批量)")
@PostMapping("/hits/action")
public Result<Integer> handleAction(@RequestBody SensitiveActionDTO dto) {
return Result.success(sensitiveWordService.handleAction(dto.getIds(), dto.getAction()));
}
}
@@ -0,0 +1,96 @@
package com.banben.modules.admin.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.Result;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
import com.banben.modules.admin.service.UserAdminService;
import com.banben.modules.admin.service.UserExcelService;
import com.banben.modules.admin.support.AdminAccess;
import com.banben.modules.resource.dto.ImportResult;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 用户管理,含导入模板导出和批量导入。
*/
@Tag(name = "后台管理-用户")
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class UserAdminController {
private final UserAdminService userAdminService;
private final UserExcelService userExcelService;
private final AdminAccess adminAccess;
@Operation(summary = "分页查询用户")
@GetMapping("/page")
public Result<Page<UserVO>> page(@RequestParam(defaultValue = "1") long current,
@RequestParam(defaultValue = "10") long size,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long orgId,
@RequestParam(required = false) Long roleId) {
adminAccess.require();
return Result.success(userAdminService.page(current, size, keyword, orgId, roleId));
}
@Operation(summary = "新增用户")
@PostMapping
public Result<Void> create(@Valid @RequestBody UserSaveRequest request) {
adminAccess.require();
userAdminService.create(request);
return Result.success();
}
@Operation(summary = "修改用户")
@PutMapping("/{id}")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserSaveRequest request) {
adminAccess.require();
userAdminService.update(id, request);
return Result.success();
}
@Operation(summary = "删除用户")
@DeleteMapping("/{id}")
public Result<Void> remove(@PathVariable Long id) {
adminAccess.require();
userAdminService.remove(id);
return Result.success();
}
@Operation(summary = "导出用户导入模板")
@GetMapping("/import-template")
public void template(jakarta.servlet.http.HttpServletResponse response) throws IOException {
adminAccess.require();
String fileName = URLEncoder.encode("用户导入模板.xlsx", StandardCharsets.UTF_8);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
userExcelService.writeTemplate(response.getOutputStream());
}
@Operation(summary = "批量导入用户")
@PostMapping("/import")
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
adminAccess.require();
return Result.success(userExcelService.importExcel(file));
}
}
@@ -0,0 +1,30 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 新增或修改组织。
*/
@Data
public class OrgSaveRequest {
/** 上级组织,空表示顶级 */
private Long parentId;
@NotBlank(message = "请填写组织名称")
@Size(max = 128, message = "组织名称不能超过128字")
private String name;
@Size(max = 64, message = "组织编码不能超过64字")
private String code;
private Integer sortNo;
/** 1启用 0停用 */
private Integer status;
@Size(max = 256, message = "备注不能超过256字")
private String remark;
}
@@ -0,0 +1,21 @@
package com.banben.modules.admin.dto;
import lombok.Data;
import java.util.List;
/**
* 组织树节点。叶子节点不带 children。
*/
@Data
public class OrgTreeVO {
private Long id;
private Long parentId;
private String name;
private String code;
private Integer sortNo;
private Integer status;
private String remark;
private List<OrgTreeVO> children;
}
@@ -0,0 +1,33 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/**
* 新增或修改角色。
*/
@Data
public class RoleSaveRequest {
@NotBlank(message = "请填写角色编码")
@Size(max = 32, message = "角色编码不能超过32字")
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]{0,31}", message = "角色编码需以字母开头,只能包含字母、数字和下划线")
private String code;
@NotBlank(message = "请填写角色名称")
@Size(max = 64, message = "角色名称不能超过64字")
private String name;
@Size(max = 256, message = "备注不能超过256字")
private String remark;
/** 1启用 0停用 */
private Integer status;
/** 顶部导航编码。空列表表示该角色看不到任何顶部栏目。 */
private List<String> menuCodes;
}
@@ -0,0 +1,20 @@
package com.banben.modules.admin.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 敏感词命中处置请求。
*/
@Data
@Schema(description = "敏感词命中处置请求")
public class SensitiveActionDTO {
@Schema(description = "版本资源ID列表(单条操作传一个,批量传多个)")
private List<Long> ids;
@Schema(description = "处置动作:MASK屏蔽 / OFFLINE下架 / RESTORE恢复正常 / DELETE删除")
private String action;
}
@@ -0,0 +1,42 @@
package com.banben.modules.admin.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 敏感词命中条目(供后台处置列表展示)。
*/
@Data
@Schema(description = "敏感词命中条目")
public class SensitiveHitVO {
@Schema(description = "版本资源ID")
private Long id;
@Schema(description = "正题名")
private String title;
@Schema(description = "责任者")
private String author;
@Schema(description = "来源馆/院校")
private String sourceLibrary;
@Schema(description = "媒体类型")
private String mediaType;
@Schema(description = "治理状态")
private String governStatus;
@Schema(description = "敏感标记:0正常 1敏感")
private Integer sensitiveFlag;
@Schema(description = "管理状态:0正常 1屏蔽 2下架")
private Integer manageStatus;
@Schema(description = "命中的敏感词列表")
private List<String> matchedWords = new ArrayList<>();
}
@@ -0,0 +1,32 @@
package com.banben.modules.admin.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 新增或修改用户。修改时密码留空表示不改密码。
*/
@Data
public class UserSaveRequest {
@NotBlank(message = "请填写登录账号")
@Size(max = 64, message = "登录账号不能超过64字")
private String username;
@Size(max = 64, message = "密码不能超过64字")
private String password;
@NotBlank(message = "请填写姓名")
@Size(max = 128, message = "姓名不能超过128字")
private String realName;
@NotNull(message = "请选择角色")
private Long roleId;
private Long orgId;
/** 1启用 0停用 */
private Integer status;
}
@@ -0,0 +1,24 @@
package com.banben.modules.admin.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户列表行,不包含密码。
*/
@Data
public class UserVO {
private Long id;
private String username;
private String realName;
private Long roleId;
private String roleCode;
private String roleName;
private Long orgId;
private String orgName;
private Integer status;
private LocalDateTime lastLoginTime;
private LocalDateTime createTime;
}
@@ -0,0 +1,49 @@
package com.banben.modules.admin.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("list_field_config")
@Schema(description = "列表显示字段配置")
public class ListFieldConfig implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "配置场景:SEARCH 检索结果列表")
private String scene;
@Schema(description = "字段键,对应 VersionResource 的驼峰属性名")
private String fieldKey;
@Schema(description = "列表与导出时的显示名")
private String fieldLabel;
@Schema(description = "展示顺序,数值小的靠前")
private Integer sortNo;
@Schema(description = "是否显示:1显示 0隐藏")
private Integer visible;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,54 @@
package com.banben.modules.admin.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("resource_node")
@Schema(description = "院校资源节点")
public class ResourceNode implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@NotBlank(message = "资源节点名称不能为空")
@Schema(description = "资源节点名称")
private String name;
@Schema(description = "资源类型")
private String nodeType;
@Schema(description = "类别归属")
private String category;
@Schema(description = "访问链接")
private String linkUrl;
@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,42 @@
package com.banben.modules.admin.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("sensitive_word")
@Schema(description = "敏感词库")
public class SensitiveWord implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@NotBlank(message = "敏感词不能为空")
@Schema(description = "敏感词(中文)")
private String word;
@Schema(description = "敏感词拼音")
private String pinyin;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,52 @@
package com.banben.modules.admin.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_org")
@Schema(description = "组织")
public class SysOrg implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "上级组织,空为顶级")
private Long parentId;
@Schema(description = "组织名称")
private String name;
@Schema(description = "组织编码")
private String code;
@Schema(description = "同级排序,小的在前")
private Integer sortNo;
@Schema(description = "1启用 0停用")
private Integer status;
@Schema(description = "备注")
private String remark;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,58 @@
package com.banben.modules.admin.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;
import java.util.ArrayList;
import java.util.List;
/**
* 角色。内置角色不可删除,编码供登录令牌使用。
*/
@Data
@TableName("sys_role")
@Schema(description = "角色")
public class SysRole implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "角色编码")
private String code;
@Schema(description = "角色名称")
private String name;
@Schema(description = "备注")
private String remark;
@Schema(description = "1启用 0停用")
private Integer status;
@Schema(description = "1内置 0自建")
private Integer builtin;
@Schema(description = "1表示顶部导航已初始化")
private Integer menuInited;
@TableField(exist = false)
@Schema(description = "可访问的顶部导航编码")
private List<String> menuCodes = new ArrayList<>();
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableLogic
private Integer deleted;
}
@@ -0,0 +1,23 @@
package com.banben.modules.admin.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* 角色与顶部导航的对应关系。
*/
@Data
@TableName("sys_role_menu")
public class SysRoleMenu implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
private Long roleId;
private String menuCode;
}
@@ -0,0 +1,8 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.ListFieldConfig;
/** 列表显示字段配置 Mapper。 */
public interface ListFieldConfigMapper extends BaseMapper<ListFieldConfig> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.ResourceNode;
import org.apache.ibatis.annotations.Mapper;
/**
* 院校资源节点 Mapper。
*/
@Mapper
public interface ResourceNodeMapper extends BaseMapper<ResourceNode> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SensitiveWord;
import org.apache.ibatis.annotations.Mapper;
/**
* 敏感词库 Mapper。
*/
@Mapper
public interface SensitiveWordMapper extends BaseMapper<SensitiveWord> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysOrg;
import org.apache.ibatis.annotations.Mapper;
/**
* 组织 Mapper。
*/
@Mapper
public interface SysOrgMapper extends BaseMapper<SysOrg> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysRole;
import org.apache.ibatis.annotations.Mapper;
/**
* 角色 Mapper。
*/
@Mapper
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
@@ -0,0 +1,12 @@
package com.banben.modules.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.admin.entity.SysRoleMenu;
import org.apache.ibatis.annotations.Mapper;
/**
* 角色导航权限。
*/
@Mapper
public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> {
}
@@ -0,0 +1,22 @@
package com.banben.modules.admin.service;
import com.banben.modules.admin.entity.ListFieldConfig;
import java.util.List;
/**
* 列表显示字段配置服务。
*
* <p>管理员可在后台调整检索结果列表展示的字段、显示名与顺序。</p>
*/
public interface ListFieldConfigService {
/** 查询场景配置(为空时自动写入默认字段),按 sort_no 升序 */
List<ListFieldConfig> listScene(String scene);
/** 全量覆盖保存场景配置 */
void saveScene(String scene, List<ListFieldConfig> items);
/** 恢复场景默认配置 */
List<ListFieldConfig> resetScene(String scene);
}
@@ -0,0 +1,24 @@
package com.banben.modules.admin.service;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import java.util.List;
import java.util.Set;
/**
* 多层级组织。
*/
public interface OrgService {
List<OrgTreeVO> tree();
void create(OrgSaveRequest request);
void update(Long id, OrgSaveRequest request);
void remove(Long id);
/** 本级及全部下级的 id,含自身。 */
Set<Long> subtreeIds(Long orgId);
}
@@ -0,0 +1,18 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.admin.entity.ResourceNode;
import java.util.List;
/**
* 院校资源节点服务。
*/
public interface ResourceNodeService extends IService<ResourceNode> {
/** 全量列表(按展示顺序、类别排序) */
List<ResourceNode> listOrdered();
/** 批量删除(逻辑删除) */
void removeBatch(List<Long> ids);
}
@@ -0,0 +1,22 @@
package com.banben.modules.admin.service;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import java.util.List;
/**
* 角色维护。内置角色不可删除,编码变更时同步用户表上的角色编码。
*/
public interface RoleService {
List<SysRole> listAll();
void create(RoleSaveRequest request);
void update(Long id, RoleSaveRequest request);
void remove(Long id);
void ensureBuiltin();
}
@@ -0,0 +1,37 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.admin.dto.SensitiveHitVO;
import com.banben.modules.admin.entity.SensitiveWord;
import java.util.List;
/**
* 敏感词库服务。
*/
public interface SensitiveWordService extends IService<SensitiveWord> {
/** 分页查询敏感词(keyword 模糊匹配词/拼音) */
Page<SensitiveWord> pageWords(long current, long size, String keyword);
/** 新增敏感词(词去重) */
void saveWord(SensitiveWord word);
/** 更新敏感词(词去重,排除自身) */
void updateWord(Long id, SensitiveWord word);
/** 批量删除敏感词(逻辑删除) */
void removeBatch(List<Long> ids);
/** 扫描元数据中命中敏感词的版本资源(分页) */
Page<SensitiveHitVO> hits(long current, long size);
/**
* 对命中记录进行处置(支持单条与批量):
* MASK 屏蔽(检索/索引中隐藏)、OFFLINE 下架、RESTORE 恢复正常、DELETE 删除。
*
* @return 实际处置条数
*/
int handleAction(List<Long> ids, String action);
}
@@ -0,0 +1,19 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
/**
* 用户管理。
*/
public interface UserAdminService {
Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId);
void create(UserSaveRequest request);
void update(Long id, UserSaveRequest request);
void remove(Long id);
}
@@ -0,0 +1,376 @@
package com.banben.modules.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.resource.dto.ImportResult;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 用户导入模板与批量导入。
*
* <p>模板第 1 行是表头,第 2 行是说明,第 3 行起为数据。账号已存在时更新该用户,密码留空则不改原密码。</p>
*/
@Service
@RequiredArgsConstructor
public class UserExcelService {
private static final String[] HEADERS = {"登录账号*", "姓名*", "初始密码", "角色编码*", "组织编码", "状态"};
private static final String[] HINTS = {
"必填。示例行以「示例:」开头,导入时自动跳过",
"必填",
"选填。新增留空则为 123456;更新留空则不修改密码",
"必填。填角色编码,见「可选数据」页",
"选填。填组织编码,或「上级/本级」路径",
"选填。启用 或 停用,默认启用"
};
private static final String[] SAMPLE = {"示例:zhangsan", "张三", "123456", "USER", "", "启用"};
private final SysUserMapper userMapper;
private final SysRoleMapper roleMapper;
private final SysOrgMapper orgMapper;
private final UserAdminService userAdminService;
private final DataFormatter formatter = new DataFormatter();
public void writeTemplate(OutputStream out) throws IOException {
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>().orderByAsc(SysRole::getId));
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>().orderByAsc(SysOrg::getSortNo).orderByAsc(SysOrg::getId));
Map<Long, SysOrg> byId = new HashMap<>();
for (SysOrg org : orgs) {
byId.put(org.getId(), org);
}
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("用户");
CellStyle headStyle = headStyle(wb);
CellStyle hintStyle = hintStyle(wb);
Row head = sheet.createRow(0);
Row hint = sheet.createRow(1);
head.setHeightInPoints(22);
hint.setHeightInPoints(32);
int[] widths = {22, 16, 28, 22, 28, 16};
for (int i = 0; i < HEADERS.length; i++) {
Cell h = head.createCell(i);
h.setCellValue(HEADERS[i]);
h.setCellStyle(headStyle);
Cell t = hint.createCell(i);
t.setCellValue(HINTS[i]);
t.setCellStyle(hintStyle);
sheet.setColumnWidth(i, widths[i] * 256);
}
Row sample = sheet.createRow(2);
for (int i = 0; i < SAMPLE.length; i++) {
sample.createCell(i).setCellValue(SAMPLE[i]);
}
sheet.createFreezePane(0, 2);
Sheet dict = wb.createSheet("可选数据");
Row dictHead = dict.createRow(0);
dictHead.createCell(0).setCellValue("角色编码");
dictHead.createCell(1).setCellValue("角色名称");
dictHead.createCell(2).setCellValue("组织编码");
dictHead.createCell(3).setCellValue("组织路径");
for (int i = 0; i < roles.size(); i++) {
Row row = dict.createRow(i + 1);
row.createCell(0).setCellValue(roles.get(i).getCode());
row.createCell(1).setCellValue(roles.get(i).getName());
}
int orgRow = 1;
for (SysOrg org : orgs) {
Row row = dict.getRow(orgRow);
if (row == null) {
row = dict.createRow(orgRow);
}
row.createCell(2).setCellValue(org.getCode() == null ? "" : org.getCode());
row.createCell(3).setCellValue(pathOf(org, byId));
orgRow++;
}
dict.setColumnWidth(0, 18 * 256);
dict.setColumnWidth(1, 18 * 256);
dict.setColumnWidth(2, 18 * 256);
dict.setColumnWidth(3, 36 * 256);
if (!roles.isEmpty()) {
dropdown(sheet, 3, "'可选数据'!$A$2:$A$" + (roles.size() + 1));
}
dropdown(sheet, 5, "\"启用,停用\"");
wb.setActiveSheet(0);
wb.write(out);
}
}
public ImportResult importExcel(MultipartFile file) throws IOException {
ImportResult result = new ImportResult();
if (file == null || file.isEmpty()) {
result.addError(0, "请选择要导入的 Excel 文件");
return result;
}
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>());
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>());
Map<Long, SysOrg> byId = new HashMap<>();
for (SysOrg org : orgs) {
byId.put(org.getId(), org);
}
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
Sheet sheet = wb.getNumberOfSheets() == 0 ? null : wb.getSheetAt(0);
if (sheet == null || sheet.getLastRowNum() < 1) {
result.addError(0, "表格为空,请使用系统导出的导入模板");
return result;
}
Map<String, Integer> columns = headerIndex(sheet.getRow(0));
if (!columns.containsKey("登录账号") || !columns.containsKey("姓名") || !columns.containsKey("角色编码")) {
result.addError(1, "表头缺少登录账号、姓名或角色编码,请使用系统导出的导入模板");
return result;
}
int start = hintRow(sheet) ? 2 : 1;
for (int r = start; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
String username = cell(row, columns.get("登录账号"));
String realName = cell(row, columns.get("姓名"));
String password = cell(row, columns.get("初始密码"));
String roleText = cell(row, columns.get("角色编码"));
String orgText = cell(row, columns.get("组织编码"));
String statusText = cell(row, columns.get("状态"));
if (!StringUtils.hasText(username) && !StringUtils.hasText(realName)
&& !StringUtils.hasText(roleText)) {
continue;
}
int excelRow = r + 1;
if (isSample(username) || isSample(realName)) {
result.setSkipped(result.getSkipped() + 1);
continue;
}
result.setTotal(result.getTotal() + 1);
try {
importRow(username, realName, password, roleText, orgText, statusText, roles, orgs, byId, result);
} catch (BusinessException e) {
result.addError(excelRow, e.getMessage());
}
}
if (result.getTotal() == 0 && result.getFailed() == 0) {
result.addError(0, result.getSkipped() > 0
? "仅读取到模板示例数据,请填写实际数据后再导入"
: "未读取到有效数据行,请从第 3 行开始填写");
}
return result;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
result.addError(0, "文件解析失败:" + e.getMessage());
return result;
}
}
private void importRow(String username, String realName, String password, String roleText, String orgText,
String statusText, List<SysRole> roles, List<SysOrg> orgs, Map<Long, SysOrg> byId,
ImportResult result) {
if (!StringUtils.hasText(username)) {
throw new BusinessException("登录账号不能为空");
}
if (!StringUtils.hasText(realName)) {
throw new BusinessException("姓名不能为空");
}
SysRole role = matchRole(roleText, roles);
if (role == null) {
throw new BusinessException("角色不存在:" + roleText);
}
Long orgId = matchOrg(orgText, orgs, byId);
Integer status = parseStatus(statusText);
SysUser existing = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, username.trim()));
UserSaveRequest request = new UserSaveRequest();
request.setUsername(username.trim());
request.setRealName(realName.trim());
request.setPassword(StringUtils.hasText(password) ? password.trim() : null);
request.setRoleId(role.getId());
request.setOrgId(orgId);
request.setStatus(status);
if (existing == null) {
userAdminService.create(request);
result.setInserted(result.getInserted() + 1);
} else {
userAdminService.update(existing.getId(), request);
result.setUpdated(result.getUpdated() + 1);
}
}
private SysRole matchRole(String text, List<SysRole> roles) {
if (!StringUtils.hasText(text)) {
throw new BusinessException("角色编码不能为空");
}
String value = text.trim();
for (SysRole role : roles) {
if (role.getCode() != null && role.getCode().equalsIgnoreCase(value)) {
return role;
}
}
for (SysRole role : roles) {
if (value.equals(role.getName())) {
return role;
}
}
return null;
}
private Long matchOrg(String text, List<SysOrg> orgs, Map<Long, SysOrg> byId) {
if (!StringUtils.hasText(text)) {
return null;
}
String value = text.trim();
for (SysOrg org : orgs) {
if (value.equals(org.getCode())) {
return org.getId();
}
}
List<SysOrg> byPath = new ArrayList<>();
List<SysOrg> byName = new ArrayList<>();
for (SysOrg org : orgs) {
if (value.equals(pathOf(org, byId))) {
byPath.add(org);
}
if (value.equals(org.getName())) {
byName.add(org);
}
}
if (byPath.size() == 1) {
return byPath.get(0).getId();
}
if (byName.size() == 1) {
return byName.get(0).getId();
}
if (byName.size() > 1) {
throw new BusinessException("组织名称不唯一,请填写组织编码");
}
throw new BusinessException("组织不存在:" + value);
}
private Integer parseStatus(String text) {
if (!StringUtils.hasText(text) || "启用".equals(text.trim()) || "1".equals(text.trim())) {
return 1;
}
if ("停用".equals(text.trim()) || "0".equals(text.trim())) {
return 0;
}
throw new BusinessException("状态只能填启用或停用");
}
private String pathOf(SysOrg org, Map<Long, SysOrg> byId) {
LinkedHashMap<Long, String> guard = new LinkedHashMap<>();
List<String> parts = new ArrayList<>();
SysOrg cursor = org;
while (cursor != null && guard.put(cursor.getId(), cursor.getName()) == null) {
parts.add(0, cursor.getName());
cursor = cursor.getParentId() == null ? null : byId.get(cursor.getParentId());
}
return String.join("/", parts);
}
private Map<String, Integer> headerIndex(Row head) {
Map<String, Integer> columns = new HashMap<>();
if (head == null) {
return columns;
}
for (Cell cell : head) {
String name = formatter.formatCellValue(cell).replace("*", "").replace("*", "").trim();
if (StringUtils.hasText(name)) {
columns.put(name, cell.getColumnIndex());
}
}
return columns;
}
private boolean hintRow(Sheet sheet) {
Row second = sheet.getRow(1);
if (second == null) {
return false;
}
String first = formatter.formatCellValue(second.getCell(0));
return first.startsWith("必填") || first.startsWith("选填");
}
private String cell(Row row, Integer index) {
if (index == null) {
return "";
}
return formatter.formatCellValue(row.getCell(index)).trim();
}
private boolean isSample(String value) {
return value != null && (value.startsWith("示例:") || value.startsWith("示例:"));
}
private void dropdown(Sheet sheet, int column, String formula) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = formula.startsWith("\"")
? helper.createExplicitListConstraint(new String[]{"启用", "停用"})
: helper.createFormulaListConstraint(formula);
CellRangeAddressList range = new CellRangeAddressList(2, 5000, column, column);
DataValidation validation = helper.createValidation(constraint, range);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
private CellStyle headStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
private CellStyle hintStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontHeightInPoints((short) 9);
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setWrapText(true);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}
@@ -0,0 +1,94 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.admin.entity.ListFieldConfig;
import com.banben.modules.admin.mapper.ListFieldConfigMapper;
import com.banben.modules.admin.service.ListFieldConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 列表显示字段配置服务实现。
*/
@Service
@RequiredArgsConstructor
public class ListFieldConfigServiceImpl implements ListFieldConfigService {
private final ListFieldConfigMapper listFieldConfigMapper;
/** 默认展示字段:字段键 / 显示名 */
private static final List<String[]> DEFAULT_SEARCH_FIELDS = Arrays.asList(
new String[]{"title", "文献题名"},
new String[]{"publishYear", "发行时间"},
new String[]{"author", "作者"},
new String[]{"authorOrg", "作者单位"},
new String[]{"publisher", "来源刊名/出版社"},
new String[]{"mediaType", "资源类型"},
new String[]{"sourceLibrary", "来源院校"},
new String[]{"sourceRepo", "来源资源库名"}
);
@Override
public List<ListFieldConfig> listScene(String scene) {
List<ListFieldConfig> list = queryScene(scene);
if (list.isEmpty()) {
return resetScene(scene);
}
return list;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveScene(String scene, List<ListFieldConfig> items) {
// 场景内全量覆盖:先删除旧配置(物理删除,避免历史脏数据堆积)
listFieldConfigMapper.delete(new LambdaQueryWrapper<ListFieldConfig>().eq(ListFieldConfig::getScene, scene));
if (items == null || items.isEmpty()) {
return;
}
int no = 1;
for (ListFieldConfig item : items) {
ListFieldConfig cfg = new ListFieldConfig();
cfg.setScene(scene);
cfg.setFieldKey(item.getFieldKey());
cfg.setFieldLabel(item.getFieldLabel());
cfg.setSortNo(item.getSortNo() != null ? item.getSortNo() : no * 10);
cfg.setVisible(item.getVisible() == null ? 1 : item.getVisible());
listFieldConfigMapper.insert(cfg);
no++;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<ListFieldConfig> resetScene(String scene) {
listFieldConfigMapper.delete(new LambdaQueryWrapper<ListFieldConfig>().eq(ListFieldConfig::getScene, scene));
List<ListFieldConfig> defaults = new ArrayList<>();
int no = 1;
for (String[] kv : DEFAULT_SEARCH_FIELDS) {
ListFieldConfig cfg = new ListFieldConfig();
cfg.setScene(scene);
cfg.setFieldKey(kv[0]);
cfg.setFieldLabel(kv[1]);
cfg.setSortNo(no * 10);
cfg.setVisible(1);
listFieldConfigMapper.insert(cfg);
defaults.add(cfg);
no++;
}
return defaults;
}
private List<ListFieldConfig> queryScene(String scene) {
return listFieldConfigMapper.selectList(
new LambdaQueryWrapper<ListFieldConfig>()
.eq(ListFieldConfig::getScene, scene)
.orderByAsc(ListFieldConfig::getSortNo)
.orderByAsc(ListFieldConfig::getId)
);
}
}
@@ -0,0 +1,215 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.OrgSaveRequest;
import com.banben.modules.admin.dto.OrgTreeVO;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 组织树的增删改。删除时若仍有下级或用户则拒绝。
*/
@Service
@RequiredArgsConstructor
public class OrgServiceImpl implements OrgService {
private final SysOrgMapper orgMapper;
private final SysUserMapper userMapper;
@Override
public List<OrgTreeVO> tree() {
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>()
.orderByAsc(SysOrg::getSortNo)
.orderByAsc(SysOrg::getId));
Map<Long, OrgTreeVO> nodes = new HashMap<>();
for (SysOrg org : all) {
nodes.put(org.getId(), toVo(org));
}
List<OrgTreeVO> roots = new ArrayList<>();
for (SysOrg org : all) {
OrgTreeVO node = nodes.get(org.getId());
OrgTreeVO parent = org.getParentId() == null ? null : nodes.get(org.getParentId());
if (parent == null) {
roots.add(node);
} else {
if (parent.getChildren() == null) {
parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(node);
}
}
sortTree(roots);
return roots;
}
@Override
public void create(OrgSaveRequest request) {
SysOrg org = new SysOrg();
fill(org, request, null);
orgMapper.insert(org);
}
@Override
public void update(Long id, OrgSaveRequest request) {
SysOrg org = require(id);
fill(org, request, id);
orgMapper.update(null, new LambdaUpdateWrapper<SysOrg>()
.eq(SysOrg::getId, id)
.set(SysOrg::getParentId, org.getParentId())
.set(SysOrg::getName, org.getName())
.set(SysOrg::getCode, org.getCode())
.set(SysOrg::getSortNo, org.getSortNo())
.set(SysOrg::getStatus, org.getStatus())
.set(SysOrg::getRemark, org.getRemark()));
syncUserOrgName(org);
}
@Override
public void remove(Long id) {
require(id);
Long children = orgMapper.selectCount(new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getParentId, id));
if (children != null && children > 0) {
throw new BusinessException("请先删除下级组织");
}
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, id));
if (users != null && users > 0) {
throw new BusinessException("该组织下还有用户,不能删除");
}
orgMapper.deleteById(id);
}
@Override
public Set<Long> subtreeIds(Long orgId) {
require(orgId);
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<>());
Map<Long, List<Long>> children = new HashMap<>();
for (SysOrg org : all) {
if (org.getParentId() != null) {
children.computeIfAbsent(org.getParentId(), key -> new ArrayList<>()).add(org.getId());
}
}
Set<Long> ids = new HashSet<>();
collect(orgId, children, ids);
return ids;
}
private void collect(Long id, Map<Long, List<Long>> children, Set<Long> ids) {
if (!ids.add(id)) {
return;
}
for (Long child : children.getOrDefault(id, List.of())) {
collect(child, children, ids);
}
}
private void fill(SysOrg org, OrgSaveRequest request, Long selfId) {
Long parentId = request.getParentId();
if (parentId != null) {
if (parentId.equals(selfId)) {
throw new BusinessException("上级组织不能是自己");
}
require(parentId);
assertNoCycle(selfId, parentId);
}
String code = blankToNull(request.getCode());
assertCodeUnique(code, selfId);
org.setParentId(parentId);
org.setName(request.getName().trim());
org.setCode(code);
org.setSortNo(request.getSortNo() == null ? 0 : request.getSortNo());
org.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
org.setRemark(blankToNull(request.getRemark()));
}
private void assertNoCycle(Long selfId, Long parentId) {
if (selfId == null) {
return;
}
Long cursor = parentId;
Set<Long> seen = new HashSet<>();
while (cursor != null) {
if (cursor.equals(selfId)) {
throw new BusinessException("不能把组织移动到自己的下级");
}
if (!seen.add(cursor)) {
break;
}
SysOrg parent = orgMapper.selectById(cursor);
cursor = parent == null ? null : parent.getParentId();
}
}
private void assertCodeUnique(String code, Long selfId) {
if (code == null) {
return;
}
LambdaQueryWrapper<SysOrg> query = new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getCode, code);
if (selfId != null) {
query.ne(SysOrg::getId, selfId);
}
Long count = orgMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("组织编码已存在");
}
}
private void syncUserOrgName(SysOrg org) {
SysUser patch = new SysUser();
patch.setOrgName(org.getName());
userMapper.update(patch, new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, org.getId()));
}
private SysOrg require(Long id) {
SysOrg org = orgMapper.selectById(id);
if (org == null) {
throw new BusinessException("组织不存在");
}
return org;
}
private OrgTreeVO toVo(SysOrg org) {
OrgTreeVO vo = new OrgTreeVO();
vo.setId(org.getId());
vo.setParentId(org.getParentId());
vo.setName(org.getName());
vo.setCode(org.getCode());
vo.setSortNo(org.getSortNo());
vo.setStatus(org.getStatus());
vo.setRemark(org.getRemark());
return vo;
}
private void sortTree(List<OrgTreeVO> nodes) {
nodes.sort(Comparator
.comparing((OrgTreeVO node) -> node.getSortNo() == null ? 0 : node.getSortNo())
.thenComparing(OrgTreeVO::getId));
for (OrgTreeVO node : nodes) {
if (node.getChildren() != null) {
sortTree(node.getChildren());
}
}
}
private String blankToNull(String value) {
if (!StringUtils.hasText(value)) {
return null;
}
return value.trim();
}
}
@@ -0,0 +1,35 @@
package com.banben.modules.admin.service.impl;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException;
import com.banben.modules.admin.entity.ResourceNode;
import com.banben.modules.admin.mapper.ResourceNodeMapper;
import com.banben.modules.admin.service.ResourceNodeService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 院校资源节点服务实现。
*/
@Service
public class ResourceNodeServiceImpl extends ServiceImpl<ResourceNodeMapper, ResourceNode>
implements ResourceNodeService {
@Override
public List<ResourceNode> listOrdered() {
return this.lambdaQuery()
.orderByAsc(ResourceNode::getSortNo)
.orderByAsc(ResourceNode::getId)
.list();
}
@Override
public void removeBatch(List<Long> ids) {
if (CollUtil.isEmpty(ids)) {
throw new BusinessException("请先选择要删除的资源节点");
}
this.removeByIds(ids);
}
}
@@ -0,0 +1,193 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.RoleSaveRequest;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.admin.service.RoleService;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.auth.nav.NavMenus;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 角色增删改。ADMIN、USER 为内置角色。
*/
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
private final SysRoleMapper roleMapper;
private final SysRoleMenuMapper roleMenuMapper;
private final SysUserMapper userMapper;
@Override
public List<SysRole> listAll() {
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
.orderByDesc(SysRole::getBuiltin)
.orderByAsc(SysRole::getId));
Map<Long, List<String>> menus = roleMenuMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.groupingBy(SysRoleMenu::getRoleId,
Collectors.mapping(SysRoleMenu::getMenuCode, Collectors.toList())));
for (SysRole role : roles) {
if (isAdminCode(role)) {
role.setMenuCodes(new ArrayList<>(NavMenus.CODES));
continue;
}
role.setMenuCodes(menus.getOrDefault(role.getId(), List.of()).stream()
.filter(NavMenus::contains)
.distinct()
.toList());
}
return roles;
}
@Override
public void create(RoleSaveRequest request) {
SysRole role = new SysRole();
role.setBuiltin(0);
fill(role, request, null);
roleMapper.insert(role);
replaceMenus(role.getId(), request.getMenuCodes());
markMenusInited(role.getId());
}
@Override
public void update(Long id, RoleSaveRequest request) {
SysRole role = require(id);
String previousCode = role.getCode();
if (isBuiltin(role) && !previousCode.equalsIgnoreCase(request.getCode().trim())) {
throw new BusinessException("内置角色不能修改编码");
}
fill(role, request, id);
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
.eq(SysRole::getId, id)
.set(SysRole::getCode, role.getCode())
.set(SysRole::getName, role.getName())
.set(SysRole::getRemark, role.getRemark())
.set(SysRole::getStatus, role.getStatus()));
if (!previousCode.equals(role.getCode())) {
userMapper.update(null, new LambdaUpdateWrapper<SysUser>()
.set(SysUser::getRole, role.getCode())
.eq(SysUser::getRoleId, id));
}
if (isAdminCode(role)) {
replaceMenus(id, NavMenus.CODES);
markMenusInited(id);
} else if (request.getMenuCodes() != null) {
replaceMenus(id, request.getMenuCodes());
markMenusInited(id);
}
}
@Override
public void remove(Long id) {
SysRole role = require(id);
if (isBuiltin(role)) {
throw new BusinessException("内置角色不能删除");
}
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRoleId, id));
if (users != null && users > 0) {
throw new BusinessException("该角色下还有用户,不能删除");
}
roleMapper.deleteById(id);
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
}
@Override
public void ensureBuiltin() {
ensure("ADMIN", "系统管理员", "系统内置,可管理组织、用户与角色");
ensure("USER", "普通用户", "系统内置普通用户");
}
private void ensure(String code, String name, String remark) {
SysRole existing = roleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
if (existing != null) {
if ("ADMIN".equalsIgnoreCase(code)) {
replaceMenus(existing.getId(), NavMenus.CODES);
markMenusInited(existing.getId());
}
return;
}
SysRole role = new SysRole();
role.setCode(code);
role.setName(name);
role.setRemark(remark);
role.setStatus(1);
role.setBuiltin(1);
roleMapper.insert(role);
replaceMenus(role.getId(), NavMenus.CODES);
markMenusInited(role.getId());
}
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
String code = request.getCode().trim().toUpperCase();
LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code);
if (selfId != null) {
query.ne(SysRole::getId, selfId);
}
Long count = roleMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("角色编码已存在");
}
role.setCode(code);
role.setName(request.getName().trim());
role.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
role.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
}
private SysRole require(Long id) {
SysRole role = roleMapper.selectById(id);
if (role == null) {
throw new BusinessException("角色不存在");
}
return role;
}
private boolean isBuiltin(SysRole role) {
return role.getBuiltin() != null && role.getBuiltin() == 1;
}
private boolean isAdminCode(SysRole role) {
return role.getCode() != null && "ADMIN".equalsIgnoreCase(role.getCode());
}
private void replaceMenus(Long roleId, List<String> menuCodes) {
List<String> codes = menuCodes == null ? new ArrayList<>(NavMenus.CODES) : normalize(menuCodes);
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
for (String code : codes) {
SysRoleMenu row = new SysRoleMenu();
row.setRoleId(roleId);
row.setMenuCode(code);
roleMenuMapper.insert(row);
}
}
private List<String> normalize(List<String> menuCodes) {
LinkedHashSet<String> codes = new LinkedHashSet<>();
for (String code : menuCodes) {
if (NavMenus.contains(code)) {
codes.add(code);
}
}
return new ArrayList<>(codes);
}
private void markMenusInited(Long roleId) {
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
.eq(SysRole::getId, roleId)
.set(SysRole::getMenuInited, 1));
}
}
@@ -0,0 +1,168 @@
package com.banben.modules.admin.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.SensitiveHitVO;
import com.banben.modules.admin.entity.SensitiveWord;
import com.banben.modules.admin.mapper.SensitiveWordMapper;
import com.banben.modules.admin.service.SensitiveWordService;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 敏感词库服务实现。
*/
@Service
@RequiredArgsConstructor
public class SensitiveWordServiceImpl extends ServiceImpl<SensitiveWordMapper, SensitiveWord>
implements SensitiveWordService {
private final VersionResourceMapper resourceMapper;
@Override
public Page<SensitiveWord> pageWords(long current, long size, String keyword) {
LambdaUpdateWrapper<SensitiveWord> w = new LambdaUpdateWrapper<>();
if (StrUtil.isNotBlank(keyword)) {
String kw = keyword.trim();
w.and(x -> x.like(SensitiveWord::getWord, kw).or().like(SensitiveWord::getPinyin, kw));
}
w.orderByDesc(SensitiveWord::getCreateTime);
return this.page(Page.of(current, size), w);
}
@Override
public void saveWord(SensitiveWord word) {
normalizeAndCheckDuplicate(word, null);
this.save(word);
}
@Override
public void updateWord(Long id, SensitiveWord word) {
if (this.getById(id) == null) {
throw new BusinessException("敏感词不存在");
}
normalizeAndCheckDuplicate(word, id);
word.setId(id);
this.updateById(word);
}
@Override
public void removeBatch(List<Long> ids) {
if (CollUtil.isEmpty(ids)) {
throw new BusinessException("请先选择要删除的敏感词");
}
this.removeByIds(ids);
}
@Override
public Page<SensitiveHitVO> hits(long current, long size) {
List<SensitiveWord> words = this.list();
if (CollUtil.isEmpty(words)) {
return Page.of(current, size);
}
// title/summary/keywords/note 任一字段命中任一敏感词即视为命中
QueryWrapper<VersionResource> w = new QueryWrapper<>();
w.eq("deleted", 0);
w.and(x -> {
for (SensitiveWord sw : words) {
String word = sw.getWord();
x.or(y -> y.like("title", word))
.or(y -> y.like("summary", word))
.or(y -> y.like("keywords", word))
.or(y -> y.like("note", word));
}
});
Page<VersionResource> page = resourceMapper.selectPage(Page.of(current, size), w);
Page<SensitiveHitVO> vo = Page.of(page.getCurrent(), page.getSize(), page.getTotal());
vo.setRecords(page.getRecords().stream()
.map(r -> toHitVO(r, words))
.toList());
return vo;
}
@Override
@Transactional
public int handleAction(List<Long> ids, String action) {
if (CollUtil.isEmpty(ids)) {
throw new BusinessException("请先选择要处置的记录");
}
if (StrUtil.isBlank(action)) {
throw new BusinessException("请指定处置动作");
}
switch (action.toUpperCase()) {
case "MASK", "OFFLINE" -> {
// 屏蔽/下架:置管理状态,同时打上敏感标记
LambdaUpdateWrapper<VersionResource> uw = new LambdaUpdateWrapper<>();
uw.in(VersionResource::getId, ids)
.set(VersionResource::getManageStatus, "MASK".equalsIgnoreCase(action) ? 1 : 2)
.set(VersionResource::getSensitiveFlag, 1);
resourceMapper.update(null, uw);
}
case "RESTORE" -> {
LambdaUpdateWrapper<VersionResource> uw = new LambdaUpdateWrapper<>();
uw.in(VersionResource::getId, ids).set(VersionResource::getManageStatus, 0);
resourceMapper.update(null, uw);
}
case "DELETE" -> resourceMapper.deleteBatchIds(ids);
default -> throw new BusinessException("不支持的处置动作:" + action);
}
return ids.size();
}
// ------------------------------------------------------------------
/** 去空格 + 词唯一性校验(excludeId 为更新时排除自身) */
private void normalizeAndCheckDuplicate(SensitiveWord word, Long excludeId) {
String w = StrUtil.trimToNull(word.getWord());
if (w == null) {
throw new BusinessException("敏感词不能为空");
}
word.setWord(w);
word.setPinyin(StrUtil.trimToNull(word.getPinyin()));
long cnt = this.lambdaQuery()
.eq(SensitiveWord::getWord, w)
.ne(excludeId != null, SensitiveWord::getId, excludeId)
.count();
if (cnt > 0) {
throw new BusinessException("敏感词已存在:" + w);
}
}
/** 计算单条资源命中的敏感词 */
private SensitiveHitVO toHitVO(VersionResource r, List<SensitiveWord> words) {
SensitiveHitVO vo = new SensitiveHitVO();
vo.setId(r.getId());
vo.setTitle(r.getTitle());
vo.setAuthor(r.getAuthor());
vo.setSourceLibrary(r.getSourceLibrary());
vo.setMediaType(r.getMediaType());
vo.setGovernStatus(r.getGovernStatus());
vo.setSensitiveFlag(r.getSensitiveFlag());
vo.setManageStatus(r.getManageStatus());
String haystack = StrUtil.nullToEmpty(r.getTitle()) + "\n"
+ StrUtil.nullToEmpty(r.getSummary()) + "\n"
+ StrUtil.nullToEmpty(r.getKeywords()) + "\n"
+ StrUtil.nullToEmpty(r.getNote());
for (SensitiveWord sw : words) {
if (haystack.contains(sw.getWord())) {
vo.getMatchedWords().add(sw.getWord());
}
}
return vo;
}
}
@@ -0,0 +1,216 @@
package com.banben.modules.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.banben.common.BusinessException;
import com.banben.modules.admin.dto.UserSaveRequest;
import com.banben.modules.admin.dto.UserVO;
import com.banben.modules.admin.entity.SysOrg;
import com.banben.modules.admin.entity.SysRole;
import com.banben.modules.admin.mapper.SysOrgMapper;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.service.OrgService;
import com.banben.modules.admin.service.UserAdminService;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 用户新增、修改、删除。密码留空时,新增使用 123456,修改则保持原密码。
*/
@Service
@RequiredArgsConstructor
public class UserAdminServiceImpl implements UserAdminService {
static final String DEFAULT_PASSWORD = "123456";
private final SysUserMapper userMapper;
private final SysRoleMapper roleMapper;
private final SysOrgMapper orgMapper;
private final OrgService orgService;
private final PasswordEncoder passwordEncoder;
@Override
public Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId) {
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
if (StringUtils.hasText(keyword)) {
String word = keyword.trim();
query.and(w -> w.like(SysUser::getUsername, word).or().like(SysUser::getRealName, word));
}
if (orgId != null) {
query.in(SysUser::getOrgId, orgService.subtreeIds(orgId));
}
if (roleId != null) {
query.eq(SysUser::getRoleId, roleId);
}
query.orderByDesc(SysUser::getId);
Page<SysUser> raw = userMapper.selectPage(new Page<>(current, size), query);
Map<Long, SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.toMap(SysRole::getId, role -> role, (a, b) -> a));
Map<Long, SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>()).stream()
.collect(Collectors.toMap(SysOrg::getId, org -> org, (a, b) -> a));
Page<UserVO> page = new Page<>(raw.getCurrent(), raw.getSize(), raw.getTotal());
page.setRecords(raw.getRecords().stream().map(user -> toVo(user, roles, orgs)).toList());
return page;
}
@Override
public void create(UserSaveRequest request) {
SysRole role = requireRole(request.getRoleId());
SysOrg org = optionalOrg(request.getOrgId());
assertUsernameFree(request.getUsername().trim(), null);
assertPassword(request.getPassword(), true);
SysUser user = new SysUser();
user.setUsername(request.getUsername().trim());
user.setPassword(passwordEncoder.encode(passwordOrDefault(request.getPassword())));
user.setRealName(request.getRealName().trim());
user.setRoleId(role.getId());
user.setRole(role.getCode());
user.setOrgId(org == null ? null : org.getId());
user.setOrgName(org == null ? null : org.getName());
user.setStatus(statusOf(request.getStatus()));
try {
userMapper.insert(user);
} catch (DuplicateKeyException e) {
throw new BusinessException("登录账号已存在");
}
}
@Override
public void update(Long id, UserSaveRequest request) {
SysUser existing = requireUser(id);
SysRole role = requireRole(request.getRoleId());
SysOrg org = optionalOrg(request.getOrgId());
assertUsernameFree(request.getUsername().trim(), id);
assertPassword(request.getPassword(), false);
guardLastAdmin(existing, role.getCode(), statusOf(request.getStatus()), false);
LambdaUpdateWrapper<SysUser> update = new LambdaUpdateWrapper<SysUser>()
.eq(SysUser::getId, id)
.set(SysUser::getUsername, request.getUsername().trim())
.set(SysUser::getRealName, request.getRealName().trim())
.set(SysUser::getRoleId, role.getId())
.set(SysUser::getRole, role.getCode())
.set(SysUser::getOrgId, org == null ? null : org.getId())
.set(SysUser::getOrgName, org == null ? null : org.getName())
.set(SysUser::getStatus, statusOf(request.getStatus()));
if (StringUtils.hasText(request.getPassword())) {
update.set(SysUser::getPassword, passwordEncoder.encode(request.getPassword().trim()));
}
try {
userMapper.update(null, update);
} catch (DuplicateKeyException e) {
throw new BusinessException("登录账号已存在");
}
}
@Override
public void remove(Long id) {
SysUser existing = requireUser(id);
if (id.equals(UserContext.currentUserId())) {
throw new BusinessException("不能删除当前登录账号");
}
guardLastAdmin(existing, null, 0, true);
userMapper.deleteById(id);
}
private void guardLastAdmin(SysUser existing, String nextRole, int nextStatus, boolean deleting) {
if (!"ADMIN".equalsIgnoreCase(existing.getRole())) {
return;
}
boolean stillAdmin = !deleting && "ADMIN".equalsIgnoreCase(nextRole) && nextStatus == 1;
if (stillAdmin) {
return;
}
Long admins = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getRole, "ADMIN")
.eq(SysUser::getStatus, 1)
.ne(SysUser::getId, existing.getId()));
if (admins == null || admins == 0) {
throw new BusinessException("至少保留一个启用的系统管理员");
}
}
private void assertUsernameFree(String username, Long selfId) {
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
if (selfId != null) {
query.ne(SysUser::getId, selfId);
}
Long count = userMapper.selectCount(query);
if (count != null && count > 0) {
throw new BusinessException("登录账号已存在");
}
}
private SysUser requireUser(Long id) {
SysUser user = userMapper.selectById(id);
if (user == null) {
throw new BusinessException("用户不存在");
}
return user;
}
private SysRole requireRole(Long roleId) {
SysRole role = roleMapper.selectById(roleId);
if (role == null) {
throw new BusinessException("角色不存在");
}
return role;
}
private SysOrg optionalOrg(Long orgId) {
if (orgId == null) {
return null;
}
SysOrg org = orgMapper.selectById(orgId);
if (org == null) {
throw new BusinessException("组织不存在");
}
return org;
}
private int statusOf(Integer status) {
return status != null && status == 0 ? 0 : 1;
}
private String passwordOrDefault(String password) {
return StringUtils.hasText(password) ? password.trim() : DEFAULT_PASSWORD;
}
private void assertPassword(String password, boolean creating) {
if (!StringUtils.hasText(password)) {
return;
}
if (password.trim().length() < 6) {
throw new BusinessException(creating ? "密码至少 6 位,留空则使用 123456" : "密码至少 6 位");
}
}
private UserVO toVo(SysUser user, Map<Long, SysRole> roles, Map<Long, SysOrg> orgs) {
UserVO vo = new UserVO();
vo.setId(user.getId());
vo.setUsername(user.getUsername());
vo.setRealName(user.getRealName());
vo.setRoleId(user.getRoleId());
vo.setRoleCode(user.getRole());
SysRole role = user.getRoleId() == null ? null : roles.get(user.getRoleId());
vo.setRoleName(role == null ? user.getRole() : role.getName());
vo.setOrgId(user.getOrgId());
SysOrg org = user.getOrgId() == null ? null : orgs.get(user.getOrgId());
vo.setOrgName(org == null ? user.getOrgName() : org.getName());
vo.setStatus(user.getStatus());
vo.setLastLoginTime(user.getLastLoginTime());
vo.setCreateTime(user.getCreateTime());
return vo;
}
}
@@ -0,0 +1,59 @@
package com.banben.modules.admin.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.auth.context.LoginUser;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/**
* 后台管理接口:角色勾选了「后台管理」栏目才能调用。
* 权限表暂时不可用时,仍放行角色编码为 ADMIN 的账号,避免把管理员锁在外面。
*/
@Component
@RequiredArgsConstructor
public class AdminAccess {
private final SysUserMapper userMapper;
private final SysRoleMenuMapper roleMenuMapper;
public void require() {
LoginUser login = UserContext.get();
if (login == null || login.id() == null || !allowed(login.id(), login.role())) {
throw new BusinessException(403, "需要后台管理权限");
}
}
private boolean allowed(Long userId, String roleCode) {
if (isAdminCode(roleCode)) {
return true;
}
try {
SysUser user = userMapper.selectById(userId);
if (user == null) {
return false;
}
if (isAdminCode(user.getRole())) {
return true;
}
if (user.getRoleId() == null) {
return false;
}
Long count = roleMenuMapper.selectCount(new LambdaQueryWrapper<SysRoleMenu>()
.eq(SysRoleMenu::getRoleId, user.getRoleId())
.eq(SysRoleMenu::getMenuCode, "admin"));
return count != null && count > 0;
} catch (Exception ignored) {
return isAdminCode(roleCode);
}
}
private boolean isAdminCode(String roleCode) {
return roleCode != null && "ADMIN".equalsIgnoreCase(roleCode);
}
}
@@ -126,14 +126,49 @@ public class AnalysisServiceImpl implements AnalysisService {
@Override
public List<FacetItem> hotKeywords(int limit) {
int top = Math.max(1, limit);
// 热词 = 检索日志真实检索词 + 元数据关键词(库内真实数据),合并累计
Map<String, Long> merged = new LinkedHashMap<>();
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));
.last("limit " + top * 3);
for (Map<String, Object> m : searchLogMapper.selectMaps(wrapper)) {
Object name = m.get("name");
if (name == null) {
continue;
}
String word = String.valueOf(name).trim();
if (!word.isEmpty()) {
merged.merge(word, toLong(m.get("cnt")), Long::sum);
}
}
// 元数据关键词按分号/逗号拆分后的高频词(补充检索日志条数不足时的词云展示)
try {
for (Map<String, Object> m : resourceMapper.splitKeywordCounts(top * 3)) {
Object name = m.get("name");
if (name == null) {
continue;
}
String word = String.valueOf(name).trim();
if (!word.isEmpty()) {
merged.merge(word, toLong(m.get("cnt")), Long::sum);
}
}
} catch (Exception e) {
// 拆分统计失败时退化为仅检索日志热词
}
return merged.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(top)
.map(e -> new FacetItem(e.getKey(), e.getValue()))
.toList();
}
@Override
@@ -0,0 +1,51 @@
package com.banben.modules.auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
* 登录日志表自举建表。
*
* <p>应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
* 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
* 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。</p>
*/
@Slf4j
@Component
public class LoginLogTableInitializer {
private final JdbcTemplate jdbcTemplate;
public LoginLogTableInitializer(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@EventListener(ApplicationReadyEvent.class)
public void init() {
try {
jdbcTemplate.execute(
"CREATE TABLE IF NOT EXISTS login_log ("
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
+ "user_id BIGINT, "
+ "username VARCHAR(128), "
+ "real_name VARCHAR(128), "
+ "org_name VARCHAR(256), "
+ "ip VARCHAR(64), "
+ "user_agent VARCHAR(512), "
+ "login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
+ "logout_time TIMESTAMP, "
+ "online SMALLINT DEFAULT 1, "
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time)");
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online)");
log.info("登录日志表 login_log 已就绪(不存在则已自动创建)");
} catch (Exception e) {
// 建表失败不应阻断启动;缺表时登录日志接口已做优雅降级
log.warn("自动创建 login_log 表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
}
}
}
@@ -5,12 +5,16 @@ 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 com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.context.UserContext;
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;
/**
* 认证接口。
*/
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.*;
public class AuthController {
private final AuthService authService;
private final LoginLogService loginLogService;
@Operation(summary = "登录")
@PostMapping("/login")
@@ -34,10 +39,17 @@ public class AuthController {
return Result.success(authService.currentUser());
}
@Operation(summary = "当前用户可见的顶部导航")
@GetMapping("/menus")
public Result<List<String>> menus() {
return Result.success(authService.currentMenus());
}
@Operation(summary = "登出")
@PostMapping("/logout")
public Result<Void> logout() {
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
loginLogService.recordLogout(UserContext.currentUserId());
return Result.success();
}
}
@@ -0,0 +1,76 @@
package com.banben.modules.auth.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.admin.support.AdminAccess;
import com.banben.modules.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
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;
/**
* 后台管理 - 登录日志。
*/
@Tag(name = "后台管理-登录日志")
@RestController
@RequestMapping("/api/admin/login-logs")
@RequiredArgsConstructor
public class LoginLogController {
private final LoginLogService loginLogService;
private final AdminAccess adminAccess;
@Operation(summary = "登录日志分页(支持账号/姓名/单位关键字、在线状态、登录时间区间)")
@GetMapping("/page")
public Result<PageResult<LoginLog>> page(LoginLogQuery query) {
adminAccess.require();
return Result.success(loginLogService.page(query));
}
@Operation(summary = "登录日志概览:会话总数 / 当前在线 / 今日登录")
@GetMapping("/summary")
public Result<LoginLogSummary> summary() {
adminAccess.require();
return Result.success(loginLogService.summary());
}
@Operation(summary = "网络访问概览:历史/本月/本周/今日 的人次与人数")
@GetMapping("/access-overview")
public Result<AccessOverview> accessOverview() {
adminAccess.require();
return Result.success(loginLogService.accessOverview());
}
@Operation(summary = "网络访问趋势:按 小时/日/周/月/年 分桶(可指定时段)")
@GetMapping("/access-trend")
public Result<List<AccessTrendPoint>> accessTrend(
@RequestParam(defaultValue = "hour") String granularity,
@RequestParam(required = false) String start,
@RequestParam(required = false) String end) {
adminAccess.require();
return Result.success(loginLogService.accessTrend(granularity, start, end));
}
@Operation(summary = "网络访问维度统计:按 IP/单位/账号/类型 分组(可指定时段)")
@GetMapping("/access-dimension")
public Result<List<AccessDimensionItem>> accessDimension(
@RequestParam(defaultValue = "ip") String dimension,
@RequestParam(required = false) String start,
@RequestParam(required = false) String end,
@RequestParam(defaultValue = "20") int limit) {
adminAccess.require();
return Result.success(loginLogService.accessDimension(dimension, start, end, limit));
}
}
@@ -0,0 +1,31 @@
package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 登录日志查询条件。
*/
@Data
@Schema(description = "登录日志查询条件")
public class LoginLogQuery {
@Schema(description = "页码,从1开始", example = "1")
private Long current = 1L;
@Schema(description = "每页条数", example = "20")
private Long size = 20L;
@Schema(description = "关键字:匹配账号 / 姓名 / 单位")
private String keyword;
/** ONLINE 在线 / OFFLINE 离线 / 空 全部 */
@Schema(description = "状态:ONLINE 在线 / OFFLINE 离线 / 空 全部")
private String status;
@Schema(description = "登录时间起(含,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss)")
private String loginStart;
@Schema(description = "登录时间止(含)")
private String loginEnd;
}
@@ -3,6 +3,8 @@ package com.banben.modules.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 登录响应。
*/
@@ -27,4 +29,7 @@ public class LoginResponse {
@Schema(description = "所属单位")
private String orgName;
@Schema(description = "可见的顶部导航编码")
private List<String> menus;
}
@@ -0,0 +1,60 @@
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.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 用户登录日志(会话维度)。
*
* <p>一次成功登录产生一条会话记录:{@code online=1}、{@code logoutTime=null};
* 用户主动退出时回填 {@code logoutTime} 并置 {@code online=0}。
* 「在线」状态以 {@code logoutTime 为 null} 为准,前端据此展示在线/离线。</p>
*/
@Data
@TableName("login_log")
@Schema(description = "用户登录日志(会话维度:一次登录一条,登出置 logout_time)")
public class LoginLog implements Serializable {
@TableId(type = IdType.AUTO)
@Schema(description = "主键")
private Long id;
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "登录账号")
private String username;
@Schema(description = "姓名")
private String realName;
@Schema(description = "所属单位")
private String orgName;
@Schema(description = "登录IP")
private String ip;
@Schema(description = "浏览器/客户端标识")
private String userAgent;
@Schema(description = "登录时间")
private LocalDateTime loginTime;
@Schema(description = "退出时间,未退出为 null")
private LocalDateTime logoutTime;
@Schema(description = "是否在线:1在线 0离线")
private Integer online;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -6,6 +6,7 @@ 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 com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -20,24 +21,31 @@ import java.time.LocalDateTime;
@Schema(description = "系统用户")
public class SysUser implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "登录账号")
private String username;
@JsonIgnore
@Schema(description = "BCrypt 加密后的密码")
private String password;
@Schema(description = "姓名")
private String realName;
@Schema(description = "角色:ADMIN / USER")
@Schema(description = "角色编码,与 sys_role.code 一致,写入登录令牌")
private String role;
@Schema(description = "所属单位")
@Schema(description = "角色,对应 sys_role.id")
private Long roleId;
@Schema(description = "所属单位名称,与组织名称同步")
private String orgName;
@Schema(description = "所属组织,对应 sys_org.id")
private Long orgId;
@Schema(description = "状态:1启用 0停用")
private Integer status;
@@ -0,0 +1,10 @@
package com.banben.modules.auth.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.auth.entity.LoginLog;
/**
* 用户登录日志 Mapper。
*/
public interface LoginLogMapper extends BaseMapper<LoginLog> {
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.nav;
import java.util.List;
/**
* 顶部导航。编码与前端路由一致,角色按编码授权。
*/
public final class NavMenus {
public static final List<String> CODES = List.of(
"dashboard",
"search",
"hotwords",
"special",
"deposit",
"analysis",
"resource",
"collect",
"sync",
"governance",
"admin"
);
private NavMenus() {
}
public static boolean contains(String code) {
return code != null && CODES.contains(code);
}
}
@@ -4,6 +4,8 @@ import com.banben.modules.auth.dto.LoginRequest;
import com.banben.modules.auth.dto.LoginResponse;
import com.banben.modules.auth.entity.SysUser;
import java.util.List;
/**
* 认证服务。
*/
@@ -18,4 +20,9 @@ public interface AuthService {
* 查询当前登录用户完整信息。
*/
SysUser currentUser();
/**
* 当前用户可见的顶部导航编码。
*/
List<String> currentMenus();
}
@@ -0,0 +1,38 @@
package com.banben.modules.auth.service;
import com.banben.common.PageResult;
import com.banben.modules.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
import java.util.List;
/**
* 用户登录日志服务。
*/
public interface LoginLogService {
/** 记录一次成功登录(会话开始)。 */
void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent);
/** 记录退出:回填该用户最近一条未退出的会话。 */
void recordLogout(Long userId);
/** 分页查询登录日志。 */
PageResult<LoginLog> page(LoginLogQuery query);
/** 概览统计:总数 / 在线 / 今日登录。 */
LoginLogSummary summary();
/** 网络访问概览:历史 / 本月 / 本周 / 今日 的人次与人数。 */
AccessOverview accessOverview();
/** 网络访问趋势:按 小时/日/周/月/年 分桶统计。 */
List<AccessTrendPoint> accessTrend(String granularity, String start, String end);
/** 网络访问维度统计:按 IP / 单位 / 账号 / 类型 分组。 */
List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit);
}
@@ -1,20 +1,32 @@
package com.banben.modules.auth.service.impl;
import cn.hutool.core.util.StrUtil;
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.admin.entity.SysRole;
import com.banben.modules.admin.entity.SysRoleMenu;
import com.banben.modules.admin.mapper.SysRoleMapper;
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
import com.banben.modules.auth.entity.SysUser;
import com.banben.modules.auth.mapper.SysUserMapper;
import com.banben.modules.auth.nav.NavMenus;
import com.banben.modules.auth.service.AuthService;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 认证服务实现。
@@ -25,8 +37,11 @@ import java.time.LocalDateTime;
public class AuthServiceImpl implements AuthService {
private final SysUserMapper sysUserMapper;
private final SysRoleMapper sysRoleMapper;
private final SysRoleMenuMapper roleMenuMapper;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
private final LoginLogService loginLogService;
@Override
public LoginResponse login(LoginRequest request) {
@@ -40,10 +55,23 @@ public class AuthServiceImpl implements AuthService {
if (user.getStatus() != null && user.getStatus() == 0) {
throw new BusinessException("账号已停用,请联系管理员");
}
if (user.getRoleId() != null) {
SysRole role = sysRoleMapper.selectById(user.getRoleId());
if (role == null || (role.getStatus() != null && role.getStatus() == 0)) {
throw new BusinessException("角色已停用,请联系管理员");
}
user.setRole(role.getCode());
}
user.setLastLoginTime(LocalDateTime.now());
sysUserMapper.updateById(user);
// 记录登录日志(会话维度):取客户端 IP 与 UA
HttpServletRequest httpReq = currentRequest();
String ip = httpReq == null ? null : clientIp(httpReq);
String ua = httpReq == null ? null : httpReq.getHeader("User-Agent");
loginLogService.recordLogin(user.getId(), user.getUsername(), user.getRealName(), user.getOrgName(), ip, ua);
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
LoginResponse response = new LoginResponse();
@@ -53,9 +81,23 @@ public class AuthServiceImpl implements AuthService {
response.setRealName(user.getRealName());
response.setRole(user.getRole());
response.setOrgName(user.getOrgName());
response.setMenus(menusOf(user));
return response;
}
@Override
public List<String> currentMenus() {
Long userId = UserContext.currentUserId();
if (userId == null) {
throw new BusinessException("未登录");
}
SysUser user = sysUserMapper.selectById(userId);
if (user == null) {
throw new BusinessException("未登录");
}
return menusOf(user);
}
@Override
public SysUser currentUser() {
Long userId = UserContext.currentUserId();
@@ -68,4 +110,59 @@ public class AuthServiceImpl implements AuthService {
}
return user;
}
private List<String> menusOf(SysUser user) {
if (isAdmin(user)) {
return new ArrayList<>(NavMenus.CODES);
}
if (user.getRoleId() == null) {
return new ArrayList<>(NavMenus.CODES);
}
try {
return roleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, user.getRoleId()))
.stream()
.map(SysRoleMenu::getMenuCode)
.filter(NavMenus::contains)
.distinct()
.toList();
} catch (Exception e) {
log.warn("读取导航权限失败,暂时开放全部栏目:{}", e.getMessage());
return new ArrayList<>(NavMenus.CODES);
}
}
private boolean isAdmin(SysUser user) {
if (user.getRole() != null && "ADMIN".equalsIgnoreCase(user.getRole())) {
return true;
}
if (user.getRoleId() == null) {
return false;
}
SysRole role = sysRoleMapper.selectById(user.getRoleId());
return role != null && "ADMIN".equalsIgnoreCase(role.getCode());
}
/** 从请求上下文取当前 HttpServletRequest(非 Web 请求线程下为 null)。 */
private HttpServletRequest currentRequest() {
try {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs == null ? null : attrs.getRequest();
} catch (Exception e) {
return null;
}
}
/** 取真实客户端 IP,兼容反向代理的 X-Forwarded-For。 */
private String clientIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For");
if (StrUtil.isNotBlank(forwarded)) {
// X-Forwarded-For 格式:client, proxy1, proxy2
return StrUtil.subPre(forwarded.trim(), forwarded.indexOf(',') < 0 ? forwarded.length() : forwarded.indexOf(',')).trim();
}
String realIp = request.getHeader("X-Real-IP");
if (StrUtil.isNotBlank(realIp)) {
return realIp.trim();
}
return request.getRemoteAddr();
}
}
@@ -0,0 +1,260 @@
package com.banben.modules.auth.service.impl;
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.auth.dto.LoginLogQuery;
import com.banben.modules.auth.entity.LoginLog;
import com.banben.modules.auth.mapper.LoginLogMapper;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.vo.AccessDimensionItem;
import com.banben.modules.auth.vo.AccessOverview;
import com.banben.modules.auth.vo.AccessTrendPoint;
import com.banben.modules.auth.vo.LoginLogSummary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 用户登录日志服务实现。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginLogServiceImpl implements LoginLogService {
private final LoginLogMapper logMapper;
@Override
public void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent) {
try {
LoginLog entity = new LoginLog();
entity.setUserId(userId);
entity.setUsername(username);
entity.setRealName(realName);
entity.setOrgName(orgName);
entity.setIp(ip);
entity.setUserAgent(userAgent == null ? null : StrUtil.subPre(userAgent, 500));
entity.setLoginTime(LocalDateTime.now());
entity.setOnline(1);
logMapper.insert(entity);
} catch (Exception e) {
// 日志写入失败不应影响登录主流程
log.warn("记录登录日志失败(不影响登录):{}", e.getMessage());
}
}
@Override
public void recordLogout(Long userId) {
if (userId == null) {
return;
}
try {
LoginLog entity = new LoginLog();
entity.setLogoutTime(LocalDateTime.now());
entity.setOnline(0);
// 仅关闭该用户最近一条尚未退出的会话
logMapper.update(entity, new QueryWrapper<LoginLog>()
.eq("user_id", userId)
.isNull("logout_time")
.orderByDesc("login_time")
.last("LIMIT 1"));
} catch (Exception e) {
log.warn("记录退出日志失败:{}", e.getMessage());
}
}
@Override
public PageResult<LoginLog> page(LoginLogQuery q) {
long current = q.getCurrent() == null ? 1L : q.getCurrent();
long size = q.getSize() == null ? 20L : q.getSize();
try {
QueryWrapper<LoginLog> w = new QueryWrapper<>();
if (StrUtil.isNotBlank(q.getKeyword())) {
String kw = q.getKeyword().trim();
w.and(x -> x.like("username", kw).or().like("real_name", kw).or().like("org_name", kw));
}
if ("ONLINE".equalsIgnoreCase(q.getStatus())) {
w.eq("online", 1).isNull("logout_time");
} else if ("OFFLINE".equalsIgnoreCase(q.getStatus())) {
w.isNotNull("logout_time");
}
if (StrUtil.isNotBlank(q.getLoginStart())) {
w.ge("login_time", q.getLoginStart().trim());
}
if (StrUtil.isNotBlank(q.getLoginEnd())) {
// 结束日期按当天 23:59:59 包含整日,避免漏掉结束日当天的记录
String end = q.getLoginEnd().trim();
if (end.length() == 10) {
end = end + " 23:59:59";
}
w.le("login_time", end);
}
w.orderByDesc("login_time");
Page<LoginLog> page = logMapper.selectPage(Page.of(current, size), w);
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
} catch (Exception e) {
// 表缺失等异常时降级为空结果,避免进入后台管理时整页报「操作失败」
log.warn("分页查询登录日志失败:{}", e.getMessage());
return PageResult.of(new ArrayList<>(), 0L, current, size);
}
}
@Override
public LoginLogSummary summary() {
LoginLogSummary s = new LoginLogSummary();
try {
s.setTotal(logMapper.selectCount(new QueryWrapper<>()));
s.setOnline(logMapper.selectCount(new QueryWrapper<LoginLog>().eq("online", 1).isNull("logout_time")));
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
s.setToday(logMapper.selectCount(new QueryWrapper<LoginLog>().ge("login_time", startOfToday)));
} catch (Exception e) {
log.warn("统计登录日志概览失败:{}", e.getMessage());
}
return s;
}
// ==================== 网络访问统计 ====================
@Override
public AccessOverview accessOverview() {
AccessOverview o = new AccessOverview();
try {
long[] history = countPair(null);
o.setHistoryCount(history[0]);
o.setHistoryUsers(history[1]);
long[] month = countPair(LocalDate.now().withDayOfMonth(1).atStartOfDay());
o.setMonthCount(month[0]);
o.setMonthUsers(month[1]);
long[] week = countPair(LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay());
o.setWeekCount(week[0]);
o.setWeekUsers(week[1]);
long[] today = countPair(LocalDate.now().atStartOfDay());
o.setTodayCount(today[0]);
o.setTodayUsers(today[1]);
} catch (Exception e) {
log.warn("统计网络访问概览失败:{}", e.getMessage());
}
return o;
}
@Override
public List<AccessTrendPoint> accessTrend(String granularity, String start, String end) {
String expr = granularityExpr(granularity);
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select(expr + " AS bucket", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
applyRange(w, start, end);
w.groupBy(expr).orderByAsc("bucket");
List<AccessTrendPoint> list = new ArrayList<>();
try {
for (Map<String, Object> m : logMapper.selectMaps(w)) {
Object b = m.get("bucket");
list.add(new AccessTrendPoint(b == null ? "" : b.toString(),
toLong(m.get("cnt")), toLong(m.get("users"))));
}
} catch (Exception e) {
log.warn("统计网络访问趋势失败:{}", e.getMessage());
}
return list;
}
@Override
public List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit) {
String col = "ip";
if ("org".equals(dimension)) {
col = "org_name";
} else if ("account".equals(dimension)) {
col = "username";
} else if ("type".equals(dimension)) {
col = "online";
}
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select(col + " AS name", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
// 字符串维度排除空值;type 维度(online 为整数)仅排除 NULL,避免 integer <> '' 报错
if ("type".equals(dimension)) {
w.isNotNull(col);
} else {
w.isNotNull(col).ne(col, "");
}
applyRange(w, start, end);
w.groupBy(col).orderByDesc("cnt").last("LIMIT " + Math.max(1, limit));
List<AccessDimensionItem> list = new ArrayList<>();
try {
for (Map<String, Object> m : logMapper.selectMaps(w)) {
Object raw = m.get("name");
String name = raw == null ? "未知" : raw.toString();
if ("type".equals(dimension)) {
name = "1".equals(name) ? "在线" : "0".equals(name) ? "离线" : name;
}
list.add(new AccessDimensionItem(name, toLong(m.get("cnt")), toLong(m.get("users"))));
}
} catch (Exception e) {
log.warn("统计网络访问维度失败:{}", e.getMessage());
}
return list;
}
/** 人次 + 去重人数(按给定起始时间)。 */
private long[] countPair(LocalDateTime ge) {
QueryWrapper<LoginLog> w = new QueryWrapper<>();
w.select("COUNT(*) AS c", "COUNT(DISTINCT user_id) AS u");
if (ge != null) {
w.ge("login_time", ge);
}
List<Map<String, Object>> maps = logMapper.selectMaps(w);
long c = 0, u = 0;
if (!maps.isEmpty()) {
Map<String, Object> m = maps.get(0);
c = toLong(m.get("c"));
u = toLong(m.get("u"));
}
return new long[]{c, u};
}
/** 时间分桶表达式(PostgreSQL)。 */
private String granularityExpr(String g) {
if ("day".equals(g)) {
return "to_char(login_time, 'YYYY-MM-DD')";
}
if ("week".equals(g)) {
return "to_char(date_trunc('week', login_time), 'YYYY-MM-DD')";
}
if ("month".equals(g)) {
return "to_char(login_time, 'YYYY-MM')";
}
if ("year".equals(g)) {
return "to_char(login_time, 'YYYY')";
}
// 默认按小时(含日期,避免跨天合并)
return "to_char(login_time, 'YYYY-MM-DD HH24')";
}
/** 时间区间条件:start 含当天 00:00,end 含当天 23:59:59。 */
private void applyRange(QueryWrapper<LoginLog> w, String start, String end) {
if (StrUtil.isNotBlank(start)) {
w.ge("login_time", start.trim());
}
if (StrUtil.isNotBlank(end)) {
String e = end.trim();
if (e.length() == 10) {
e = e + " 23:59:59";
}
w.le("login_time", e);
}
}
private long toLong(Object value) {
return value instanceof Number number ? number.longValue() : 0L;
}
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问维度统计项(按 IP / 单位 / 账号 / 类型)。
*/
@Data
@Schema(description = "网络访问维度统计项")
public class AccessDimensionItem {
@Schema(description = "维度值(IP / 单位 / 账号 / 在线状态)")
private String name;
@Schema(description = "访问人次")
private long count;
@Schema(description = "访问人数(去重)")
private long users;
public AccessDimensionItem() {
}
public AccessDimensionItem(String name, long count, long users) {
this.name = name;
this.count = count;
this.users = users;
}
}
@@ -0,0 +1,38 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问统计概览。
*
* <p>人次 = 登录会话记录数;人数 = 去重用户数(按 user_id)。</p>
*/
@Data
@Schema(description = "网络访问统计概览")
public class AccessOverview {
@Schema(description = "历史访问人次")
private long historyCount;
@Schema(description = "历史访问人数(去重)")
private long historyUsers;
@Schema(description = "本月访问人次")
private long monthCount;
@Schema(description = "本月访问人数(去重)")
private long monthUsers;
@Schema(description = "本周访问人次")
private long weekCount;
@Schema(description = "本周访问人数(去重)")
private long weekUsers;
@Schema(description = "今日访问人次")
private long todayCount;
@Schema(description = "今日访问人数(去重)")
private long todayUsers;
}
@@ -0,0 +1,30 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 网络访问趋势(按时间分桶)。
*/
@Data
@Schema(description = "网络访问趋势(按时间分桶)")
public class AccessTrendPoint {
@Schema(description = "时间桶,如 2026-11-04 08 / 2026-11 / 2026")
private String bucket;
@Schema(description = "访问人次")
private long count;
@Schema(description = "访问人数(去重)")
private long users;
public AccessTrendPoint() {
}
public AccessTrendPoint(String bucket, long count, long users) {
this.bucket = bucket;
this.count = count;
this.users = users;
}
}
@@ -0,0 +1,21 @@
package com.banben.modules.auth.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 登录日志概览统计。
*/
@Data
@Schema(description = "登录日志概览统计")
public class LoginLogSummary {
@Schema(description = "会话总数")
private long total;
@Schema(description = "当前在线人数(未退出的会话数)")
private long online;
@Schema(description = "今日登录次数")
private long today;
}
@@ -1,6 +1,7 @@
package com.banben.modules.collect.controller;
import com.banben.common.Result;
import com.banben.modules.collect.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.service.CollectService;
import io.swagger.v3.oas.annotations.Operation;
@@ -29,13 +30,32 @@ public class CollectController {
return Result.success(collectService.createTask(task));
}
@Operation(summary = "执行采集任务")
@PostMapping("/task/{id}/start")
public Result<Void> startTask(@PathVariable Long id) {
collectService.startTask(id);
@Operation(summary = "修改采集任务")
@PutMapping("/task/{id}")
public Result<Void> updateTask(@PathVariable Long id, @RequestBody CollectTask task) {
collectService.updateTask(id, task);
return Result.success();
}
@Operation(summary = "删除采集任务")
@DeleteMapping("/task/{id}")
public Result<Void> removeTask(@PathVariable Long id) {
collectService.removeTask(id);
return Result.success();
}
@Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表")
@PostMapping("/preview")
public Result<CollectTableVO> preview(@RequestBody CollectTask source) {
return Result.success(collectService.previewSource(source));
}
@Operation(summary = "执行采集任务:按来源表读取并写入版本资源表")
@PostMapping("/task/{id}/start")
public Result<CollectTask> startTask(@PathVariable Long id) {
return Result.success(collectService.startTask(id));
}
@Operation(summary = "采集任务列表")
@GetMapping("/tasks")
public Result<List<CollectTask>> tasks() {
@@ -0,0 +1,21 @@
package com.banben.modules.collect.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 来源表的一列,以及它会写入版本资源表的哪个字段。
*/
@Data
@Schema(description = "采集字段对应关系")
public class CollectColumnVO {
@Schema(description = "来源列名")
private String columnName;
@Schema(description = "写入 version_resource 的字段名,无法对应时为空")
private String targetField;
@Schema(description = "写入字段的中文名")
private String targetLabel;
}
@@ -0,0 +1,27 @@
package com.banben.modules.collect.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 版本资源表字段与来源列的对照。
*/
@Data
@Schema(description = "版本资源字段对照")
public class CollectFieldCompareVO {
@Schema(description = "version_resource 字段名")
private String targetField;
@Schema(description = "字段中文名")
private String targetLabel;
@Schema(description = "是否为必备字段")
private boolean required;
@Schema(description = "对应的来源列名,没有则为空")
private String sourceColumn;
@Schema(description = "来源表是否有列对应到该字段")
private boolean matched;
}
@@ -0,0 +1,27 @@
package com.banben.modules.collect.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 可采集的数据库表。
*/
@Data
@Schema(description = "可采集数据表")
public class CollectTableVO {
@Schema(description = "表名")
private String tableName;
@Schema(description = "当前行数")
private long rowCount;
@Schema(description = "列与版本资源字段的对应关系")
private List<CollectColumnVO> columns = new ArrayList<>();
@Schema(description = "版本资源表字段与来源列的对照")
private List<CollectFieldCompareVO> compares = new ArrayList<>();
}
@@ -6,6 +6,7 @@ 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 com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -20,7 +21,7 @@ import java.time.LocalDateTime;
@Schema(description = "数据采集任务")
public class CollectTask implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "单位编码")
@@ -32,6 +33,28 @@ public class CollectTask implements Serializable {
@Schema(description = "数据源类型:MARC/EXCEL/DB/API")
private String sourceType;
@Schema(description = "数据库地址,如 10.1.1.14")
private String dbHost;
@Schema(description = "来源数据库类型:MYSQL 或 POSTGRESQL(瀚高走 PostgreSQL 协议)")
private String dbType;
@Schema(description = "数据库端口。MySQL 常用 3306,PostgreSQL 常用 5432,瀚高常用 5866")
private Integer dbPort;
@Schema(description = "数据库名")
private String dbName;
@Schema(description = "数据库用户名")
private String dbUsername;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Schema(description = "数据库密码,只用于连接,接口不回传")
private String dbPassword;
@Schema(description = "要采集的表名,可写 schema.table")
private String sourceTable;
@Schema(description = "目标采集量")
private Integer targetCount;
@@ -1,6 +1,7 @@
package com.banben.modules.collect.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.collect.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask;
import java.util.List;
@@ -16,9 +17,24 @@ public interface CollectService extends IService<CollectTask> {
Long createTask(CollectTask task);
/**
* 执行采集任务(异步)。
* 修改采集任务的连接信息。密码留空则保持原密码。
*/
void startTask(Long taskId);
void updateTask(Long id, CollectTask task);
/**
* 删除采集任务。
*/
void removeTask(Long id);
/**
* 执行采集任务,返回执行后的任务(含采集条数和结果说明)。
*/
CollectTask startTask(Long taskId);
/**
* 按填写的地址、账号和表名连接来源库,返回行数和字段对应关系。
*/
CollectTableVO previewSource(CollectTask source);
/**
* 查询任务列表。
@@ -3,6 +3,7 @@ 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.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.mapper.CollectTaskMapper;
import com.banben.modules.collect.service.CollectService;
@@ -37,16 +38,19 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
/** 数据源类型 → 采集适配器 的映射(key 统一大写)。 */
private final Map<String, Collector> collectorMap;
private final DbTableCollector dbTableCollector;
/**
* 构造注入所有 Collector 实现。
* 若当前没有任何实现类,Spring 注入空集合,运行时会提示「未找到适配器」并跳过实际采集。
*/
public CollectServiceImpl(List<Collector> collectors) {
public CollectServiceImpl(List<Collector> collectors, DbTableCollector dbTableCollector) {
this.dbTableCollector = dbTableCollector;
this.collectorMap = collectors.stream()
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
}
/** 创建任务:初始状态 PENDING、已采集量 0,目标量缺省为 20 万条。 */
/** 创建任务:初始状态 PENDING、已采集量 0。来源表至少要有一列能写入版本资源表。 */
@Override
public Long createTask(CollectTask task) {
task.setId(null);
@@ -55,12 +59,80 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
if (task.getTargetCount() == null) {
task.setTargetCount(200000);
}
ensureMapped(task);
this.save(task);
return task.getId();
}
@Override
public void startTask(Long taskId) {
public void updateTask(Long id, CollectTask task) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能修改");
}
stored.setLibraryCode(task.getLibraryCode());
stored.setLibraryName(task.getLibraryName());
stored.setSourceType(task.getSourceType() == null ? "DB" : task.getSourceType());
stored.setDbHost(task.getDbHost());
stored.setDbType(task.getDbType());
stored.setDbPort(task.getDbPort());
stored.setDbName(task.getDbName());
stored.setDbUsername(task.getDbUsername());
stored.setSourceTable(task.getSourceTable());
if (task.getDbPassword() != null && !task.getDbPassword().isBlank()) {
stored.setDbPassword(task.getDbPassword());
}
ensureMapped(stored);
this.updateById(stored);
}
@Override
public void removeTask(Long id) {
CollectTask stored = requireTask(id);
if ("RUNNING".equals(stored.getStatus())) {
throw new BusinessException("任务正在执行,不能删除");
}
this.removeById(id);
}
@Override
public CollectTableVO previewSource(CollectTask source) {
fillPassword(source);
return dbTableCollector.preview(source);
}
private CollectTask requireTask(Long id) {
CollectTask stored = this.getById(id);
if (stored == null) {
throw new BusinessException("采集任务不存在");
}
return stored;
}
/** 编辑时密码留空,沿用已保存的密码再去测试连接。 */
private void fillPassword(CollectTask source) {
if (source.getDbPassword() != null && !source.getDbPassword().isBlank()) {
return;
}
if (source.getId() == null) {
return;
}
CollectTask stored = this.getById(source.getId());
if (stored != null) {
source.setDbPassword(stored.getDbPassword());
}
}
private void ensureMapped(CollectTask task) {
CollectTableVO preview = previewSource(task);
boolean matched = preview.getColumns().stream().anyMatch(column -> column.getTargetField() != null);
if (!matched) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表");
}
}
@Override
public CollectTask startTask(Long taskId) {
CollectTask task = this.getById(taskId);
if (task == null) {
throw new BusinessException("采集任务不存在");
@@ -78,22 +150,24 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
Collector collector = collectorMap.get(sourceType);
int count;
if (collector == null) {
log.warn("未找到数据源类型 [{}] 的采集适配器,任务 {} 跳过实际采集", sourceType, taskId);
count = 0;
} else {
count = collector.collect(task);
throw new BusinessException("未找到数据源类型 " + sourceType + " 的采集适配器");
}
count = collector.collect(task);
task.setCollectedCount(count);
task.setStatus("SUCCESS");
task.setMessage("采集完成");
if (task.getMessage() == null || task.getMessage().isBlank()) {
task.setMessage("采集完成,写入 " + count + " 条");
}
} catch (Exception e) {
log.error("采集任务执行失败: {}", e.getMessage(), e);
task.setStatus("FAILED");
task.setCollectedCount(0);
task.setMessage(e.getMessage());
} finally {
task.setEndTime(LocalDateTime.now());
this.updateById(task);
}
return task;
}
@Override
@@ -0,0 +1,528 @@
package com.banben.modules.collect.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
import com.banben.modules.collect.dto.CollectColumnVO;
import com.banben.modules.collect.dto.CollectFieldCompareVO;
import com.banben.modules.collect.dto.CollectTableVO;
import com.banben.modules.collect.entity.CollectTask;
import com.banben.modules.collect.service.Collector;
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 org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.BiConsumer;
/**
* 从当前数据库的指定表采集记录,按版本资源表的字段写入 {@code version_resource}。
*
* <p>列名与版本资源字段一致时直接填入;书名、作者、出版社等常见别名也会识别。
* 对不上的列不写入。治理状态统一记为原始数据。</p>
*/
@Component
@RequiredArgsConstructor
public class DbTableCollector implements Collector {
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final int MAX_ROWS = 200000;
/** 写入 version_resource 时建议具备的字段。正题名未对应则该行无法入库。 */
private static final List<String> REQUIRED_FIELDS = List.of(
"title", "processNo", "clcCode", "keywords", "summary", "publishYear", "processDate",
"contentForm", "mediaType", "format", "language", "fulltextUrl"
);
private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>();
private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>();
private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>();
static {
label("processNo", "加工编号");
label("title", "正题名");
label("clcCode", "中图分类号");
label("keywords", "主题词或关键词");
label("summary", "摘要");
label("publishYear", "出版年份");
label("processDate", "加工日期");
label("contentForm", "内容形式");
label("mediaType", "媒体类型");
label("format", "格式");
label("pageCount", "页码");
label("language", "语种");
label("submitOrg", "数据提交单位");
label("taskYear", "所属任务年份");
label("sourceLibrary", "来源馆");
label("sourceLibraryAddr", "来源馆地址");
label("fulltextUrl", "全文地址");
label("otherTitle", "其他题名");
label("author", "责任者");
label("responsibility", "责任方式");
label("note", "附注");
label("publisher", "出版者");
label("publishPlace", "出版地");
label("publishDate", "出版日期");
label("edition", "版本");
label("isbn", "ISBN");
label("unifiedBookNo", "统一书号");
label("cdoi", "CDOI");
label("publishUrl", "发布地址");
alias("processNo", "process_no", "processno", "加工编号");
alias("title", "title", "name", "book_name", "bookname", "resource_title", "题名", "正题名", "书名");
alias("clcCode", "clc_code", "clccode", "clc", "class_no", "classno", "分类号", "中图分类号");
alias("keywords", "keywords", "keyword", "subject", "关键词", "主题词");
alias("summary", "summary", "abstract", "intro", "摘要", "简介");
alias("publishYear", "publish_year", "publishyear", "pub_year", "pubyear", "出版年", "出版年份");
alias("processDate", "process_date", "processdate", "加工日期");
alias("contentForm", "content_form", "contentform", "内容形式");
alias("mediaType", "media_type", "mediatype", "媒体类型", "资源类型");
alias("format", "format", "格式");
alias("pageCount", "page_count", "pagecount", "pages", "页码", "页数");
alias("language", "language", "lang", "语种");
alias("submitOrg", "submit_org", "submitorg", "org_name", "orgname", "数据提交单位", "提交单位");
alias("taskYear", "task_year", "taskyear", "所属任务年份", "任务年份");
alias("sourceLibrary", "source_library", "sourcelibrary", "library_name", "libraryname", "来源馆", "馆藏单位");
alias("sourceLibraryAddr", "source_library_addr", "sourcelibraryaddr", "来源馆地址");
alias("fulltextUrl", "fulltext_url", "fulltexturl", "file_url", "fileurl", "ebook_url", "ebookurl", "全文地址");
alias("otherTitle", "other_title", "othertitle", "其他题名");
alias("author", "author", "writer", "作者", "责任者");
alias("responsibility", "responsibility", "责任方式");
alias("note", "note", "remark", "附注", "备注");
alias("publisher", "publisher", "press", "出版者", "出版社");
alias("publishPlace", "publish_place", "publishplace", "出版地");
alias("publishDate", "publish_date", "publishdate", "出版日期");
alias("edition", "edition", "版本", "版次");
alias("isbn", "isbn");
alias("unifiedBookNo", "unified_book_no", "unifiedbookno", "统一书号");
alias("cdoi", "cdoi");
alias("publishUrl", "publish_url", "publishurl", "发布地址");
setter("processNo", VersionResource::setProcessNo, 128);
setter("title", VersionResource::setTitle, 512);
setter("clcCode", VersionResource::setClcCode, 64);
setter("keywords", VersionResource::setKeywords, 512);
setter("summary", VersionResource::setSummary, 0);
setter("publishYear", VersionResource::setPublishYear, 8);
setter("processDate", VersionResource::setProcessDate, 16);
setter("contentForm", VersionResource::setContentForm, 64);
setter("mediaType", VersionResource::setMediaType, 32);
setter("format", VersionResource::setFormat, 64);
setter("pageCount", VersionResource::setPageCount, 64);
setter("language", VersionResource::setLanguage, 16);
setter("submitOrg", VersionResource::setSubmitOrg, 256);
setter("taskYear", VersionResource::setTaskYear, 8);
setter("sourceLibrary", VersionResource::setSourceLibrary, 256);
setter("sourceLibraryAddr", VersionResource::setSourceLibraryAddr, 256);
setter("fulltextUrl", VersionResource::setFulltextUrl, 1024);
setter("otherTitle", VersionResource::setOtherTitle, 512);
setter("author", VersionResource::setAuthor, 512);
setter("responsibility", VersionResource::setResponsibility, 256);
setter("note", VersionResource::setNote, 0);
setter("publisher", VersionResource::setPublisher, 256);
setter("publishPlace", VersionResource::setPublishPlace, 128);
setter("publishDate", VersionResource::setPublishDate, 32);
setter("edition", VersionResource::setEdition, 128);
setter("isbn", VersionResource::setIsbn, 64);
setter("unifiedBookNo", VersionResource::setUnifiedBookNo, 64);
setter("cdoi", VersionResource::setCdoi, 256);
setter("publishUrl", VersionResource::setPublishUrl, 1024);
}
private final VersionResourceMapper resourceMapper;
@Override
public String sourceType() {
return "DB";
}
/**
* 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。
*/
public CollectTableVO preview(CollectTask task) {
String[] qualified = qualify(task);
try (Connection connection = openConnection(task)) {
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
CollectTableVO table = new CollectTableVO();
table.setTableName(qualified[0] + "." + qualified[1]);
table.setRowCount(countRows(connection, qualified[0], qualified[1], mysql(task)));
table.setColumns(readColumns(connection, qualified[0], qualified[1]));
table.setCompares(buildCompares(table.getColumns()));
return table;
} catch (SQLException e) {
throw new BusinessException(sqlMessage(e));
}
}
@Override
public int collect(CollectTask task) {
String[] qualified = qualify(task);
int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS);
List<Map<String, Object>> rows;
try (Connection connection = openConnection(task)) {
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
List<CollectColumnVO> columns = readColumns(connection, qualified[0], qualified[1]);
if (columns.stream().noneMatch(column -> column.getTargetField() != null)) {
throw new BusinessException("来源表至少要有一列能对应到版本资源表,无法写入");
}
rows = readRows(connection, qualified[0], qualified[1], limit, mysql(task));
} catch (SQLException e) {
throw new BusinessException(sqlMessage(e));
}
String table = qualified[1];
Set<String> existing = loadProcessNos();
int inserted = 0;
int duplicated = 0;
int missingTitle = 0;
int sequence = 0;
String today = LocalDate.now().format(DAY);
String year = String.valueOf(LocalDate.now().getYear());
for (Map<String, Object> row : rows) {
VersionResource resource = new VersionResource();
for (Map.Entry<String, Object> entry : row.entrySet()) {
String field = FIELD_BY_COLUMN.get(normalize(entry.getKey()));
if (field == null || entry.getValue() == null) {
continue;
}
String value = stringify(entry.getValue());
if (value.isEmpty()) {
continue;
}
SETTERS.get(field).accept(resource, value);
}
if (blank(resource.getTitle())) {
missingTitle++;
continue;
}
if (blank(resource.getProcessNo())) {
Object sourceId = first(row, "id");
sequence++;
String suffix = sourceId == null ? String.valueOf(sequence) : stringify(sourceId);
String prefix = blank(task.getLibraryCode()) ? "DB" : task.getLibraryCode().trim();
resource.setProcessNo(truncate(prefix + "-" + table + "-" + suffix, 128));
}
if (existing.contains(resource.getProcessNo())) {
duplicated++;
continue;
}
if (blank(resource.getSourceLibrary())) {
resource.setSourceLibrary(truncate(task.getLibraryName(), 256));
}
if (blank(resource.getSubmitOrg())) {
resource.setSubmitOrg(truncate(blank(task.getLibraryName()) ? resource.getSourceLibrary() : task.getLibraryName(), 256));
}
if (blank(resource.getTaskYear())) {
resource.setTaskYear(year);
}
if (blank(resource.getProcessDate())) {
resource.setProcessDate(today);
}
resource.setGovernStatus(GovernStatus.RAW.getCode());
resource.setAbnormalFlag(0);
resource.setSensitiveFlag(0);
resource.setIsSpecial(0);
resource.setManageStatus(0);
resource.setDeleted(0);
resourceMapper.insert(resource);
existing.add(resource.getProcessNo());
inserted++;
}
task.setMessage(String.format(
"已从 %s:%s/%s 的表 %s.%s 读取 %d 条,按版本资源字段写入 %d 条,跳过重复 %d 条,缺少正题名 %d 条",
task.getDbHost(), task.getDbPort(), task.getDbName(), qualified[0], qualified[1],
rows.size(), inserted, duplicated, missingTitle));
return inserted;
}
private Connection openConnection(CollectTask task) {
if (blank(task.getDbHost()) || !task.getDbHost().trim().matches("[A-Za-z0-9._-]+")) {
throw new BusinessException("请填写合法的数据库地址");
}
int port = task.getDbPort() == null ? 5432 : task.getDbPort();
if (port < 1 || port > 65535) {
throw new BusinessException("数据库端口应在 1 到 65535 之间");
}
if (blank(task.getDbName()) || !task.getDbName().trim().matches("[A-Za-z0-9_]+")) {
throw new BusinessException("请填写合法的数据库名");
}
if (blank(task.getDbUsername())) {
throw new BusinessException("请填写数据库用户名");
}
if (blank(task.getDbPassword())) {
throw new BusinessException("请填写数据库密码");
}
String url = mysql(task)
? "jdbc:mysql://" + task.getDbHost().trim() + ":" + port + "/" + task.getDbName().trim()
+ "?connectTimeout=8000&socketTimeout=30000&useSSL=false&allowPublicKeyRetrieval=true"
+ "&characterEncoding=utf8&serverTimezone=Asia/Shanghai"
: "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
+ task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30";
Properties properties = new Properties();
properties.setProperty("user", task.getDbUsername().trim());
properties.setProperty("password", task.getDbPassword());
try {
return DriverManager.getConnection(url, properties);
} catch (SQLException e) {
throw new BusinessException(sqlMessage(e));
}
}
/**
* 按页面选择的数据库类型决定驱动。未填写类型的旧任务仍按 3306 识别为 MySQL。
*/
private boolean mysql(CollectTask task) {
String type = task.getDbType() == null ? "" : task.getDbType().trim().toUpperCase(Locale.ROOT);
if ("MYSQL".equals(type)) {
return true;
}
if ("POSTGRESQL".equals(type) || "HIGHGO".equals(type)) {
return false;
}
if (type.isEmpty()) {
return task.getDbPort() != null && task.getDbPort() == 3306;
}
throw new BusinessException("数据库类型只支持 MySQL 或 PostgreSQL");
}
private String[] qualify(CollectTask task) {
if (blank(task.getSourceTable())) {
throw new BusinessException("请填写要采集的表名");
}
String[] parts = task.getSourceTable().trim().split("\\.");
if (parts.length > 2) {
throw new BusinessException("表名格式应为表名,或模式名.表名");
}
boolean mysql = mysql(task);
String schema = parts.length == 2 ? parts[0] : (mysql ? task.getDbName().trim() : "public");
String table = parts.length == 2 ? parts[1] : parts[0];
if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) {
throw new BusinessException("表名只能包含字母、数字和下划线");
}
if (!mysql) {
schema = schema.toLowerCase(Locale.ROOT);
table = table.toLowerCase(Locale.ROOT);
}
return new String[]{schema, table};
}
private String canonicalTable(Connection connection, String schema, String table, boolean mysql) throws SQLException {
String sql = mysql
? """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND LOWER(table_name) = LOWER(?)
"""
: """
SELECT table_name FROM information_schema.tables
WHERE table_schema = ? AND table_name = ?
""";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, schema);
statement.setString(2, table);
try (ResultSet resultSet = statement.executeQuery()) {
String found = null;
while (resultSet.next()) {
String name = resultSet.getString(1);
if (name.equals(table)) {
return name;
}
found = name;
}
if (found == null) {
throw new BusinessException("来源库中不存在表:" + schema + "." + table);
}
return found;
}
}
}
private long countRows(Connection connection, String schema, String table, boolean mysql) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"SELECT COUNT(*) FROM " + quote(schema, mysql) + "." + quote(table, mysql));
ResultSet resultSet = statement.executeQuery()) {
resultSet.next();
return resultSet.getLong(1);
}
}
private String quote(String identifier, boolean mysql) {
return mysql ? "`" + identifier + "`" : "\"" + identifier + "\"";
}
private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException {
List<CollectColumnVO> columns = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement("""
SELECT column_name FROM information_schema.columns
WHERE table_schema = ? AND table_name = ?
ORDER BY ordinal_position
""")) {
statement.setString(1, schema);
statement.setString(2, table);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
String columnName = resultSet.getString(1);
CollectColumnVO item = new CollectColumnVO();
item.setColumnName(columnName);
String field = FIELD_BY_COLUMN.get(normalize(columnName));
item.setTargetField(field);
item.setTargetLabel(field == null ? null : FIELD_LABEL.get(field));
columns.add(item);
}
}
}
return columns;
}
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit,
boolean mysql) throws SQLException {
List<Map<String, Object>> rows = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM " + quote(schema, mysql) + "." + quote(table, mysql) + " LIMIT " + limit);
ResultSet resultSet = statement.executeQuery()) {
ResultSetMetaData meta = resultSet.getMetaData();
while (resultSet.next()) {
Map<String, Object> row = new LinkedHashMap<>();
for (int i = 1; i <= meta.getColumnCount(); i++) {
row.put(meta.getColumnLabel(i), resultSet.getObject(i));
}
rows.add(row);
}
}
return rows;
}
private String sqlMessage(SQLException exception) {
String message = exception.getMessage() == null ? "" : exception.getMessage();
String lower = message.toLowerCase(Locale.ROOT);
if (lower.contains("password authentication failed") || lower.contains("authentication failed")
|| lower.contains("access denied")) {
return "数据库用户名或密码错误";
}
if ((lower.contains("does not exist") && lower.contains("database")) || lower.contains("unknown database")) {
return "数据库不存在";
}
if (lower.contains("connection refused") || lower.contains("communications link failure")) {
return "连接被拒绝,请检查数据库地址和端口";
}
if (lower.contains("timeout") || lower.contains("timed out")) {
return "连接超时,请检查数据库地址和端口";
}
String brief = message.replaceAll("\\s+", " ").trim();
if (brief.length() > 180) {
brief = brief.substring(0, 180);
}
return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief;
}
private List<CollectFieldCompareVO> buildCompares(List<CollectColumnVO> columns) {
Map<String, String> sourceByField = new LinkedHashMap<>();
for (CollectColumnVO column : columns) {
if (column.getTargetField() != null) {
sourceByField.putIfAbsent(column.getTargetField(), column.getColumnName());
}
}
List<CollectFieldCompareVO> compares = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (String field : REQUIRED_FIELDS) {
compares.add(compareItem(field, true, sourceByField));
seen.add(field);
}
for (String field : FIELD_LABEL.keySet()) {
if (!seen.contains(field)) {
compares.add(compareItem(field, false, sourceByField));
}
}
return compares;
}
private CollectFieldCompareVO compareItem(String field, boolean required, Map<String, String> sourceByField) {
CollectFieldCompareVO item = new CollectFieldCompareVO();
item.setTargetField(field);
item.setTargetLabel(FIELD_LABEL.get(field));
item.setRequired(required);
item.setSourceColumn(sourceByField.get(field));
item.setMatched(item.getSourceColumn() != null);
return item;
}
private Set<String> loadProcessNos() {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo);
Set<String> nos = new HashSet<>();
for (VersionResource resource : resourceMapper.selectList(query)) {
if (!blank(resource.getProcessNo())) {
nos.add(resource.getProcessNo());
}
}
return nos;
}
private static void label(String field, String text) {
FIELD_LABEL.put(field, text);
}
private static void alias(String field, String... names) {
for (String name : names) {
FIELD_BY_COLUMN.put(normalize(name), field);
}
}
private static void setter(String field, BiConsumer<VersionResource, String> setter, int maxLength) {
SETTERS.put(field, (resource, value) -> setter.accept(resource, maxLength > 0 ? truncate(value, maxLength) : value));
}
private static String normalize(String name) {
if (name == null) {
return "";
}
return name.trim().toLowerCase(Locale.ROOT).replace("_", "").replace("-", "");
}
private static Object first(Map<String, Object> row, String key) {
for (Map.Entry<String, Object> entry : row.entrySet()) {
if (key.equalsIgnoreCase(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
private static String stringify(Object value) {
return value == null ? "" : String.valueOf(value).trim();
}
private static String truncate(String value, int maxLength) {
if (value == null) {
return null;
}
String text = value.trim();
if (text.isEmpty()) {
return null;
}
return text.length() <= maxLength ? text : text.substring(0, maxLength);
}
private static boolean blank(String value) {
return value == null || value.trim().isEmpty();
}
}
@@ -1,7 +1,10 @@
package com.banben.modules.deposit.controller;
import com.banben.common.BusinessException;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.auth.context.UserContext;
import com.banben.modules.auth.context.LoginUser;
import com.banben.modules.deposit.dto.DepositQuery;
import com.banben.modules.deposit.entity.DepositRecord;
import com.banben.modules.deposit.service.DepositService;
@@ -30,31 +33,43 @@ public class DepositController {
return Result.success(depositService.submit(record));
}
@Operation(summary = "管理端查看呈缴列表")
@Operation(summary = "管理端查看呈缴列表(仅管理员)")
@GetMapping("/page")
public Result<PageResult<DepositRecord>> page(DepositQuery query) {
requireAdmin();
return Result.success(depositService.pageQuery(query));
}
@Operation(summary = "管理端查看呈缴详情")
@Operation(summary = "管理端查看呈缴详情(仅管理员)")
@GetMapping("/{id}")
public Result<DepositRecord> detail(@PathVariable Long id) {
requireAdmin();
return Result.success(depositService.getById(id));
}
@Operation(summary = "管理端接收呈缴")
@Operation(summary = "管理端接收呈缴(仅管理员)")
@PostMapping("/{id}/accept")
public Result<Void> accept(@PathVariable Long id,
@RequestParam(required = false) String auditRemark) {
requireAdmin();
depositService.audit(id, true, auditRemark);
return Result.success();
}
@Operation(summary = "管理端退回呈缴")
@Operation(summary = "管理端退回呈缴(仅管理员)")
@PostMapping("/{id}/reject")
public Result<Void> reject(@PathVariable Long id,
@RequestParam(required = false) String auditRemark) {
requireAdmin();
depositService.audit(id, false, auditRemark);
return Result.success();
}
/** 管理端接口统一校验:仅管理员可访问(提交呈缴不受限) */
private void requireAdmin() {
LoginUser user = UserContext.get();
if (user == null || !"ADMIN".equalsIgnoreCase(user.role())) {
throw new BusinessException("仅管理员可执行该操作");
}
}
}
@@ -21,7 +21,7 @@ import java.time.LocalDateTime;
@Schema(description = "版本资源呈缴记录")
public class DepositRecord implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
private Long id;
@NotBlank(message = "呈缴单位名称不能为空")
@@ -1,19 +1,29 @@
package com.banben.modules.governance.controller;
import com.banben.common.Result;
import com.banben.modules.governance.dto.GovernanceHintVO;
import com.banben.modules.governance.entity.GovernanceJob;
import com.banben.modules.governance.service.GovernanceService;
import com.banben.modules.resource.entity.VersionResource;
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 org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 数据治理接口。
*
* <p>对应「数据治理」四动作:聚同、优化、提示、提纯。</p>
* <p>对应「数据治理」:聚同、优化、提示、提纯。</p>
* <ul>
* <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li>
* <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li>
* <li>提纯:将相关纸电图书数据从全部图书数据中提取出来,形成版本资源数据集。</li>
* </ul>
*/
@Tag(name = "数据治理", description = "聚同 / 优化 / 提示 / 提纯")
@RestController
@@ -29,22 +39,34 @@ public class GovernanceController {
return Result.success(governanceService.runJob("MERGE"));
}
@Operation(summary = "优化:整合优化元数据描述")
@Operation(summary = "优化:整合聚同文献的不同描述,生成更完整的元数据")
@PostMapping("/optimize")
public Result<GovernanceJob> optimize() {
return Result.success(governanceService.runJob("OPTIMIZE"));
return Result.success(governanceService.optimize());
}
@Operation(summary = "提示:生成疑似同一文献/错漏提示清单")
@Operation(summary = "提示:生成疑似同一文献清单与疑似元数据错漏清单")
@PostMapping("/hint")
public Result<GovernanceJob> hint() {
return Result.success(governanceService.runJob("HINT"));
public Result<GovernanceHintVO> hint() {
return Result.success(governanceService.hint());
}
@Operation(summary = "提纯:提取版本资源数据集")
@Operation(summary = "查看当前疑似同一文献清单与错漏清单")
@GetMapping("/hints")
public Result<GovernanceHintVO> hints() {
return Result.success(governanceService.previewHints());
}
@Operation(summary = "提纯:从全部图书数据中提取纸电图书,形成版本资源数据集")
@PostMapping("/purify")
public Result<GovernanceJob> purify() {
return Result.success(governanceService.runJob("PURIFY"));
return Result.success(governanceService.purify());
}
@Operation(summary = "版本资源数据集(已提纯的纸电图书)")
@GetMapping("/dataset")
public Result<List<VersionResource>> dataset() {
return Result.success(governanceService.listDataset());
}
@Operation(summary = "治理任务历史")
@@ -0,0 +1,36 @@
package com.banben.modules.governance.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 疑似元数据错漏清单中的一条资源。
*/
@Data
@Schema(description = "疑似元数据错漏条目")
public class DefectItemVO {
@Schema(description = "资源ID")
private Long id;
@Schema(description = "加工编号")
private String processNo;
@Schema(description = "正题名")
private String title;
@Schema(description = "责任者")
private String author;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "媒体类型")
private String mediaType;
@Schema(description = "错漏说明")
private List<String> issues = new ArrayList<>();
}
@@ -0,0 +1,24 @@
package com.banben.modules.governance.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 一组疑似同一文献。
*/
@Data
@Schema(description = "疑似同一文献分组")
public class DuplicateGroupVO {
@Schema(description = "判定原因")
private String reason;
@Schema(description = "分组依据,如 ISBN 或归一题名")
private String matchKey;
@Schema(description = "组内记录")
private List<DuplicateItemVO> records = new ArrayList<>();
}
@@ -0,0 +1,42 @@
package com.banben.modules.governance.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 疑似同一文献清单中的一条资源。
*/
@Data
@Schema(description = "疑似同一文献条目")
public class DuplicateItemVO {
@Schema(description = "资源ID")
private Long id;
@Schema(description = "加工编号")
private String processNo;
@Schema(description = "正题名")
private String title;
@Schema(description = "责任者")
private String author;
@Schema(description = "出版者")
private String publisher;
@Schema(description = "出版年份")
private String publishYear;
@Schema(description = "ISBN")
private String isbn;
@Schema(description = "媒体类型")
private String mediaType;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "治理状态")
private String governStatus;
}
@@ -0,0 +1,31 @@
package com.banben.modules.governance.dto;
import com.banben.modules.governance.entity.GovernanceJob;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 提示动作的两份清单。
*/
@Data
@Schema(description = "治理提示清单")
public class GovernanceHintVO {
@Schema(description = "本次任务;预览时为空")
private GovernanceJob job;
@Schema(description = "疑似同一文献组数")
private int duplicateGroupCount;
@Schema(description = "疑似错漏条数")
private int defectCount;
@Schema(description = "疑似同一文献提示清单")
private List<DuplicateGroupVO> duplicateGroups = new ArrayList<>();
@Schema(description = "疑似元数据错漏提示清单")
private List<DefectItemVO> defects = new ArrayList<>();
}
@@ -20,7 +20,7 @@ import java.time.LocalDateTime;
@Schema(description = "数据治理任务")
public class GovernanceJob implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "治理类型:MERGE聚同 / OPTIMIZE优化 / HINT提示 / PURIFY提纯")
@@ -1,7 +1,9 @@
package com.banben.modules.governance.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.banben.modules.governance.dto.GovernanceHintVO;
import com.banben.modules.governance.entity.GovernanceJob;
import com.banben.modules.resource.entity.VersionResource;
import java.util.List;
@@ -17,6 +19,31 @@ public interface GovernanceService extends IService<GovernanceJob> {
*/
GovernanceJob runJob(String jobType);
/**
* 优化:整合已聚同文献的不同描述,生成更完整的元数据。
*/
GovernanceJob optimize();
/**
* 提示:生成疑似同一文献清单、疑似元数据错漏清单,并标记错漏记录。
*/
GovernanceHintVO hint();
/**
* 按当前数据预览两份提示清单,不写任务、不改标记。
*/
GovernanceHintVO previewHints();
/**
* 提纯:从全部图书数据中提取纸电图书,形成版本资源数据集。
*/
GovernanceJob purify();
/**
* 已纳入版本资源数据集的记录(治理状态为已提纯)。
*/
List<VersionResource> listDataset();
/**
* 治理任务历史。
*/
@@ -0,0 +1,74 @@
package com.banben.modules.resource.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.banben.common.Result;
import com.banben.modules.resource.entity.ResourceSource;
import com.banben.modules.resource.mapper.ResourceSourceMapper;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 版本资源多来源管理接口。
*
* <p>对应检索概览页「一条结果可有多个来源,点击可下载」的能力:
* 一条文献可挂载到多个资源库 / 来源馆,概览页据此渲染多个来源并分别下载。</p>
*/
@Tag(name = "版本资源-多来源管理", description = "文献多来源(资源库)的增删改查")
@RestController
@RequestMapping("/api/resource")
@RequiredArgsConstructor
public class ResourceSourceController {
private final ResourceSourceMapper sourceMapper;
private final VersionResourceMapper resourceMapper;
@Operation(summary = "查询某条文献的全部来源(按展示顺序)")
@GetMapping("/{id}/sources")
public Result<List<ResourceSource>> list(@PathVariable Long id) {
QueryWrapper<ResourceSource> w = new QueryWrapper<>();
w.eq("resource_id", id).eq("deleted", 0).orderByAsc("sort_no");
return Result.success(sourceMapper.selectList(w));
}
@Operation(summary = "为某条文献新增一个来源")
@PostMapping("/{id}/sources")
public Result<Long> add(@PathVariable Long id, @RequestBody ResourceSource source) {
VersionResource r = resourceMapper.selectById(id);
if (r == null) {
return Result.failed("文献不存在:" + id);
}
source.setId(null);
source.setResourceId(id);
sourceMapper.insert(source);
return Result.success(source.getId());
}
@Operation(summary = "更新某个来源")
@PutMapping("/sources/{sourceId}")
public Result<Void> update(@PathVariable Long sourceId, @RequestBody ResourceSource source) {
source.setId(sourceId);
source.setResourceId(null); // 不允许跨文献改归属
sourceMapper.updateById(source);
return Result.success();
}
@Operation(summary = "删除某个来源(逻辑删除)")
@DeleteMapping("/sources/{sourceId}")
public Result<Void> remove(@PathVariable Long sourceId) {
sourceMapper.deleteById(sourceId);
return Result.success();
}
}
@@ -2,14 +2,22 @@ package com.banben.modules.resource.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.resource.dto.ImportResult;
import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.service.VersionResourceExcelService;
import com.banben.modules.resource.service.VersionResourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 版本资源元数据管理接口。
@@ -48,6 +56,24 @@ import org.springframework.web.bind.annotation.*;
public class VersionResourceController {
private final VersionResourceService versionResourceService;
private final VersionResourceExcelService excelService;
@Operation(summary = "下载 Excel 导入模板")
@GetMapping("/template")
public void downloadTemplate(HttpServletResponse response) throws IOException {
String fileName = URLEncoder.encode("版本资源导入模板.xlsx", StandardCharsets.UTF_8);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
excelService.writeTemplate(response.getOutputStream());
}
@Operation(summary = "Excel 导入版本资源")
@PostMapping("/import")
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
return Result.success(excelService.importExcel(file));
}
@Operation(summary = "分页查询版本资源")
@GetMapping("/page")
@@ -73,4 +99,11 @@ public class VersionResourceController {
versionResourceService.removeById(id);
return Result.success();
}
@Operation(summary = "设置是否特藏版本(0否 1是)")
@PutMapping("/{id}/special")
public Result<Void> updateSpecialFlag(@PathVariable Long id, @RequestParam Integer isSpecial) {
versionResourceService.updateSpecialFlag(id, isSpecial);
return Result.success();
}
}
@@ -0,0 +1,41 @@
package com.banben.modules.resource.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Excel 导入结果。
*
* <p>导入不会因为个别行出错而整体失败:能入库的照常入库,
* 失败的行记录行号与原因,前端一次性提示给用户。</p>
*/
@Data
public class ImportResult {
/** 解析到的有效数据行数 */
private int total;
/** 新增成功条数 */
private int inserted;
/** 按加工编号匹配到已有记录并更新的条数 */
private int updated;
/** 失败条数 */
private int failed;
/** 跳过的模板示例行数 */
private int skipped;
/** 失败明细,格式如「第 5 行:正题名不能为空」 */
private List<String> errors = new ArrayList<>();
public void addError(int excelRowNum, String reason) {
if (errors.size() < 50) {
errors.add("第 " + excelRowNum + " 行:" + reason);
}
failed++;
}
}
@@ -0,0 +1,66 @@
package com.banben.modules.resource.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;
/**
* 版本资源多来源(一条文献可来自多个资源库 / 来源馆)。
*
* <p>对应招标文件检索结果概览页要求:「一条结果可有多个来源,按资源库图标+名称展示,点击可下载」。
* 主表 {@link VersionResource} 上的 source_library / source_repo / fulltext_url 等字段作为
* 「主来源」兜底;本表保存该文献的全部来源,概览页据此渲染多个可分别下载的来源。</p>
*/
@Data
@TableName("resource_source")
@Schema(description = "版本资源多来源")
public class ResourceSource implements Serializable {
@TableId(type = IdType.AUTO)
@Schema(description = "来源记录主键")
private Long id;
@Schema(description = "关联版本资源主记录ID(version_resource.id)")
private Long resourceId;
@Schema(description = "来源资源库名")
private String sourceRepo;
@Schema(description = "来源馆")
private String sourceLibrary;
@Schema(description = "来源馆地址(IP:端口或域名)")
private String sourceLibraryAddr;
@Schema(description = "全文地址(下载地址)")
private String fulltextUrl;
@Schema(description = "加工编号(该来源库内的编号)")
private String processNo;
@Schema(description = "媒体类型(纸质/电子,可选,便于概览页区分)")
private String mediaType;
@Schema(description = "展示顺序,数值小的靠前")
private Integer sortNo;
@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;
}
@@ -18,7 +18,7 @@ import java.time.LocalDateTime;
@Schema(description = "版本资源元数据")
public class VersionResource implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
@Schema(description = "主键ID")
private Long id;
@@ -66,7 +66,8 @@ public class VersionResource implements Serializable {
@Schema(description = "所属任务年份(必备)")
private String taskYear;
@Schema(description = "来源馆(必备)")
@TableField("source_library")
@Schema(description = "来源馆(必备),对应 version_resource.source_library")
private String sourceLibrary;
@Schema(description = "来源馆地址(必备,IP:端口或域名)")
@@ -143,6 +144,26 @@ public class VersionResource implements Serializable {
@Schema(description = "数据密级/敏感词标记:0正常 1敏感")
private Integer sensitiveFlag;
@Schema(description = "是否特藏版本:0否 1是(是则展示在特藏推荐模块)")
private Integer isSpecial;
@Schema(description = "管理状态:0正常 1屏蔽 2下架")
private Integer manageStatus;
@Schema(description = "作者单位(责任者所属机构)")
private String authorOrg;
@Schema(description = "来源资源库名(主来源兜底,多来源详见 sources)")
private String sourceRepo;
/**
* 多来源列表(一条文献可来自多个资源库)。
* 非数据库字段,由检索/细览接口按 resource_id 批量挂载,供概览页按来源展示并分别下载。
*/
@TableField(exist = false)
@Schema(description = "多来源列表:一条文献可来自多个资源库,概览页按来源图标+名称展示并可分别下载")
private java.util.List<ResourceSource> sources;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
@@ -0,0 +1,12 @@
package com.banben.modules.resource.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.resource.entity.ResourceSource;
import org.apache.ibatis.annotations.Mapper;
/**
* 版本资源多来源 Mapper。
*/
@Mapper
public interface ResourceSourceMapper extends BaseMapper<ResourceSource> {
}
@@ -3,10 +3,26 @@ 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;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
* 版本资源 Mapper。
*/
@Mapper
public interface VersionResourceMapper extends BaseMapper<VersionResource> {
/**
* 元数据关键词热度:按分号/逗号/顿号/空白拆分 keywords 列后分组统计。
* 用于检索热词词云(与检索日志热词合并展示,均为库内真实数据)。
*/
@Select("SELECT k AS name, COUNT(*) AS cnt FROM ("
+ " SELECT regexp_split_to_table(keywords, '[;;,,、\\s]+') AS k"
+ " FROM version_resource"
+ " WHERE deleted = 0 AND keywords IS NOT NULL AND keywords <> ''"
+ ") t WHERE k <> '' GROUP BY k ORDER BY cnt DESC LIMIT #{limit}")
List<Map<String, Object>> splitKeywordCounts(@Param("limit") int limit);
}
@@ -0,0 +1,428 @@
package com.banben.modules.resource.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.resource.dto.ImportResult;
import com.banben.modules.resource.entity.VersionResource;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* 版本资源 Excel 模板导出与导入。
*
* <p>模板结构:第 1 行表头(* 表示必填),第 2 行填写说明,第 3 行起为用户数据。
* 导入时按表头名称匹配列,因此用户调整列顺序也不影响。</p>
*/
@Service
@RequiredArgsConstructor
public class VersionResourceExcelService {
private final VersionResourceService versionResourceService;
/** 下拉校验覆盖的行数;只影响模板中下拉框的作用范围,不限制导入行数 */
private static final int DROPDOWN_ROWS = 5000;
private record Column(String header, String field,
BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
}
private static final List<Column> COLUMNS = List.of(
new Column("正题名*", "title", VersionResource::setTitle, 512, "必填;示例行可覆盖或直接删除"),
new Column("加工编号", "processNo", VersionResource::setProcessNo, 128, "选填;系统中已存在则更新该条"),
new Column("责任者", "author", VersionResource::setAuthor, 512, "选填;多人用 ; 分隔"),
new Column("责任方式", "responsibility", VersionResource::setResponsibility, 256, "选填;如 著、编、译"),
new Column("中图分类", "clcCode", VersionResource::setClcCode, 64, "选填;如 G250.7"),
new Column("主题词", "keywords", VersionResource::setKeywords, 512, "选填;多个用 ; 分隔"),
new Column("摘要", "summary", VersionResource::setSummary, 2000, "选填;建议不少于 100 字"),
new Column("出版年份", "publishYear", VersionResource::setPublishYear, 8, "选填;格式 yyyy"),
new Column("出版者", "publisher", VersionResource::setPublisher, 256, "选填"),
new Column("出版地", "publishPlace", VersionResource::setPublishPlace, 128, "选填"),
new Column("出版日期", "publishDate", VersionResource::setPublishDate, 32, "选填;如 2026-01-01"),
new Column("版本版次", "edition", VersionResource::setEdition, 128, "选填"),
new Column("ISBN", "isbn", VersionResource::setIsbn, 64, "选填"),
new Column("内容形式", "contentForm", VersionResource::setContentForm, 64, "选填;如 文本"),
new Column("媒体类型", "mediaType", VersionResource::setMediaType, 32, "选填;纸质 或 电子"),
new Column("格式", "format", VersionResource::setFormat, 64, "选填;如 PDF"),
new Column("页码", "pageCount", VersionResource::setPageCount, 64, "选填"),
new Column("语种", "language", VersionResource::setLanguage, 16, "选填;三位代码,如 chi"),
new Column("来源馆", "sourceLibrary", VersionResource::setSourceLibrary, 256, "选填"),
new Column("数据提交单位", "submitOrg", VersionResource::setSubmitOrg, 256, "选填"),
new Column("任务年份", "taskYear", VersionResource::setTaskYear, 8, "选填;格式 yyyy"),
new Column("全文地址", "fulltextUrl", VersionResource::setFulltextUrl, 1024, "选填"),
new Column("是否特藏", "isSpecial", (r, v) -> { }, 4, "选填;是 或 否")
);
/**
* 模板自带的 5 条示例数据,列顺序与 {@link #COLUMNS} 严格一致。
* 正题名统一以「示例:」开头,导入时会被自动跳过。
*/
private static final String[][] SAMPLES = {
{"示例:军事理论教程", "EX-2026-0001", "张明", "著", "E0-43", "军事理论;教程",
"系统介绍军事理论的基本概念、发展脉络与研究方法,适用于院校教学参考。",
"2026", "军事科学出版社", "北京", "2026-03-01", "第2版", "978-7-80137-001-1",
"文本", "纸质", "PDF", "286", "chi", "陆军步兵学院图书馆", "陆军步兵学院",
"2026", "", "否"},
{"示例:版本资源元数据著录规范", "EX-2026-0002", "李华", "编", "G254.3", "元数据;著录",
"依据国家与军队相关标准,规范版本资源元数据的著录字段、格式与质量控制要求。",
"2025", "国防大学出版社", "北京", "2025-09-15", "第1版", "978-7-5626-002-2",
"文本", "电子", "PDF", "210", "chi", "南京某院校图书馆", "陆军步兵学院",
"2026", "http://cdio.example.org/fulltext/EX-2026-0002", "否"},
{"示例:中国古代兵书辑要", "EX-2026-0003", "王强", "整理", "E892", "兵书;古籍",
"收录先秦至明清重要兵书,附版本源流考述与校勘记,供版本比对研究使用。",
"2024", "中华书局", "北京", "2024-06-20", "影印本", "978-7-101-0033-3",
"文本", "纸质", "PDF", "520", "chi", "陆军勤务学院图书馆", "陆军勤务学院",
"2025", "", "是"},
{"示例:数字图书馆建设实践", "EX-2026-0004", "赵敏", "著", "G250.76", "数字图书馆;建设",
"围绕数字图书馆的资源组织、平台架构与服务模式展开,含多个建设案例分析。",
"2023", "国家图书馆出版社", "北京", "2023-11-10", "第1版", "978-7-5013-0044-4",
"文本", "电子", "EPUB", "340", "chi", "陆军指挥学院图书馆", "陆军指挥学院",
"2025", "", "否"},
{"示例:外军装备发展研究", "EX-2026-0005", "陈刚", "主编", "E92", "装备;外军",
"分析外军主战装备的发展路径、技术特点与体系构成,供装备论证参考。",
"2025", "国防工业出版社", "北京", "2025-05-08", "", "978-7-118-0055-5",
"文本", "纸质", "PDF", "415", "chi", "陆军航空兵学院图书馆", "陆军航空兵学院",
"2026", "", "否"}
};
// ==================== 模板导出 ====================
public void writeTemplate(OutputStream out) throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("版本资源");
CellStyle headStyle = buildHeadStyle(wb);
CellStyle hintStyle = buildHintStyle(wb);
Row head = sheet.createRow(0);
Row hint = sheet.createRow(1);
head.setHeightInPoints(24);
hint.setHeightInPoints(18);
for (int i = 0; i < COLUMNS.size(); i++) {
Column col = COLUMNS.get(i);
Cell h = head.createCell(i);
h.setCellValue(col.header());
h.setCellStyle(headStyle);
Cell t = hint.createCell(i);
t.setCellValue(col.hint());
t.setCellStyle(hintStyle);
int width = Math.max(12, Math.min(46, displayWidth(col.header()) + 4));
if ("summary".equals(col.field()) || "fulltextUrl".equals(col.field())) {
width = 46;
}
sheet.setColumnWidth(i, width * 256);
}
sheet.createFreezePane(0, 2);
// 5 条示例数据:供对照填写,导入时自动跳过
CellStyle sampleStyle = buildSampleStyle(wb);
for (int r = 0; r < SAMPLES.length; r++) {
Row row = sheet.createRow(2 + r);
row.setHeightInPoints(20);
for (int c = 0; c < SAMPLES[r].length && c < COLUMNS.size(); c++) {
Cell cell = row.createCell(c);
cell.setCellValue(SAMPLES[r][c]);
cell.setCellStyle(sampleStyle);
}
}
// 媒体类型、是否特藏加下拉,避免填错
addDropdown(sheet, indexOf("mediaType"), new String[]{"纸质", "电子"});
addDropdown(sheet, indexOf("isSpecial"), new String[]{"是", "否"});
wb.write(out);
}
}
private CellStyle buildHeadStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 11);
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
border(style);
return style;
}
private CellStyle buildHintStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontHeightInPoints((short) 9);
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setWrapText(true);
border(style);
return style;
}
private CellStyle buildSampleStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFont(font);
style.setVerticalAlignment(VerticalAlignment.CENTER);
border(style);
return style;
}
private void border(CellStyle style) {
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
}
private int displayWidth(String text) {
int w = 0;
for (char c : text.toCharArray()) {
w += c > 127 ? 2 : 1;
}
return w;
}
private int indexOf(String field) {
for (int i = 0; i < COLUMNS.size(); i++) {
if (COLUMNS.get(i).field().equals(field)) return i;
}
return -1;
}
private void addDropdown(Sheet sheet, int colIndex, String[] options) {
if (colIndex < 0) return;
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint =
helper.createExplicitListConstraint(options);
CellRangeAddressList range = new CellRangeAddressList(2, DROPDOWN_ROWS, colIndex, colIndex);
DataValidation validation = helper.createValidation(constraint, range);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
// ==================== 导入 ====================
public ImportResult importExcel(MultipartFile file) throws IOException {
ImportResult result = new ImportResult();
if (file == null || file.isEmpty()) {
result.addError(0, "请选择要导入的 Excel 文件");
return result;
}
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
Sheet sheet = wb.getSheetAt(0);
if (sheet == null || sheet.getLastRowNum() < 1) {
result.addError(0, "表格为空,请使用系统导出的模板填写数据");
return result;
}
// 1) 表头 → 列号
Row headRow = sheet.getRow(0);
Map<String, Integer> colIndex = new HashMap<>();
for (Cell cell : headRow) {
String name = normalizeHeader(cellText(cell));
if (StrUtil.isNotBlank(name)) {
colIndex.put(name, cell.getColumnIndex());
}
}
if (!colIndex.containsKey("正题名")) {
result.addError(1, "表头缺少「正题名」列,请使用系统导出的模板");
return result;
}
// 2) 判断第 2 行是否为说明行
int startRow = 1;
Row second = sheet.getRow(1);
if (second != null) {
String first = cellText(second.getCell(0));
if (first != null && (first.startsWith("必填") || first.startsWith("选填"))) {
startRow = 2;
}
}
// 3) 逐行解析
List<VersionResource> parsed = new ArrayList<>();
List<Integer> rowNums = new ArrayList<>();
int last = sheet.getLastRowNum();
for (int r = startRow; r <= last; r++) {
Row row = sheet.getRow(r);
if (row == null) continue;
VersionResource res = new VersionResource();
boolean empty = true;
for (Column col : COLUMNS) {
Integer idx = colIndex.get(normalizeHeader(col.header()));
if (idx == null) continue;
String value = cellText(row.getCell(idx));
if (StrUtil.isBlank(value)) continue;
empty = false;
if ("isSpecial".equals(col.field())) {
res.setIsSpecial(parseBool(value) ? 1 : 0);
} else {
col.setter().accept(res, truncate(value.trim(), col.maxLen()));
}
}
if (empty) continue;
int excelRowNum = r + 1;
if (StrUtil.isBlank(res.getTitle())) {
result.addError(excelRowNum, "正题名不能为空");
continue;
}
// 模板自带的示例行:跳过,不参与导入
if (res.getTitle().startsWith("示例:") || res.getTitle().startsWith("示例:")) {
result.setSkipped(result.getSkipped() + 1);
continue;
}
if (StrUtil.isBlank(res.getGovernStatus())) {
res.setGovernStatus("RAW");
}
if (res.getDeleted() == null) {
res.setDeleted(0);
}
if (res.getIsSpecial() == null) {
res.setIsSpecial(0);
}
parsed.add(res);
rowNums.add(excelRowNum);
}
result.setTotal(parsed.size());
if (parsed.isEmpty()) {
if (result.getFailed() == 0) {
result.addError(0, result.getSkipped() > 0
? "仅读取到模板示例数据,请填写实际数据后再导入"
: "未读取到有效数据行,请从第 3 行开始填写");
}
return result;
}
// 4) 按加工编号匹配已有记录
Map<String, Long> existing = findExisting(parsed);
List<VersionResource> inserts = new ArrayList<>();
List<VersionResource> updates = new ArrayList<>();
for (int i = 0; i < parsed.size(); i++) {
VersionResource res = parsed.get(i);
Long existId = StrUtil.isBlank(res.getProcessNo())
? null : existing.get(res.getProcessNo().trim());
if (existId != null) {
res.setId(existId);
updates.add(res);
} else {
inserts.add(res);
}
}
// 5) 分批写库
if (!inserts.isEmpty()) {
versionResourceService.saveBatch(inserts, 500);
}
if (!updates.isEmpty()) {
versionResourceService.updateBatchById(updates, 500);
}
result.setInserted(inserts.size());
result.setUpdated(updates.size());
return result;
} catch (Exception e) {
result.addError(0, "文件解析失败:" + e.getMessage());
return result;
}
}
/** 一次性查出所有已存在的加工编号,避免逐行查库 */
private Map<String, Long> findExisting(List<VersionResource> list) {
List<String> nos = list.stream()
.map(VersionResource::getProcessNo)
.filter(StrUtil::isNotBlank)
.map(String::trim)
.distinct()
.collect(Collectors.toList());
if (nos.isEmpty()) return Collections.emptyMap();
LambdaQueryWrapper<VersionResource> wrapper = new LambdaQueryWrapper<>();
wrapper.in(VersionResource::getProcessNo, nos);
return versionResourceService.list(wrapper).stream()
.filter(r -> StrUtil.isNotBlank(r.getProcessNo()))
.collect(Collectors.toMap(
r -> r.getProcessNo().trim(),
VersionResource::getId,
(a, b) -> a));
}
private String normalizeHeader(String s) {
if (s == null) return "";
return s.replace("*", "")
.replace("*", "")
.replace(" ", "")
.replace(" ", "")
.trim();
}
private String cellText(Cell cell) {
if (cell == null) return null;
CellType type = cell.getCellType();
if (type == CellType.FORMULA) {
type = cell.getCachedFormulaResultType();
}
switch (type) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getLocalDateTimeCellValue().toLocalDate().toString();
}
double d = cell.getNumericCellValue();
if (d == Math.floor(d) && !Double.isInfinite(d)) {
return String.valueOf((long) d);
}
return String.valueOf(d);
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return null;
}
}
private boolean parseBool(String v) {
String s = v.trim();
return "是".equals(s) || "1".equals(s) || "true".equalsIgnoreCase(s) || "y".equalsIgnoreCase(s);
}
private String truncate(String v, int max) {
if (v == null) return null;
return v.length() > max ? v.substring(0, max) : v;
}
}
@@ -19,4 +19,9 @@ public interface VersionResourceService extends IService<VersionResource> {
* 保存或更新版本资源。
*/
Long saveOrUpdateResource(VersionResource resource);
/**
* 更新「是否特藏版本」标记(0否 1是)。
*/
void updateSpecialFlag(Long id, Integer isSpecial);
}
@@ -2,6 +2,7 @@ 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.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.PageResult;
@@ -71,4 +72,15 @@ public class VersionResourceServiceImpl
this.saveOrUpdate(resource);
return resource.getId();
}
/**
* 仅更新「是否特藏版本」标记:1 是 → 展示在特藏推荐模块;其余值一律归 0。
*/
@Override
public void updateSpecialFlag(Long id, Integer isSpecial) {
LambdaUpdateWrapper<VersionResource> wrapper = new LambdaUpdateWrapper<>();
wrapper.eq(VersionResource::getId, id)
.set(VersionResource::getIsSpecial, isSpecial != null && isSpecial == 1 ? 1 : 0);
this.update(wrapper);
}
}
@@ -4,6 +4,7 @@ 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.ClcNodeVO;
import com.banben.modules.search.vo.SearchResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -73,6 +74,12 @@ public class SearchController {
return Result.success(searchService.similar(id, limit));
}
@Operation(summary = "中图法分类树(部类/大类/类目,带命中数量,供左侧导航逐级展开)")
@GetMapping("/clc/tree")
public Result<List<ClcNodeVO>> clcTree(SearchQuery query) {
return Result.success(searchService.clcTree(query));
}
@Operation(summary = "检索结果列表(用于导出/批量处理,最多 10000 条)")
@PostMapping("/list")
public Result<List<VersionResource>> list(@RequestBody SearchQuery query) {
@@ -24,6 +24,9 @@ public class SearchQuery {
@Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)")
private String keyword;
@Schema(description = "去除关键字(结果集排除,空格分隔可多个;含任一排除词的记录不返回)")
private String excludeKeyword;
@Schema(description = "题名")
private String title;
@@ -42,13 +45,28 @@ public class SearchQuery {
@Schema(description = "中图分类号(前方一致)")
private String clcCode;
@Schema(description = "中图分类号(多个,前方一致,任一命中即可;用于「中图法」树导航点选部类/大类)")
private List<String> clcCodes;
/** ---------------- 多类型/多来源 ---------------- */
@Schema(description = "媒体类型:纸质/电子")
private String mediaType;
@Schema(description = "媒体类型(多选,in):纸质/电子")
private List<String> mediaTypes;
@Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)")
private String languageGroup;
@Schema(description = "来源馆(多选)")
private List<String> sourceLibraries;
@Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)")
private String sourceLibrary;
@Schema(description = "来源资源库名(多选,in)")
private List<String> sourceRepos;
/** ---------------- 限定出版时段 ---------------- */
@Schema(description = "出版年份起(含)", example = "2000")
private String publishYearStart;
@@ -60,6 +78,9 @@ public class SearchQuery {
@Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)")
private String matchType = "LIKE";
@Schema(description = "在结果中搜索:新增关键词必须同时命中(AND 收窄当前结果集)")
private String withinKeyword;
@Schema(description = "多字段逻辑:AND(默认) / OR")
private String logic = "AND";
@@ -0,0 +1,50 @@
package com.banben.modules.search.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 中图法分类字典(clc_category)。
*
* <p>层级:1 五大部类 / 2 二十二个基本大类 / 3 二级类目;
* 统一检索页左侧「中图法」分面导航使用 level=2 的大类节点。</p>
*/
@Data
@TableName("clc_category")
public class ClcCategory {
@TableId(type = IdType.AUTO)
private Long id;
/** 父级ID,顶级为 0 */
private Long parentId;
/** 中图法分类号(如 A / E / TB / E8) */
private String clcCode;
/** 分类名称 */
private String name;
/** 层级(1-7) */
private Integer level;
/** 同级排序号 */
private Integer sortOrder;
/** 全路径(部类名/大类名/类目名) */
private String fullPath;
/** 是否最末级(0否 1是) */
private Integer isLeaf;
private LocalDateTime createTime;
private LocalDateTime updateTime;
/** 逻辑删除标识 */
private Integer deleted;
}
@@ -19,7 +19,7 @@ import java.time.LocalDateTime;
@Schema(description = "检索行为日志")
public class SearchLog implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
@TableId(type = IdType.AUTO)
private Long id;
@Schema(description = "检索关键词")
@@ -0,0 +1,10 @@
package com.banben.modules.search.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.banben.modules.search.entity.ClcCategory;
import org.apache.ibatis.annotations.Mapper;
/** 中图法分类字典 Mapper */
@Mapper
public interface ClcCategoryMapper extends BaseMapper<ClcCategory> {
}
@@ -2,6 +2,7 @@ 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.ClcNodeVO;
import com.banben.modules.search.vo.SearchResultVO;
import java.util.List;
@@ -35,4 +36,10 @@ public interface SearchService {
* 导出检索结果(上限 {@code limit} 条)。
*/
List<VersionResource> exportList(SearchQuery query, int limit);
/**
* 中图法分类树(部类 -> 大类 -> 类目),带当前检索条件下的命中数量,
* 供检索页左侧导航逐级展开后点选检索。
*/
List<ClcNodeVO> clcTree(SearchQuery query);
}
@@ -5,12 +5,19 @@ 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.admin.entity.SensitiveWord;
import com.banben.modules.admin.mapper.SensitiveWordMapper;
import com.banben.modules.resource.entity.ResourceSource;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.mapper.ResourceSourceMapper;
import com.banben.modules.resource.mapper.VersionResourceMapper;
import com.banben.modules.search.dto.SearchQuery;
import com.banben.modules.search.entity.ClcCategory;
import com.banben.modules.search.entity.SearchLog;
import com.banben.modules.search.mapper.ClcCategoryMapper;
import com.banben.modules.search.mapper.SearchLogMapper;
import com.banben.modules.search.service.SearchService;
import com.banben.modules.search.vo.ClcNodeVO;
import com.banben.modules.search.vo.FacetItem;
import com.banben.modules.search.vo.SearchResultVO;
import com.banben.modules.search.vo.YearStat;
@@ -19,9 +26,13 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 检索发现服务实现。
@@ -39,12 +50,29 @@ public class SearchServiceImpl implements SearchService {
private static final int FACET_TOP = 20;
private final VersionResourceMapper resourceMapper;
private final ResourceSourceMapper sourceMapper;
private final SearchLogMapper searchLogMapper;
private final ClcCategoryMapper clcCategoryMapper;
private final SensitiveWordMapper sensitiveWordMapper;
@Override
public SearchResultVO search(SearchQuery query, String userIp) {
long start = System.currentTimeMillis();
// 敏感词拦截:检索词命中敏感词库时直接屏蔽结果(facets 一并置空)
if (hitsSensitive(query)) {
SearchResultVO vo = new SearchResultVO();
vo.setPage(PageResult.of(List.of(), 0, query.getCurrent(), query.getSize()));
vo.setMediaTypeFacets(List.of());
vo.setSourceLibraryFacets(List.of());
vo.setClcFacets(List.of());
vo.setYearStats(List.of());
vo.setSensitiveBlocked(true);
vo.setCostMs(System.currentTimeMillis() - start);
saveSearchLog(query, userIp, 0, vo.getCostMs().intValue());
return vo;
}
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
applyOrder(wrapper, query);
@@ -52,10 +80,27 @@ public class SearchServiceImpl implements SearchService {
Page.of(query.getCurrent(), query.getSize()), wrapper);
SearchResultVO vo = new SearchResultVO();
attachSources(page.getRecords());
vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize()));
// 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。
// 仅在带检索条件时统计:空词全量浏览(刷新/首页进入)不提示
if (hasCondition(query)) {
try {
long withMasked = resourceMapper.selectCount(
buildWrapper(query, false, null, true));
if (withMasked > page.getTotal()) {
vo.setMaskedCount(withMasked - page.getTotal());
}
} catch (Exception e) {
log.warn("统计被屏蔽命中数失败:{}", e.getMessage());
}
}
vo.setMediaTypeFacets(facet(query, "media_type"));
vo.setSourceLibraryFacets(facet(query, "source_library"));
vo.setClcFacets(facet(query, "clc_code"));
vo.setSourceRepoFacets(facet(query, "source_repo"));
vo.setClcFacets(clcFacet(query));
vo.setYearStats(yearStats(query));
long cost = System.currentTimeMillis() - start;
@@ -73,7 +118,11 @@ public class SearchServiceImpl implements SearchService {
@Override
public VersionResource detail(Long id) {
return resourceMapper.selectById(id);
VersionResource r = resourceMapper.selectById(id);
if (r != null) {
attachSources(List.of(r));
}
return r;
}
@Override
@@ -104,7 +153,9 @@ public class SearchServiceImpl implements SearchService {
});
}
wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper);
List<VersionResource> list = resourceMapper.selectList(wrapper);
attachSources(list);
return list;
}
@Override
@@ -112,24 +163,159 @@ public class SearchServiceImpl implements SearchService {
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
applyOrder(wrapper, query);
wrapper.last("limit " + Math.max(1, limit));
return resourceMapper.selectList(wrapper);
List<VersionResource> list = resourceMapper.selectList(wrapper);
attachSources(list);
return list;
}
/**
* 批量挂载多来源:按主记录 ID 一次查出全部来源,挂到各 {@link VersionResource#sources} 上。
*
* <p>来源为空(旧数据未维护多来源)时,{@code sources} 保持为空列表,
* 前端会回退到主表单来源字段展示与下载。</p>
*/
private void attachSources(List<VersionResource> records) {
if (records == null || records.isEmpty()) {
return;
}
List<Long> ids = records.stream()
.map(VersionResource::getId)
.filter(Objects::nonNull)
.distinct()
.toList();
if (ids.isEmpty()) {
return;
}
try {
List<ResourceSource> all = sourceMapper.selectList(
new QueryWrapper<ResourceSource>()
.in("resource_id", ids)
.eq("deleted", 0)
.orderByAsc("sort_no"));
Map<Long, List<ResourceSource>> byRes = all.stream()
.collect(Collectors.groupingBy(
ResourceSource::getResourceId,
LinkedHashMap::new,
Collectors.toList()));
for (VersionResource r : records) {
r.setSources(byRes.getOrDefault(r.getId(), List.of()));
}
} catch (Exception e) {
log.warn("批量挂载多来源失败(不影响主结果返回):{}", e.getMessage());
for (VersionResource r : records) {
if (r.getSources() == null) {
r.setSources(List.of());
}
}
}
}
// ==================== 内部方法 ====================
/**
* 敏感词拦截:检索词(综合/题名/责任者/出版者/ISBN/CDOI 任一途径)命中敏感词库即屏蔽。
*
* <p>敏感词表不存在或查询异常时不拦截(降级为正常检索),避免影响可用性。</p>
*/
private boolean hitsSensitive(SearchQuery q) {
String text = StrUtil.nullToEmpty(q.getKeyword()) + "\n"
+ StrUtil.nullToEmpty(q.getTitle()) + "\n"
+ StrUtil.nullToEmpty(q.getAuthor()) + "\n"
+ StrUtil.nullToEmpty(q.getPublisher()) + "\n"
+ StrUtil.nullToEmpty(q.getIsbn()) + "\n"
+ StrUtil.nullToEmpty(q.getCdoi());
if (text.isBlank()) {
return false;
}
try {
for (SensitiveWord sw : sensitiveWordMapper.selectList(null)) {
String word = sw.getWord();
if (StrUtil.isNotBlank(word) && text.contains(word)) {
return true;
}
}
} catch (Exception e) {
log.warn("敏感词检查失败,本次不拦截:{}", e.getMessage());
}
return false;
}
/**
* 是否带有任意检索/筛选条件(区别于空词全量浏览)。
*/
private boolean hasCondition(SearchQuery q) {
return StrUtil.isNotBlank(q.getKeyword()) || StrUtil.isNotBlank(q.getTitle())
|| StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher())
|| StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi())
|| StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes())
|| StrUtil.isNotBlank(q.getMediaType()) || CollectionUtil.isNotEmpty(q.getMediaTypes())
|| StrUtil.isNotBlank(q.getLanguageGroup())
|| StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries())
|| CollectionUtil.isNotEmpty(q.getSourceRepos())
|| StrUtil.isNotBlank(q.getWithinKeyword())
|| StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd());
}
/**
* 构造查询条件(多途径 / 多类型 / 多来源 / 多精度 / 限定出版时段)。
*/
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) {
return buildWrapper(q, false, null, false);
}
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q, boolean excludeClc) {
return buildWrapper(q, excludeClc, null, false);
}
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q, boolean excludeClc,
String excludeColumn, boolean includeMasked) {
QueryWrapper<VersionResource> w = new QueryWrapper<>();
w.eq("deleted", 0);
// 后台处置过的记录不进检索(元数据与索引屏蔽/下架):0正常 1屏蔽 2下架
// includeMasked=true 时忽略该过滤,用于统计「命中但被隐藏」的记录数
if (!includeMasked) {
w.and(x -> x.isNull("manage_status").or().eq("manage_status", 0));
}
// 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者
// 多词检索:空格分词,词与词之间 OR(命中任一词即返回)
if (StrUtil.isNotBlank(q.getKeyword())) {
String kw = q.getKeyword().trim();
w.and(x -> x.like("title", kw).or().like("author", kw).or()
List<String> terms = splitTerms(q.getKeyword());
w.and(x -> {
boolean first = true;
for (String kw : terms) {
if (!first) {
x.or();
}
first = false;
x.nested(y -> y.like("title", kw).or().like("author", kw).or()
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw));
}
});
}
// 去除关键字:排除含任一排除词的记录(与综合关键词覆盖同样的文本字段)
// 字段为空(IS NULL)不计入排除,避免把缺字段的记录误删
if (StrUtil.isNotBlank(q.getExcludeKeyword())) {
List<String> exTerms = splitTerms(q.getExcludeKeyword());
for (String ex : exTerms) {
w.and(x -> x
.and(y -> y.notLike("title", ex).or().isNull("title"))
.and(y -> y.notLike("author", ex).or().isNull("author"))
.and(y -> y.notLike("keywords", ex).or().isNull("keywords"))
.and(y -> y.notLike("summary", ex).or().isNull("summary"))
.and(y -> y.notLike("publisher", ex).or().isNull("publisher"))
);
}
}
// 在结果中搜索:每个新增关键词都必须命中(AND 收窄当前结果集)
if (StrUtil.isNotBlank(q.getWithinKeyword())) {
for (String kw : splitTerms(q.getWithinKeyword())) {
w.and(x -> x.nested(y -> y.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());
@@ -137,14 +323,51 @@ public class SearchServiceImpl implements SearchService {
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 (!excludeClc && StrUtil.isNotBlank(q.getClcCode())) {
w.likeRight("clc_code", q.getClcCode().trim().toUpperCase());
}
if (StrUtil.isNotBlank(q.getMediaType())) {
// 中图法树导航:点部类时传入其下所有大类号,任一命中即可
if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) {
w.and(x -> {
boolean first = true;
for (String c : q.getClcCodes()) {
if (StrUtil.isBlank(c)) {
continue;
}
if (!first) {
x.or();
}
first = false;
x.likeRight("clc_code", c.trim().toUpperCase());
}
});
}
// 资源类型:单选或罗列多选(分面排除时跳过本列过滤,便于切换)
if (!"media_type".equals(excludeColumn)) {
if (CollectionUtil.isNotEmpty(q.getMediaTypes())) {
w.in("media_type", q.getMediaTypes());
} else if (StrUtil.isNotBlank(q.getMediaType())) {
w.eq("media_type", q.getMediaType());
}
}
// 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据);
// 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组)
if ("chi".equalsIgnoreCase(q.getLanguageGroup())) {
w.in("language", List.of("chi", "zh", "中文"));
} else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) {
w.notIn("language", List.of("chi", "zh", "中文"));
}
// 来源院校:多选(IN)或单选(分面排除时跳过本列过滤)
if (!"source_library".equals(excludeColumn)) {
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
w.in("source_library", q.getSourceLibraries());
} else if (StrUtil.isNotBlank(q.getSourceLibrary())) {
w.eq("source_library", q.getSourceLibrary().trim());
}
}
// 资源库名:多选(IN)
if (CollectionUtil.isNotEmpty(q.getSourceRepos()) && !"source_repo".equals(excludeColumn)) {
w.in("source_repo", q.getSourceRepos());
}
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
w.ge("publish_year", q.getPublishYearStart().trim());
@@ -157,19 +380,43 @@ public class SearchServiceImpl implements SearchService {
/**
* 多精度匹配:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊。
*
* <p>多词检索:按空格分词,同一字段内词与词之间 OR(LIKE/LEFT/RIGHT 生效;
* EQ 为精确匹配语义,保持整串不拆分)。不同字段之间仍为 AND。</p>
*/
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);
if ("EQ".equals(type)) {
w.eq(column, value.trim());
return;
}
List<String> terms = splitTerms(value);
w.and(x -> {
boolean first = true;
for (String term : terms) {
if (!first) {
x.or();
}
first = false;
switch (type) {
case "LEFT" -> x.likeRight(column, term);
case "RIGHT" -> x.likeLeft(column, term);
default -> x.like(column, term);
}
}
});
}
/**
* 检索词分词:按空白字符拆分为多个关键词。
*/
private List<String> splitTerms(String value) {
return Arrays.stream(value.trim().split("\\s+"))
.filter(StrUtil::isNotBlank)
.toList();
}
/**
@@ -203,7 +450,9 @@ public class SearchServiceImpl implements SearchService {
* @param column 参与分组的列(media_type / source_library / clc_code)
*/
private List<FacetItem> facet(SearchQuery query, String column) {
QueryWrapper<VersionResource> w = buildWrapper(query);
// 统计该列分面时排除列自身的过滤条件:选中「电子」后,
// 「资源类型」分组里纸质等其它选项仍应显示数量、可点击切换
QueryWrapper<VersionResource> w = buildWrapper(query, false, column, false);
w.select(column + " AS name", "COUNT(*) AS cnt")
.isNotNull(column)
.ne(column, "")
@@ -223,6 +472,181 @@ public class SearchServiceImpl implements SearchService {
return items;
}
/**
* 中图法分面:按分类号首字母聚合到 {@code clc_category} 的二十二个基本大类。
*
* <p>统计口径为「分类号前方一致」:E8、E9 都计入大类 E(军事),
* 再用 clc_category 的 level=2 节点把字母翻译成类名。
* 统计时忽略条件里已选的大类(excludeClc),保证导航间可切换。</p>
*/
private List<FacetItem> clcFacet(SearchQuery query) {
QueryWrapper<VersionResource> w = buildWrapper(query, true);
w.select("UPPER(SUBSTRING(clc_code, 1, 1)) AS name", "COUNT(*) AS cnt")
.isNotNull("clc_code")
.ne("clc_code", "")
.groupBy("UPPER(SUBSTRING(clc_code, 1, 1))")
.orderByDesc("cnt");
List<Map<String, Object>> maps = resourceMapper.selectMaps(w);
Map<String, String> names = clcTopClassNames();
List<FacetItem> items = new ArrayList<>();
for (Map<String, Object> m : maps) {
Object name = m.get("name");
if (name == null) {
continue;
}
String code = String.valueOf(name);
items.add(new FacetItem(names.getOrDefault(code, code), toLong(m.get("cnt")), code));
}
return items;
}
/**
* 中图法分类树:部类 -> 大类 -> 类目,逐级列出并带命中数量。
*
* <p>实现要点:
* <ol>
* <li>一次取出 {@code clc_category} 全部节点(deleted=0),按层级组装成树;</li>
* <li>一次按 {@code clc_code} 分组统计当前检索条件下的命中数(忽略已选分类,
* 保证切换到别的分支时数量依然可见);</li>
* <li>资源的分类号通常比三级类目更细(如 E83、TN97、G250.7),
* 按「最长前缀」归并到最具体的类目节点,再自底向上累加到父节点。</li>
* </ol>
*/
@Override
public List<ClcNodeVO> clcTree(SearchQuery query) {
List<ClcCategory> all = new ArrayList<>();
try {
all = clcCategoryMapper.selectList(new QueryWrapper<ClcCategory>()
.eq("deleted", 0)
.orderByAsc("level", "sort_order", "id"));
} catch (Exception e) {
log.warn("读取中图法分类失败:{}", e.getMessage());
}
if (all.isEmpty()) {
return List.of();
}
// 命中数量:先落到最具体的类目节点上,再由子节点向上累加
Map<Long, Long> countByNodeId = new java.util.HashMap<>();
List<ClcCategory> byLevel = new ArrayList<>(all);
for (Map<String, Object> m : clcCodeCounts(query)) {
String resCode = String.valueOf(m.get("name"));
long cnt = toLong(m.get("cnt"));
if (StrUtil.isBlank(resCode)) {
continue;
}
ClcCategory node = matchDeepest(byLevel, resCode.trim().toUpperCase());
if (node != null) {
countByNodeId.merge(node.getId(), cnt, Long::sum);
}
}
return buildTree(all, countByNodeId);
}
/** 当前检索条件下的分类号分组统计(忽略条件里已选的中图分类) */
private List<Map<String, Object>> clcCodeCounts(SearchQuery query) {
QueryWrapper<VersionResource> w = buildWrapper(query, true);
w.select("clc_code AS name", "COUNT(*) AS cnt")
.isNotNull("clc_code")
.ne("clc_code", "")
.groupBy("clc_code");
try {
return resourceMapper.selectMaps(w);
} catch (Exception e) {
log.warn("统计中图法命中数量失败:{}", e.getMessage());
return List.of();
}
}
/**
* 找与资源分类号最匹配的类目:类目号是其前缀时命中,取最长的那个(类目越细越具体)。
* 区间号(D33-37 这类含短横线的)不参与前缀匹配。
*
* <p>level=1 的部类编号(1~5)是字典表的分组号、不是真实分类号,
* 若参与前缀匹配,会把 clc_code 恰好以数字开头的脏数据(如 11)误算进部类计数,
* 导致「树上有数量、点进去检索却是 0 条」——部类计数只能由子节点累加而来。</p>
*/
private ClcCategory matchDeepest(List<ClcCategory> nodes, String resCode) {
ClcCategory best = null;
for (ClcCategory n : nodes) {
String code = n.getClcCode();
if (StrUtil.isBlank(code) || code.contains("-") || code.contains("/")) {
continue;
}
if (n.getLevel() == null || n.getLevel() <= 1) {
continue;
}
if (!resCode.startsWith(code.toUpperCase())) {
continue;
}
if (best == null || code.length() > best.getClcCode().length()) {
best = n;
}
}
return best;
}
/** 组装树并自底向上累加命中数量 */
private List<ClcNodeVO> buildTree(List<ClcCategory> all, Map<Long, Long> countByNodeId) {
Map<Long, List<ClcCategory>> childrenByParent = new java.util.HashMap<>();
for (ClcCategory c : all) {
childrenByParent.computeIfAbsent(c.getParentId() == null ? 0L : c.getParentId(), k -> new ArrayList<>()).add(c);
}
// 按层级从深到浅累加:子节点数量汇总到父节点
Map<Long, Long> total = new java.util.HashMap<>(countByNodeId);
for (int lv = 7; lv >= 2; lv--) {
int cur = lv;
for (ClcCategory c : all) {
if (c.getLevel() == null || c.getLevel() != cur) {
continue;
}
long self = total.getOrDefault(c.getId(), 0L);
if (self == 0) {
continue;
}
Long pid = c.getParentId() == null ? 0L : c.getParentId();
total.merge(pid, self, Long::sum);
}
}
List<ClcCategory> roots = childrenByParent.getOrDefault(0L, List.of());
List<ClcNodeVO> tree = new ArrayList<>();
for (ClcCategory r : roots) {
tree.add(toNode(r, childrenByParent, total));
}
return tree;
}
private ClcNodeVO toNode(ClcCategory c, Map<Long, List<ClcCategory>> childrenByParent, Map<Long, Long> total) {
ClcNodeVO vo = new ClcNodeVO();
vo.setCode(c.getClcCode());
vo.setName(c.getName());
vo.setLevel(c.getLevel());
vo.setCount(total.getOrDefault(c.getId(), 0L));
for (ClcCategory child : childrenByParent.getOrDefault(c.getId(), List.of())) {
vo.getChildren().add(toNode(child, childrenByParent, total));
}
return vo;
}
/** 中图法二十二个基本大类:分类号 -> 类名(查不到字典表时返回空映射,前端退化为显示字母) */
private Map<String, String> clcTopClassNames() {
try {
List<ClcCategory> list = clcCategoryMapper.selectList(
new QueryWrapper<ClcCategory>().eq("deleted", 0).eq("level", 2));
Map<String, String> map = new java.util.HashMap<>();
for (ClcCategory c : list) {
map.put(c.getClcCode(), c.getName());
}
return map;
} catch (Exception e) {
log.warn("读取中图法大类失败:{}", e.getMessage());
return Map.of();
}
}
/**
* 命中文献各年份发文量。
*/
@@ -0,0 +1,30 @@
package com.banben.modules.search.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 中图法分类树节点(左侧逐级展开的导航)。
*/
@Data
@Schema(description = "中图法分类树节点")
public class ClcNodeVO {
@Schema(description = "分类号,如 3 / E / E8")
private String code;
@Schema(description = "分类名称")
private String name;
@Schema(description = "层级:1部类 2大类 3类目")
private Integer level;
@Schema(description = "当前检索条件下的命中数量(含下级)")
private Long count;
@Schema(description = "下级节点")
private List<ClcNodeVO> children = new ArrayList<>();
}
@@ -1,7 +1,6 @@
package com.banben.modules.search.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@@ -10,7 +9,6 @@ import lombok.NoArgsConstructor;
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "分面项")
public class FacetItem {
@@ -19,4 +17,18 @@ public class FacetItem {
@Schema(description = "命中数量")
private Long value;
@Schema(description = "筛选值(中图法分面为分类号前缀,如 E;其余分面为空)")
private String code;
public FacetItem(String name, Long value) {
this.name = name;
this.value = value;
}
public FacetItem(String name, Long value, String code) {
this.name = name;
this.value = value;
this.code = code;
}
}
@@ -25,6 +25,9 @@ public class SearchResultVO {
@Schema(description = "来源院校分面")
private List<FacetItem> sourceLibraryFacets;
@Schema(description = "资源库名分面")
private List<FacetItem> sourceRepoFacets;
@Schema(description = "中图分类分面")
private List<FacetItem> clcFacets;
@@ -33,4 +36,10 @@ public class SearchResultVO {
@Schema(description = "检索耗时(ms)")
private Long costMs;
@Schema(description = "检索词命中敏感词库,结果已被屏蔽")
private Boolean sensitiveBlocked;
@Schema(description = "命中但被屏蔽/下架而不展示的记录数")
private Long maskedCount;
}
@@ -1,6 +1,8 @@
package com.banben.modules.special.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.special.dto.SpecialRecommendVO;
import com.banben.modules.special.entity.SpecialResource;
import com.banben.modules.special.service.SpecialService;
import io.swagger.v3.oas.annotations.Operation;
@@ -24,12 +26,20 @@ public class SpecialController {
private final SpecialService specialService;
@Operation(summary = "首页推荐特藏列表")
@Operation(summary = "特藏推荐列表(version_resource 中 is_special=1 的记录)")
@GetMapping("/recommend")
public Result<List<SpecialResource>> recommend(@RequestParam(defaultValue = "8") int limit) {
public Result<List<SpecialRecommendVO>> recommend(@RequestParam(defaultValue = "8") int limit) {
return Result.success(specialService.recommend(limit));
}
@Operation(summary = "特藏推荐分页列表")
@GetMapping("/recommend/page")
public Result<PageResult<SpecialRecommendVO>> recommendPage(
@RequestParam(defaultValue = "1") long current,
@RequestParam(defaultValue = "10") long size) {
return Result.success(specialService.recommendPage(current, size));
}
@Operation(summary = "特藏细览")
@GetMapping("/{id}")
public Result<SpecialResource> detail(@PathVariable Long id) {

Some files were not shown because too many files have changed in this diff Show More