feat: 新增后台管理入口与资源新增功能

- 首页齿轮按钮以新标签页打开后台管理,新增 Admin 路由与视图
- 资源列表支持新增版本资源,复用编辑抽屉
- 主页检索按字段映射到检索页途径(题名/关键词/责任者/出版社/综合)
- 检索支持多词分词 OR 匹配,并过滤已屏蔽/下架记录
- 聚同算法改为 ISBN 优先、无 ISBN 时四要素判定,并前后端统一抽取分组逻辑
- 数据库主键改为自增序列,新增敏感词库与院校资源节点表,补充特藏与管理状态字段及样例数据序列同步
This commit is contained in:
SUNJIAJINGS
2026-10-21 16:25:28 +08:00
parent e9c83e0be0
commit 46be7346a2
40 changed files with 2014 additions and 102 deletions
@@ -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,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,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,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,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,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,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,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,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;
}
}
@@ -20,7 +20,7 @@ import java.time.LocalDateTime;
@Schema(description = "系统用户") @Schema(description = "系统用户")
public class SysUser implements Serializable { public class SysUser implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@Schema(description = "登录账号") @Schema(description = "登录账号")
@@ -20,7 +20,7 @@ import java.time.LocalDateTime;
@Schema(description = "数据采集任务") @Schema(description = "数据采集任务")
public class CollectTask implements Serializable { public class CollectTask implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@Schema(description = "单位编码") @Schema(description = "单位编码")
@@ -21,7 +21,7 @@ import java.time.LocalDateTime;
@Schema(description = "版本资源呈缴记录") @Schema(description = "版本资源呈缴记录")
public class DepositRecord implements Serializable { public class DepositRecord implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@NotBlank(message = "呈缴单位名称不能为空") @NotBlank(message = "呈缴单位名称不能为空")
@@ -20,7 +20,7 @@ import java.time.LocalDateTime;
@Schema(description = "数据治理任务") @Schema(description = "数据治理任务")
public class GovernanceJob implements Serializable { public class GovernanceJob implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@Schema(description = "治理类型:MERGE聚同 / OPTIMIZE优化 / HINT提示 / PURIFY提纯") @Schema(description = "治理类型:MERGE聚同 / OPTIMIZE优化 / HINT提示 / PURIFY提纯")
@@ -3,6 +3,7 @@ package com.banben.modules.governance.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.banben.common.BusinessException; import com.banben.common.BusinessException;
import com.banben.modules.governance.entity.GovernanceJob; import com.banben.modules.governance.entity.GovernanceJob;
@@ -16,6 +17,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -41,9 +43,10 @@ import java.util.Set;
* ④ 提示(HINT):不改变状态,只产出清单,并把命中错漏的记录标记 abnormal_flag=1 * ④ 提示(HINT):不改变状态,只产出清单,并把命中错漏的记录标记 abnormal_flag=1
* </pre> * </pre>
* *
* <p><b>说明:</b>本实现是可运行的「轻量算法」——聚同以「题名 + 责任者」判定同一文献; * <p><b>说明:</b>本实现是可运行的「轻量算法」——聚同判定规则:
* 生产环境可按需引入 ISBN/CDOI 等多要素判定与相似度算法。批处理逐条提交, * <b>ISBN 相同</b>即同一文献;<b>无 ISBN 时</b>,以「书名 + 作者 + 出版社 + 出版年份」
* 任务失败时已处理部分保留、任务记录标记为 FAILED,可重跑(已合并记录不会重复处理)。</p> * 四要素完全一致判定同一文献。批处理逐条提交,任务失败时已处理部分保留、
* 任务记录标记为 FAILED,可重跑(已合并记录不会重复处理)。</p>
*/ */
@Slf4j @Slf4j
@Service @Service
@@ -104,55 +107,83 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
/** /**
* 聚同:将「不同来源 / 不同媒体类型」的同一文献元数据聚合为一条,并标注来源。 * 聚同:将「不同来源 / 不同媒体类型」的同一文献元数据聚合为一条,并标注来源。
* *
* <p>判定规则(轻量版):<b>题名 + 责任者</b> 相同即视为同一文献。 * <p>判定规则(两级):</p>
* 同组内按 id 升序取第一条为主记录 → 标记 {@code MERGED}; * <ol>
* 其余记录 → 标记 {@code MERGED_OUT} 并把 {@code merged_to_id} 指向主记录。</p> * <li><b>ISBN 相同</b>(非空)即视为同一文献;</li>
* * <li>ISBN 为空时,<b>「书名 + 作者 + 出版社 + 出版年份」四要素完全一致</b>
* <p>已 {@code MERGED_OUT} 的记录不参与再次聚同,因此任务可重复执行而结果稳定。</p> * 即视为同一文献。</li>
* </ol>
* <p>同组内按 id 升序取第一条为主记录 → 标记 {@code MERGED};
* 其余记录 → 标记 {@code MERGED_OUT} 并把 {@code merged_to_id} 指向主记录。
* 已 {@code MERGED_OUT} 的记录不参与再次聚同,因此任务可重复执行而结果稳定。</p>
*/ */
private void runMerge(GovernanceJob job) { private void runMerge(GovernanceJob job) {
List<Map<String, Object>> groups = findDuplicateGroups(); int[] counters = {0, 0}; // [0]=聚同组数, [1]=影响条数
int mergedGroups = 0; // 规则一:ISBN 相同(非空)→ 同一文献
int affected = 0; for (Map<String, Object> group : isbnDuplicateGroups()) {
for (Map<String, Object> group : groups) { Object isbn = group.get("isbn");
Object title = group.get("title");
Object author = group.get("author");
// 取出该组内仍「有效」的记录(排除已被合并的),按 id 升序
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>(); LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.eq(VersionResource::getTitle, title) query.eq(VersionResource::getIsbn, isbn)
.eq(author != null, VersionResource::getAuthor, author)
.isNull(author == null, VersionResource::getAuthor)
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode()) .ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode())
.orderByAsc(VersionResource::getId); .orderByAsc(VersionResource::getId);
List<VersionResource> list = resourceMapper.selectList(query); mergeGroup(resourceMapper.selectList(query), counters);
if (list.size() < 2) {
continue;
}
// 主记录:保留为「已聚同」
VersionResource master = list.get(0);
master.setGovernStatus(GovernStatus.MERGED.getCode());
master.setMergedToId(null);
resourceMapper.updateById(master);
affected++;
// 从记录:标记「已合并」并指向主记录
for (int i = 1; i < list.size(); i++) {
VersionResource slave = list.get(i);
slave.setGovernStatus(GovernStatus.MERGED_OUT.getCode());
slave.setMergedToId(master.getId());
resourceMapper.updateById(slave);
affected++;
}
mergedGroups++;
} }
job.setAffectedCount(affected); // 规则二:无 ISBN →「书名 + 作者 + 出版社 + 出版年份」完全一致 → 同一文献
for (Map<String, Object> group : fieldDuplicateGroups()) {
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
query.eq(VersionResource::getTitle, group.get("title"));
eqOrIsNull(query, VersionResource::getAuthor, group.get("author"));
eqOrIsNull(query, VersionResource::getPublisher, group.get("publisher"));
eqOrIsNull(query, VersionResource::getPublishYear, group.get("publish_year"));
query.and(x -> x.isNull(VersionResource::getIsbn).or().eq(VersionResource::getIsbn, ""))
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode())
.orderByAsc(VersionResource::getId);
mergeGroup(resourceMapper.selectList(query), counters);
}
job.setAffectedCount(counters[1]);
job.setResultSummary(String.format( job.setResultSummary(String.format(
"聚同 %d 组、影响 %d 条(组内 id 最小者保留为「已聚同」,其余标记「已合并」并指向主记录)", "聚同 %d 组、影响 %d 条(ISBN 相同,或无 ISBN 时「书名+作者+出版社+出版年份」"
mergedGroups, affected)); + "完全一致的记录聚合:组内 id 最小者保留为「已聚同」,其余标记「已合并」并指向主记录)",
counters[0], counters[1]));
}
/**
* 组内聚同:id 最小者为主记录(MERGED),其余标记 MERGED_OUT 并指向主记录。
*/
private void mergeGroup(List<VersionResource> list, int[] counters) {
if (list == null || list.size() < 2) {
return;
}
// 主记录:保留为「已聚同」
VersionResource master = list.get(0);
master.setGovernStatus(GovernStatus.MERGED.getCode());
master.setMergedToId(null);
resourceMapper.updateById(master);
counters[1]++;
// 从记录:标记「已合并」并指向主记录
for (int i = 1; i < list.size(); i++) {
VersionResource slave = list.get(i);
slave.setGovernStatus(GovernStatus.MERGED_OUT.getCode());
slave.setMergedToId(master.getId());
resourceMapper.updateById(slave);
counters[1]++;
}
counters[0]++;
}
/** 值为空时按 IS NULL 匹配,否则按等值匹配(分组键可能为 NULL 的字段用) */
private void eqOrIsNull(LambdaQueryWrapper<VersionResource> query,
SFunction<VersionResource, ?> column, Object value) {
if (value == null || "".equals(value)) {
query.isNull(column);
} else {
query.eq(column, value);
}
} }
// ==================== ② 优化 ==================== // ==================== ② 优化 ====================
@@ -224,16 +255,36 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
// ==================== 公共方法 ==================== // ==================== 公共方法 ====================
/** /**
* 查询「疑似同一文献」的重复组(题名 + 责任者 相同且多于 1 条)。 * 查询「疑似同一文献」的重复组 = ISBN 重复组 + 四要素重复组(聚同与「提示」共用)。
* 排除已被合并的记录,保证重复执行时不重复处理。 * 排除已被合并的记录,保证重复执行时不重复处理。
*/ */
private List<Map<String, Object>> findDuplicateGroups() { private List<Map<String, Object>> findDuplicateGroups() {
QueryWrapper<VersionResource> dupWrapper = new QueryWrapper<>(); List<Map<String, Object>> groups = new ArrayList<>(isbnDuplicateGroups());
dupWrapper.select("title", "author") groups.addAll(fieldDuplicateGroups());
.isNotNull("title") return groups;
}
/** ISBN 相同(非空)且多于 1 条的重复组 */
private List<Map<String, Object>> isbnDuplicateGroups() {
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.select("isbn")
.isNotNull("isbn")
.ne("isbn", "")
.ne("govern_status", GovernStatus.MERGED_OUT.getCode()) .ne("govern_status", GovernStatus.MERGED_OUT.getCode())
.groupBy("title", "author") .groupBy("isbn")
.having("COUNT(*) > 1"); .having("COUNT(*) > 1");
return resourceMapper.selectMaps(dupWrapper); return resourceMapper.selectMaps(wrapper);
}
/** 无 ISBN 时,「书名 + 作者 + 出版社 + 出版年份」完全一致且多于 1 条的重复组 */
private List<Map<String, Object>> fieldDuplicateGroups() {
QueryWrapper<VersionResource> wrapper = new QueryWrapper<>();
wrapper.select("title", "author", "publisher", "publish_year")
.isNotNull("title")
.and(x -> x.isNull("isbn").or().eq("isbn", ""))
.ne("govern_status", GovernStatus.MERGED_OUT.getCode())
.groupBy("title", "author", "publisher", "publish_year")
.having("COUNT(*) > 1");
return resourceMapper.selectMaps(wrapper);
} }
} }
@@ -18,7 +18,7 @@ import java.time.LocalDateTime;
@Schema(description = "版本资源元数据") @Schema(description = "版本资源元数据")
public class VersionResource implements Serializable { public class VersionResource implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
@Schema(description = "主键ID") @Schema(description = "主键ID")
private Long id; private Long id;
@@ -146,6 +146,9 @@ public class VersionResource implements Serializable {
@Schema(description = "是否特藏版本:0否 1是(是则展示在特藏推荐模块)") @Schema(description = "是否特藏版本:0否 1是(是则展示在特藏推荐模块)")
private Integer isSpecial; private Integer isSpecial;
@Schema(description = "管理状态:0正常 1屏蔽 2下架")
private Integer manageStatus;
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间") @Schema(description = "创建时间")
private LocalDateTime createTime; private LocalDateTime createTime;
@@ -19,7 +19,7 @@ import java.time.LocalDateTime;
@Schema(description = "检索行为日志") @Schema(description = "检索行为日志")
public class SearchLog implements Serializable { public class SearchLog implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@Schema(description = "检索关键词") @Schema(description = "检索关键词")
@@ -19,6 +19,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -123,12 +124,24 @@ public class SearchServiceImpl implements SearchService {
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) { private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) {
QueryWrapper<VersionResource> w = new QueryWrapper<>(); QueryWrapper<VersionResource> w = new QueryWrapper<>();
w.eq("deleted", 0); w.eq("deleted", 0);
// 后台处置过的记录不进检索(元数据与索引屏蔽/下架):0正常 1屏蔽 2下架
w.and(x -> x.isNull("manage_status").or().eq("manage_status", 0));
// 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者 // 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者
// 多词检索:空格分词,词与词之间 OR(命中任一词即返回)
if (StrUtil.isNotBlank(q.getKeyword())) { if (StrUtil.isNotBlank(q.getKeyword())) {
String kw = q.getKeyword().trim(); List<String> terms = splitTerms(q.getKeyword());
w.and(x -> x.like("title", kw).or().like("author", kw).or() w.and(x -> {
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw)); 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));
}
});
} }
applyMatch(w, "title", q.getTitle(), q.getMatchType()); applyMatch(w, "title", q.getTitle(), q.getMatchType());
@@ -157,19 +170,43 @@ public class SearchServiceImpl implements SearchService {
/** /**
* 多精度匹配:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊。 * 多精度匹配:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊。
*
* <p>多词检索:按空格分词,同一字段内词与词之间 OR(LIKE/LEFT/RIGHT 生效;
* EQ 为精确匹配语义,保持整串不拆分)。不同字段之间仍为 AND。</p>
*/ */
private void applyMatch(QueryWrapper<VersionResource> w, String column, String value, String matchType) { private void applyMatch(QueryWrapper<VersionResource> w, String column, String value, String matchType) {
if (StrUtil.isBlank(value)) { if (StrUtil.isBlank(value)) {
return; return;
} }
String v = value.trim();
String type = matchType == null ? "LIKE" : matchType.toUpperCase(); String type = matchType == null ? "LIKE" : matchType.toUpperCase();
switch (type) { if ("EQ".equals(type)) {
case "EQ" -> w.eq(column, v); w.eq(column, value.trim());
case "LEFT" -> w.likeRight(column, v); return;
case "RIGHT" -> w.likeLeft(column, v);
default -> w.like(column, v);
} }
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();
} }
/** /**
@@ -43,4 +43,7 @@ public class SpecialRecommendVO implements Serializable {
@Schema(description = "下载/电子版地址(special_resource.ebook_url,version_resource 场景取全文地址)") @Schema(description = "下载/电子版地址(special_resource.ebook_url,version_resource 场景取全文地址)")
private String ebookUrl; private String ebookUrl;
@Schema(description = "数据来源:VERSION=version_resource特藏标记 / MANUAL=special_resource手工维护")
private String source;
} }
@@ -21,7 +21,7 @@ import java.time.LocalDateTime;
@Schema(description = "特藏版本资源") @Schema(description = "特藏版本资源")
public class SpecialResource implements Serializable { public class SpecialResource implements Serializable {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.AUTO)
private Long id; private Long id;
@NotBlank(message = "特藏名称不能为空") @NotBlank(message = "特藏名称不能为空")
@@ -57,6 +57,7 @@ public class SpecialServiceImpl extends ServiceImpl<SpecialResourceMapper, Speci
vo.setFulltextUrl(r.getFulltextUrl()); vo.setFulltextUrl(r.getFulltextUrl());
// version_resource 无封面与电子版字段,下载地址用全文地址兜底 // version_resource 无封面与电子版字段,下载地址用全文地址兜底
vo.setEbookUrl(r.getFulltextUrl()); vo.setEbookUrl(r.getFulltextUrl());
vo.setSource("VERSION");
result.add(vo); result.add(vo);
}); });
} catch (Exception e) { } catch (Exception e) {
@@ -80,6 +81,7 @@ public class SpecialServiceImpl extends ServiceImpl<SpecialResourceMapper, Speci
vo.setNote(s.getSummary()); vo.setNote(s.getSummary());
vo.setCoverUrl(s.getCoverUrl()); vo.setCoverUrl(s.getCoverUrl());
vo.setEbookUrl(s.getEbookUrl()); vo.setEbookUrl(s.getEbookUrl());
vo.setSource("MANUAL");
result.add(vo); result.add(vo);
}); });
} }
+9 -3
View File
@@ -6,16 +6,22 @@ INSERT INTO version_resource
(id, process_no, title, clc_code, keywords, summary, publish_year, process_date, (id, process_no, title, clc_code, keywords, summary, publish_year, process_date,
content_form, media_type, format, page_count, language, submit_org, task_year, content_form, media_type, format, page_count, language, submit_org, task_year,
source_library, source_library_addr, fulltext_url, author, publisher, isbn, source_library, source_library_addr, fulltext_url, author, publisher, isbn,
govern_status, sensitive_flag, deleted) govern_status, sensitive_flag, is_special, deleted, note)
VALUES VALUES
(1, 'BB-2026-0001', '版本资源联合服务系统建设实践', 'G250.7', (1, 'BB-2026-0001', '版本资源联合服务系统建设实践', 'G250.7',
'版本资源;联合服务;元数据治理', '本书系统阐述了版本资源联合服务系统的建设思路、元数据标准与数据治理方法,涵盖数据采集、聚同优化、检索发现等关键环节,供军队院校图书馆协同建设参考。', '版本资源;联合服务;元数据治理', '本书系统阐述了版本资源联合服务系统的建设思路、元数据标准与数据治理方法,涵盖数据采集、聚同优化、检索发现等关键环节,供军队院校图书馆协同建设参考。',
'2026', '20261001', '文本', '纸质', 'PDF', '320', 'chi', '陆军步兵学院', '2026', '2026', '20261001', '文本', '纸质', 'PDF', '320', 'chi', '陆军步兵学院', '2026',
'陆军步兵学院图书馆', '10.0.0.11:8080', 'http://cdio.example.org/fulltext/BB-2026-0001', '陆军步兵学院图书馆', '10.0.0.11:8080', 'http://cdio.example.org/fulltext/BB-2026-0001',
'张三', '军事科学出版社', '978-7-80237-000-1', 'CLEANED', 0, 0), '张三', '军事科学出版社', '978-7-80237-000-1', 'CLEANED', 0, 1, 0,
'附注:本书为军队院校图书馆协同建设推荐特藏版本,附联合编目示例数据一套。'),
(2, 'BB-2026-0002', '军事理论元数据著录规范', 'E0-65', (2, 'BB-2026-0002', '军事理论元数据著录规范', 'E0-65',
'军事理论;元数据;著录规范', '本书依据国家与军队相关标准,规范军事理论类文献的元数据著录字段与格式,包含中图分类标引、主题词标引、摘要撰写等具体要求,适用于各馆联合编目工作。', '军事理论;元数据;著录规范', '本书依据国家与军队相关标准,规范军事理论类文献的元数据著录字段与格式,包含中图分类标引、主题词标引、摘要撰写等具体要求,适用于各馆联合编目工作。',
'2025', '20260915', '文本', '电子', 'PDF', '210', 'chi', '陆军步兵学院', '2026', '2025', '20260915', '文本', '电子', 'PDF', '210', 'chi', '陆军步兵学院', '2026',
'南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002', '南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002',
'李四', '国防大学出版社', '978-7-5626-000-2', 'MERGED', 0, 0); '李四', '国防大学出版社', '978-7-5626-000-2', 'MERGED', 0, 0, 0,
'附注:本规范另附著录样例四十二条,供各馆参考执行。');
-- 样例数据用显式 id 插入,需同步自增序列起点,避免后续新增主键冲突
SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource), 0), 1), true);
SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource), 0), 1), true);
+5 -5
View File
@@ -8,7 +8,7 @@
-- ---------------- 资源呈缴记录 ---------------- -- ---------------- 资源呈缴记录 ----------------
CREATE TABLE IF NOT EXISTS deposit_record CREATE TABLE IF NOT EXISTS deposit_record
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
org_name VARCHAR(256) NOT NULL, -- 呈缴单位名称 org_name VARCHAR(256) NOT NULL, -- 呈缴单位名称
contact VARCHAR(128), -- 联系人 contact VARCHAR(128), -- 联系人
phone VARCHAR(64), -- 联系方式 phone VARCHAR(64), -- 联系方式
@@ -31,7 +31,7 @@ CREATE INDEX IF NOT EXISTS idx_dr_org ON deposit_record (org_name);
-- ---------------- 特藏版本资源 ---------------- -- ---------------- 特藏版本资源 ----------------
CREATE TABLE IF NOT EXISTS special_resource CREATE TABLE IF NOT EXISTS special_resource
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR(256) NOT NULL, -- 特藏名称 name VARCHAR(256) NOT NULL, -- 特藏名称
summary TEXT, -- 简介 summary TEXT, -- 简介
category VARCHAR(128), -- 类别 category VARCHAR(128), -- 类别
@@ -48,7 +48,7 @@ CREATE INDEX IF NOT EXISTS idx_sr_status ON special_resource (status);
-- ---------------- 数据采集任务 ---------------- -- ---------------- 数据采集任务 ----------------
CREATE TABLE IF NOT EXISTS collect_task CREATE TABLE IF NOT EXISTS collect_task
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
library_code VARCHAR(64) NOT NULL, -- 单位编码 library_code VARCHAR(64) NOT NULL, -- 单位编码
library_name VARCHAR(256), -- 单位名称 library_name VARCHAR(256), -- 单位名称
source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API source_type VARCHAR(64), -- 数据源类型:MARC/EXCEL/DB/API
@@ -68,7 +68,7 @@ CREATE INDEX IF NOT EXISTS idx_ct_status ON collect_task (status);
-- ---------------- 数据治理任务 ---------------- -- ---------------- 数据治理任务 ----------------
CREATE TABLE IF NOT EXISTS governance_job CREATE TABLE IF NOT EXISTS governance_job
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
job_type VARCHAR(32) NOT NULL, -- MERGE/OPTIMIZE/HINT/PURIFY job_type VARCHAR(32) NOT NULL, -- MERGE/OPTIMIZE/HINT/PURIFY
status VARCHAR(32) DEFAULT 'PENDING', -- PENDING/RUNNING/SUCCESS/FAILED status VARCHAR(32) DEFAULT 'PENDING', -- PENDING/RUNNING/SUCCESS/FAILED
affected_count INTEGER DEFAULT 0, -- 影响记录数 affected_count INTEGER DEFAULT 0, -- 影响记录数
@@ -84,7 +84,7 @@ CREATE INDEX IF NOT EXISTS idx_gj_type ON governance_job (job_type);
-- ---------------- 检索行为日志 ---------------- -- ---------------- 检索行为日志 ----------------
CREATE TABLE IF NOT EXISTS search_log CREATE TABLE IF NOT EXISTS search_log
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
keyword VARCHAR(512), keyword VARCHAR(512),
user_ip VARCHAR(64), user_ip VARCHAR(64),
source_library VARCHAR(256), source_library VARCHAR(256),
+1 -1
View File
@@ -6,7 +6,7 @@
CREATE TABLE IF NOT EXISTS sys_user CREATE TABLE IF NOT EXISTS sys_user
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
username VARCHAR(64) NOT NULL, -- 登录账号 username VARCHAR(64) NOT NULL, -- 登录账号
password VARCHAR(128) NOT NULL, -- BCrypt 加密后的密码 password VARCHAR(128) NOT NULL, -- BCrypt 加密后的密码
real_name VARCHAR(128), -- 姓名 real_name VARCHAR(128), -- 姓名
@@ -0,0 +1,24 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v5)
-- 新增「是否特藏版本」标记字段
--
-- 背景:特藏推荐模块改为直接查询 version_resource,
-- 需要一个标记字段标识该资源是否为特藏版本:
-- 0 否(默认)
-- 1 是(展示在「特藏推荐」模块)
-- 标记由「资源管理」模块的编辑入口维护。
--
-- 幂等:全部使用 IF NOT EXISTS,可重复执行
-- =====================================================================
-- 1. 新增字段
ALTER TABLE version_resource ADD COLUMN IF NOT EXISTS is_special SMALLINT DEFAULT 0;
-- 2. 补齐空值
UPDATE version_resource SET is_special = 0 WHERE is_special IS NULL;
-- 3. 字段说明
COMMENT ON COLUMN version_resource.is_special IS '是否特藏版本:0否 1是(是则展示在特藏推荐模块)';
-- 4. 索引
CREATE INDEX IF NOT EXISTS idx_vr_is_special ON version_resource (is_special);
@@ -0,0 +1,64 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v6)
-- 新增「敏感词库」表 sensitive_word
--
-- 用途:集中维护敏感词及其拼音,供数据治理「提纯」环节
-- 对 version_resource 的题名/摘要/主题词等文本做敏感词比对,
-- 命中后将该记录 sensitive_flag 置为 1。
--
-- 幂等:全部使用 IF NOT EXISTS,可重复执行
-- =====================================================================
-- 1. 建表
CREATE TABLE IF NOT EXISTS sensitive_word
(
id BIGINT NOT NULL PRIMARY KEY,
word VARCHAR(128) NOT NULL, -- 敏感词(中文)
pinyin VARCHAR(256), -- 敏感词拼音
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
-- 2. 索引:未删除记录中敏感词唯一
CREATE UNIQUE INDEX IF NOT EXISTS uk_sw_word ON sensitive_word (word) WHERE deleted = 0;
CREATE INDEX IF NOT EXISTS idx_sw_pinyin ON sensitive_word (pinyin);
-- 3. 说明
COMMENT ON TABLE sensitive_word IS '敏感词库表';
COMMENT ON COLUMN sensitive_word.word IS '敏感词(中文)';
COMMENT ON COLUMN sensitive_word.pinyin IS '敏感词拼音';
COMMENT ON COLUMN sensitive_word.deleted IS '逻辑删除:0未删 1已删';
-- 4. 版本资源新增「管理状态」字段(后台管理:屏蔽/下架处置用)
-- 0 正常 / 1 屏蔽(检索与索引中隐藏)/ 2 下架
ALTER TABLE version_resource ADD COLUMN IF NOT EXISTS manage_status SMALLINT DEFAULT 0;
UPDATE version_resource SET manage_status = 0 WHERE manage_status IS NULL;
COMMENT ON COLUMN version_resource.manage_status IS '管理状态:0正常 1屏蔽 2下架';
CREATE INDEX IF NOT EXISTS idx_vr_manage_status ON version_resource (manage_status);
-- 5. 院校资源节点表(后台管理:资源节点与访问链接维护)
CREATE TABLE IF NOT EXISTS resource_node
(
id BIGINT NOT NULL PRIMARY KEY,
name VARCHAR(256) NOT NULL, -- 资源节点名称
node_type VARCHAR(64), -- 资源类型
category VARCHAR(128), -- 类别归属
link_url VARCHAR(1024), -- 访问链接
sort_no INT DEFAULT 0, -- 展示顺序(小在前)
status SMALLINT DEFAULT 1, -- 状态 1启用 0停用
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE INDEX IF NOT EXISTS idx_rn_sort ON resource_node (sort_no);
CREATE INDEX IF NOT EXISTS idx_rn_category ON resource_node (category);
COMMENT ON TABLE resource_node IS '院校资源节点表(资源节点与访问链接管理)';
COMMENT ON COLUMN resource_node.node_type IS '资源类型';
COMMENT ON COLUMN resource_node.category IS '类别归属';
COMMENT ON COLUMN resource_node.link_url IS '访问链接';
COMMENT ON COLUMN resource_node.sort_no IS '展示顺序,数值小的靠前';
COMMENT ON COLUMN resource_node.status IS '状态:1启用 0停用';
COMMENT ON COLUMN resource_node.deleted IS '逻辑删除:0未删 1已删';
@@ -0,0 +1,62 @@
-- =====================================================================
-- 版本资源联合服务系统 - 扩展表结构(v7)
-- 主键改为「数据库自增序列」,废弃雪花 ID(IdType.ASSIGN_ID)
--
-- 背景:雪花 ID 为 19 位(如 2112722202279440385),
-- 超过 JS Number 安全整数上限 9007199254740991,
-- 前端拿到的 id 会发生精度丢失(…440385 变成 …440400),
-- 导致「查询单个资源 / 回填 / 编辑保存」时 id 对不上。
-- 改为序列自增后,id 为 1、2、3… 连续小整数,前端不再失真。
--
-- 幂等:全部使用 IF NOT EXISTS,可重复执行
-- =====================================================================
-- 1. 为各表创建序列并设为主键默认值
CREATE SEQUENCE IF NOT EXISTS version_resource_id_seq;
ALTER TABLE version_resource ALTER COLUMN id SET DEFAULT nextval('version_resource_id_seq');
CREATE SEQUENCE IF NOT EXISTS special_resource_id_seq;
ALTER TABLE special_resource ALTER COLUMN id SET DEFAULT nextval('special_resource_id_seq');
CREATE SEQUENCE IF NOT EXISTS sensitive_word_id_seq;
ALTER TABLE sensitive_word ALTER COLUMN id SET DEFAULT nextval('sensitive_word_id_seq');
CREATE SEQUENCE IF NOT EXISTS resource_node_id_seq;
ALTER TABLE resource_node ALTER COLUMN id SET DEFAULT nextval('resource_node_id_seq');
CREATE SEQUENCE IF NOT EXISTS governance_job_id_seq;
ALTER TABLE governance_job ALTER COLUMN id SET DEFAULT nextval('governance_job_id_seq');
CREATE SEQUENCE IF NOT EXISTS search_log_id_seq;
ALTER TABLE search_log ALTER COLUMN id SET DEFAULT nextval('search_log_id_seq');
CREATE SEQUENCE IF NOT EXISTS collect_task_id_seq;
ALTER TABLE collect_task ALTER COLUMN id SET DEFAULT nextval('collect_task_id_seq');
CREATE SEQUENCE IF NOT EXISTS deposit_record_id_seq;
ALTER TABLE deposit_record ALTER COLUMN id SET DEFAULT nextval('deposit_record_id_seq');
CREATE SEQUENCE IF NOT EXISTS sys_user_id_seq;
ALTER TABLE sys_user ALTER COLUMN id SET DEFAULT nextval('sys_user_id_seq');
-- 2. 序列起点对齐现有「小整数」主键,避免与已有数据冲突
SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource WHERE id < 1000000000), 0), 1), true);
SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource WHERE id < 1000000000), 0), 1), true);
SELECT setval('sensitive_word_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM sensitive_word WHERE id < 1000000000), 0), 1), true);
SELECT setval('resource_node_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM resource_node WHERE id < 1000000000), 0), 1), true);
SELECT setval('governance_job_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM governance_job WHERE id < 1000000000), 0), 1), true);
SELECT setval('search_log_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM search_log WHERE id < 1000000000), 0), 1), true);
SELECT setval('collect_task_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM collect_task WHERE id < 1000000000), 0), 1), true);
SELECT setval('deposit_record_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM deposit_record WHERE id < 1000000000), 0), 1), true);
SELECT setval('sys_user_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM sys_user WHERE id < 1000000000), 0), 1), true);
-- 3. 把历史上生成的超大雪花 ID 重编为连续小 ID(数据内容不变)
UPDATE version_resource SET id = nextval('version_resource_id_seq') WHERE id > 1000000000;
UPDATE special_resource SET id = nextval('special_resource_id_seq') WHERE id > 1000000000;
UPDATE sensitive_word SET id = nextval('sensitive_word_id_seq') WHERE id > 1000000000;
UPDATE resource_node SET id = nextval('resource_node_id_seq') WHERE id > 1000000000;
UPDATE governance_job SET id = nextval('governance_job_id_seq') WHERE id > 1000000000;
UPDATE search_log SET id = nextval('search_log_id_seq') WHERE id > 1000000000;
UPDATE collect_task SET id = nextval('collect_task_id_seq') WHERE id > 1000000000;
UPDATE deposit_record SET id = nextval('deposit_record_id_seq') WHERE id > 1000000000;
UPDATE sys_user SET id = nextval('sys_user_id_seq') WHERE id > 1000000000;
+56 -1
View File
@@ -6,7 +6,7 @@
CREATE TABLE IF NOT EXISTS version_resource CREATE TABLE IF NOT EXISTS version_resource
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
-- ==================== 必备字段 ==================== -- ==================== 必备字段 ====================
process_no VARCHAR(128), -- 加工编号(必备) process_no VARCHAR(128), -- 加工编号(必备)
@@ -49,6 +49,8 @@ CREATE TABLE IF NOT EXISTS version_resource
merged_to_id BIGINT, -- 聚同后指向的主记录ID merged_to_id BIGINT, -- 聚同后指向的主记录ID
abnormal_flag SMALLINT DEFAULT 0, -- 疑似错漏 0正常 1疑似 abnormal_flag SMALLINT DEFAULT 0, -- 疑似错漏 0正常 1疑似
sensitive_flag SMALLINT DEFAULT 0, -- 敏感标记 0正常 1敏感 sensitive_flag SMALLINT DEFAULT 0, -- 敏感标记 0正常 1敏感
is_special SMALLINT DEFAULT 0, -- 是否特藏版本 0否 1是
manage_status SMALLINT DEFAULT 0, -- 管理状态 0正常 1屏蔽 2下架
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删 deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
@@ -62,9 +64,62 @@ CREATE INDEX IF NOT EXISTS idx_vr_media_type ON version_resource (media_type);
CREATE INDEX IF NOT EXISTS idx_vr_source_lib ON version_resource (source_library); CREATE INDEX IF NOT EXISTS idx_vr_source_lib ON version_resource (source_library);
CREATE INDEX IF NOT EXISTS idx_vr_publish_year ON version_resource (publish_year); CREATE INDEX IF NOT EXISTS idx_vr_publish_year ON version_resource (publish_year);
CREATE INDEX IF NOT EXISTS idx_vr_cdoi ON version_resource (cdoi); CREATE INDEX IF NOT EXISTS idx_vr_cdoi ON version_resource (cdoi);
CREATE INDEX IF NOT EXISTS idx_vr_manage_status ON version_resource (manage_status);
COMMENT ON TABLE version_resource IS '版本资源元数据表'; COMMENT ON TABLE version_resource IS '版本资源元数据表';
COMMENT ON COLUMN version_resource.media_type IS '媒体类型:纸质/电子'; COMMENT ON COLUMN version_resource.media_type IS '媒体类型:纸质/电子';
COMMENT ON COLUMN version_resource.govern_status IS '数据治理状态:RAW原始/MERGED已聚同/OPTIMIZED已优化/FINAL已提纯/MERGED_OUT已合并'; COMMENT ON COLUMN version_resource.govern_status IS '数据治理状态:RAW原始/MERGED已聚同/OPTIMIZED已优化/FINAL已提纯/MERGED_OUT已合并';
COMMENT ON COLUMN version_resource.merged_to_id IS '聚同后指向的主记录ID'; COMMENT ON COLUMN version_resource.merged_to_id IS '聚同后指向的主记录ID';
COMMENT ON COLUMN version_resource.abnormal_flag IS '疑似错漏标记:0正常 1疑似'; COMMENT ON COLUMN version_resource.abnormal_flag IS '疑似错漏标记:0正常 1疑似';
COMMENT ON COLUMN version_resource.is_special IS '是否特藏版本:0否 1是(是则展示在特藏推荐模块)';
-- =====================================================================
-- 敏感词库
-- 供数据治理「提纯」环节做敏感词比对,命中后 sensitive_flag 置 1
-- =====================================================================
CREATE TABLE IF NOT EXISTS sensitive_word
(
id BIGSERIAL NOT NULL PRIMARY KEY,
word VARCHAR(128) NOT NULL, -- 敏感词(中文)
pinyin VARCHAR(256), -- 敏感词拼音
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE UNIQUE INDEX IF NOT EXISTS uk_sw_word ON sensitive_word (word) WHERE deleted = 0;
CREATE INDEX IF NOT EXISTS idx_sw_pinyin ON sensitive_word (pinyin);
COMMENT ON TABLE sensitive_word IS '敏感词库表';
COMMENT ON COLUMN sensitive_word.word IS '敏感词(中文)';
COMMENT ON COLUMN sensitive_word.pinyin IS '敏感词拼音';
COMMENT ON COLUMN sensitive_word.deleted IS '逻辑删除:0未删 1已删';
-- =====================================================================
-- 院校资源节点
-- 后台管理:资源节点与访问链接的增删改、展示顺序与类别归属控制
-- =====================================================================
CREATE TABLE IF NOT EXISTS resource_node
(
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR(256) NOT NULL, -- 资源节点名称
node_type VARCHAR(64), -- 资源类型
category VARCHAR(128), -- 类别归属
link_url VARCHAR(1024), -- 访问链接
sort_no INT DEFAULT 0, -- 展示顺序(小在前)
status SMALLINT DEFAULT 1, -- 状态 1启用 0停用
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE INDEX IF NOT EXISTS idx_rn_sort ON resource_node (sort_no);
CREATE INDEX IF NOT EXISTS idx_rn_category ON resource_node (category);
COMMENT ON TABLE resource_node IS '院校资源节点表(资源节点与访问链接管理)';
COMMENT ON COLUMN resource_node.node_type IS '资源类型';
COMMENT ON COLUMN resource_node.category IS '类别归属';
COMMENT ON COLUMN resource_node.link_url IS '访问链接';
COMMENT ON COLUMN resource_node.sort_no IS '展示顺序,数值小的靠前';
COMMENT ON COLUMN resource_node.status IS '状态:1启用 0停用';
COMMENT ON COLUMN resource_node.deleted IS '逻辑删除:0未删 1已删';
+39 -1
View File
@@ -5,7 +5,7 @@
CREATE TABLE IF NOT EXISTS version_resource CREATE TABLE IF NOT EXISTS version_resource
( (
id BIGINT NOT NULL PRIMARY KEY, id BIGSERIAL NOT NULL PRIMARY KEY,
-- 必备字段 -- 必备字段
process_no VARCHAR(128), process_no VARCHAR(128),
@@ -46,6 +46,8 @@ CREATE TABLE IF NOT EXISTS version_resource
-- 治理与系统字段 -- 治理与系统字段
govern_status VARCHAR(32) DEFAULT 'RAW', govern_status VARCHAR(32) DEFAULT 'RAW',
sensitive_flag SMALLINT DEFAULT 0, sensitive_flag SMALLINT DEFAULT 0,
manage_status SMALLINT DEFAULT 0,
is_special SMALLINT DEFAULT 0,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 deleted SMALLINT DEFAULT 0
@@ -58,6 +60,38 @@ CREATE INDEX IF NOT EXISTS idx_vr_media_type ON version_resource (media_type);
CREATE INDEX IF NOT EXISTS idx_vr_source_lib ON version_resource (source_library); CREATE INDEX IF NOT EXISTS idx_vr_source_lib ON version_resource (source_library);
CREATE INDEX IF NOT EXISTS idx_vr_publish_year ON version_resource (publish_year); CREATE INDEX IF NOT EXISTS idx_vr_publish_year ON version_resource (publish_year);
-- 敏感词库
CREATE TABLE IF NOT EXISTS sensitive_word
(
id BIGSERIAL NOT NULL PRIMARY KEY,
word VARCHAR(128) NOT NULL, -- 敏感词(中文)
pinyin VARCHAR(256), -- 敏感词拼音
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE UNIQUE INDEX IF NOT EXISTS uk_sw_word ON sensitive_word (word) WHERE deleted = 0;
CREATE INDEX IF NOT EXISTS idx_sw_pinyin ON sensitive_word (pinyin);
-- 院校资源节点
CREATE TABLE IF NOT EXISTS resource_node
(
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR(256) NOT NULL, -- 资源节点名称
node_type VARCHAR(64), -- 资源类型
category VARCHAR(128), -- 类别归属
link_url VARCHAR(1024), -- 访问链接
sort_no INT DEFAULT 0, -- 展示顺序(小在前)
status SMALLINT DEFAULT 1, -- 状态 1启用 0停用
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted SMALLINT DEFAULT 0 -- 逻辑删除 0未删 1已删
);
CREATE INDEX IF NOT EXISTS idx_rn_sort ON resource_node (sort_no);
CREATE INDEX IF NOT EXISTS idx_rn_category ON resource_node (category);
-- 样例数据 -- 样例数据
INSERT INTO version_resource INSERT INTO version_resource
(id, process_no, title, clc_code, keywords, summary, publish_year, process_date, (id, process_no, title, clc_code, keywords, summary, publish_year, process_date,
@@ -76,3 +110,7 @@ VALUES
'南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002', '南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002',
'李四', '国防大学出版社', '978-7-5626-000-2', 'MERGED', 0, 0) '李四', '国防大学出版社', '978-7-5626-000-2', 'MERGED', 0, 0)
ON CONFLICT (id) DO NOTHING; ON CONFLICT (id) DO NOTHING;
-- 同步自增序列起点,避免与样例数据主键冲突
SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource), 0), 1), true);
SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource), 0), 1), true);
+117
View File
@@ -0,0 +1,117 @@
import request from './request'
import type { PageResult } from './types'
// ==================== 敏感词库 ====================
export interface SensitiveWord {
id?: number
/** 敏感词(中文) */
word: string
/** 敏感词拼音 */
pinyin?: string
createTime?: string
updateTime?: string
}
/** 分页查询敏感词 */
export function pageSensitiveWords(params: { current: number; size: number; keyword?: string }) {
return request.get<never, PageResult<SensitiveWord>>('/admin/sensitive-words/page', { params })
}
/** 新增敏感词 */
export function createSensitiveWord(data: SensitiveWord) {
return request.post<never, void>('/admin/sensitive-words', data)
}
/** 更新敏感词 */
export function updateSensitiveWord(id: number, data: SensitiveWord) {
return request.put<never, void>(`/admin/sensitive-words/${id}`, data)
}
/** 删除敏感词(单条) */
export function removeSensitiveWord(id: number) {
return request.delete<never, void>(`/admin/sensitive-words/${id}`)
}
/** 批量删除敏感词 */
export function batchRemoveSensitiveWords(ids: number[]) {
return request.post<never, void>('/admin/sensitive-words/batch-delete', ids)
}
// ==================== 敏感词命中处置 ====================
export interface SensitiveHit {
id: number
title?: string
author?: string
sourceLibrary?: string
mediaType?: string
governStatus?: string
/** 0正常 1敏感 */
sensitiveFlag?: number
/** 0正常 1屏蔽 2下架 */
manageStatus?: number
matchedWords: string[]
}
export type HitAction = 'MASK' | 'OFFLINE' | 'RESTORE' | 'DELETE'
/** 敏感词命中扫描 */
export function pageHits(params: { current: number; size: number }) {
return request.get<never, PageResult<SensitiveHit>>('/admin/sensitive-words/hits', { params })
}
/** 命中处置(支持单条与批量) */
export function handleHitAction(ids: number[], action: HitAction) {
return request.post<never, number>('/admin/sensitive-words/hits/action', { ids, action })
}
// ==================== 院校资源节点 ====================
export interface ResourceNode {
id?: number
/** 资源节点名称 */
name: string
/** 资源类型 */
nodeType?: string
/** 类别归属 */
category?: string
/** 访问链接 */
linkUrl?: string
/** 展示顺序,数值小的靠前 */
sortNo?: number
/** 1启用 0停用 */
status?: number
}
/** 资源节点全量列表 */
export function listResourceNodes() {
return request.get<never, ResourceNode[]>('/admin/resource-nodes/list')
}
/** 新增资源节点 */
export function createResourceNode(data: ResourceNode) {
return request.post<never, void>('/admin/resource-nodes', data)
}
/** 更新资源节点 */
export function updateResourceNode(id: number, data: ResourceNode) {
return request.put<never, void>(`/admin/resource-nodes/${id}`, data)
}
/** 删除资源节点(单条) */
export function removeResourceNode(id: number) {
return request.delete<never, void>(`/admin/resource-nodes/${id}`)
}
/** 批量删除资源节点 */
export function batchRemoveResourceNodes(ids: number[]) {
return request.post<never, void>('/admin/resource-nodes/batch-delete', ids)
}
/** 版本资源分组统计 */
export function resourceStats(dim: 'sourceLibrary' | 'mediaType' | 'title', limit = 20) {
return request.get<never, { name: string; count: number }[]>('/admin/resource-nodes/stats', {
params: { dim, limit },
})
}
+2
View File
@@ -23,6 +23,8 @@ export interface SpecialRecommendItem {
fulltextUrl?: string fulltextUrl?: string
/** 电子版地址(special_resource.ebook_url) */ /** 电子版地址(special_resource.ebook_url) */
ebookUrl?: string ebookUrl?: string
/** 数据来源:VERSION=version_resource特藏标记 / MANUAL=special_resource手工维护 */
source?: 'VERSION' | 'MANUAL'
} }
/** 特藏推荐列表 */ /** 特藏推荐列表 */
+6 -1
View File
@@ -27,6 +27,11 @@ function logout() {
clearAuth() clearAuth()
router.push('/login') router.push('/login')
} }
/** 齿轮按钮:新标签页打开后台管理 */
function openAdmin() {
window.open(router.resolve('/admin').href, '_blank')
}
</script> </script>
<template> <template>
@@ -51,7 +56,7 @@ function logout() {
</nav> </nav>
<div class="right"> <div class="right">
<img class="hicon" :src="noticeUrl" alt="notice" /> <img class="hicon" :src="noticeUrl" alt="notice" />
<img class="hicon" :src="settingUrl" alt="setting" /> <img class="hicon" :src="settingUrl" alt="setting" title="后台管理" @click="openAdmin" />
<img class="avatar" :src="avatarUrl" alt="avatar" /> <img class="avatar" :src="avatarUrl" alt="avatar" />
<span class="user">{{ user?.realName || 'admin' }}</span> <span class="user">{{ user?.realName || 'admin' }}</span>
<a class="quit" @click="logout">退出登录</a> <a class="quit" @click="logout">退出登录</a>
+6
View File
@@ -71,6 +71,12 @@ const routes: RouteRecordRaw[] = [
name: 'Analysis', name: 'Analysis',
component: () => import('@/views/analysis/AnalysisView.vue'), component: () => import('@/views/analysis/AnalysisView.vue'),
meta: { title: '统计分析', icon: 'DataAnalysis' } meta: { title: '统计分析', icon: 'DataAnalysis' }
},
{
path: 'admin',
name: 'Admin',
component: () => import('@/views/admin/AdminView.vue'),
meta: { title: '后台管理' }
} }
] ]
}, },
+12 -1
View File
@@ -98,8 +98,19 @@ function resume() {
reset() reset()
} }
/** 主页途径 → 检索页途径命名映射 */
const fieldToSearchField: Record<string, string> = {
题名: '题名',
关键词: '关键词',
作者: '责任者',
出版机构: '出版社'
}
function doSearch() { function doSearch() {
router.push({ path: '/search', query: { keyword: keyword.value } }) router.push({
path: '/search',
query: { keyword: keyword.value, field: fieldToSearchField[field.value] || '综合' }
})
} }
onMounted(() => { onMounted(() => {
+613
View File
@@ -0,0 +1,613 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const activeTab = ref('words')
import {
batchRemoveResourceNodes,
batchRemoveSensitiveWords,
createResourceNode,
createSensitiveWord,
handleHitAction,
listResourceNodes,
pageHits,
pageSensitiveWords,
removeResourceNode,
removeSensitiveWord,
resourceStats,
updateResourceNode,
updateSensitiveWord,
type HitAction,
type ResourceNode,
type SensitiveHit,
type SensitiveWord,
} from '@/api/admin'
// ==================== 敏感词库 ====================
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
const wordList = ref<SensitiveWord[]>([])
const wordTotal = ref(0)
const wordLoading = ref(false)
const wordSelection = ref<SensitiveWord[]>([])
const wordDialog = ref(false)
const wordSaving = ref(false)
const wordForm = reactive<{ id?: number; word: string; pinyin: string }>({ word: '', pinyin: '' })
async function fetchWords() {
wordLoading.value = true
try {
const page = await pageSensitiveWords({
current: wordQuery.current,
size: wordQuery.size,
keyword: wordQuery.keyword || undefined,
})
wordList.value = page.records
wordTotal.value = page.total
} finally {
wordLoading.value = false
}
}
function searchWords() {
wordQuery.current = 1
fetchWords()
}
function openWordCreate() {
wordForm.id = undefined
wordForm.word = ''
wordForm.pinyin = ''
wordDialog.value = true
}
function openWordEdit(row: SensitiveWord) {
wordForm.id = row.id
wordForm.word = row.word
wordForm.pinyin = row.pinyin || ''
wordDialog.value = true
}
async function saveWord() {
if (!wordForm.word.trim()) {
ElMessage.warning('请输入敏感词')
return
}
wordSaving.value = true
try {
const data = { word: wordForm.word.trim(), pinyin: wordForm.pinyin.trim() || undefined }
if (wordForm.id) {
await updateSensitiveWord(wordForm.id, data)
} else {
await createSensitiveWord(data)
}
ElMessage.success('保存成功')
wordDialog.value = false
fetchWords()
} finally {
wordSaving.value = false
}
}
async function deleteWord(row: SensitiveWord) {
await ElMessageBox.confirm(`确认删除敏感词「${row.word}」?`, '提示', { type: 'warning' })
await removeSensitiveWord(row.id!)
ElMessage.success('删除成功')
fetchWords()
}
async function batchDeleteWords() {
const ids = wordSelection.value.map((r) => r.id!)
if (!ids.length) {
ElMessage.warning('请先勾选要删除的敏感词')
return
}
await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 个敏感词?`, '提示', { type: 'warning' })
await batchRemoveSensitiveWords(ids)
ElMessage.success('批量删除成功')
fetchWords()
}
// ==================== 敏感词命中处置 ====================
const hitQuery = reactive({ current: 1, size: 10 })
const hitList = ref<SensitiveHit[]>([])
const hitTotal = ref(0)
const hitLoading = ref(false)
const hitSelection = ref<SensitiveHit[]>([])
const manageStatusText: Record<number, string> = { 0: '正常', 1: '已屏蔽', 2: '已下架' }
const manageStatusTag: Record<number, 'success' | 'warning' | 'danger'> = {
0: 'success',
1: 'danger',
2: 'warning',
}
async function fetchHits() {
hitLoading.value = true
try {
const page = await pageHits({ current: hitQuery.current, size: hitQuery.size })
hitList.value = page.records
hitTotal.value = page.total
} finally {
hitLoading.value = false
}
}
async function doHitAction(ids: number[], action: HitAction, label: string) {
const count = await handleHitAction(ids, action)
ElMessage.success(`${label}成功,共 ${count} 条`)
fetchHits()
}
async function handleHit(row: SensitiveHit, action: HitAction, label: string) {
if (action === 'DELETE') {
await ElMessageBox.confirm(`确认删除「${row.title}」?删除后不可恢复。`, '提示', { type: 'warning' })
}
await doHitAction([row.id], action, label)
}
async function batchHit(action: HitAction, label: string) {
const ids = hitSelection.value.map((r) => r.id)
if (!ids.length) {
ElMessage.warning('请先勾选要处置的记录')
return
}
if (action === 'DELETE') {
await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录?删除后不可恢复。`, '提示', {
type: 'warning',
})
}
await doHitAction(ids, action, `批量${label}`)
}
// ==================== 院校资源库 ====================
const nodeLoading = ref(false)
const nodeList = ref<ResourceNode[]>([])
const nodeSelection = ref<ResourceNode[]>([])
const nodeDialog = ref(false)
const nodeSaving = ref(false)
const nodeForm = reactive<{
id?: number
name: string
nodeType: string
category: string
linkUrl: string
sortNo: number
status: number
}>({ name: '', nodeType: '', category: '', linkUrl: '', sortNo: 0, status: 1 })
const statDim = ref<'sourceLibrary' | 'mediaType' | 'title'>('sourceLibrary')
const statLoading = ref(false)
const statList = ref<{ name: string; count: number }[]>([])
const statDims = [
{ value: 'sourceLibrary', label: '按来源院校' },
{ value: 'mediaType', label: '按资源类型' },
{ value: 'title', label: '按资源名称' },
] as const
async function fetchNodes() {
nodeLoading.value = true
try {
nodeList.value = await listResourceNodes()
} finally {
nodeLoading.value = false
}
}
async function fetchStats() {
statLoading.value = true
try {
statList.value = await resourceStats(statDim.value, 50)
} finally {
statLoading.value = false
}
}
function openNodeCreate() {
Object.assign(nodeForm, { id: undefined, name: '', nodeType: '', category: '', linkUrl: '', sortNo: 0, status: 1 })
nodeDialog.value = true
}
function openNodeEdit(row: ResourceNode) {
Object.assign(nodeForm, {
id: row.id,
name: row.name,
nodeType: row.nodeType || '',
category: row.category || '',
linkUrl: row.linkUrl || '',
sortNo: row.sortNo ?? 0,
status: row.status ?? 1,
})
nodeDialog.value = true
}
async function saveNode() {
if (!nodeForm.name.trim()) {
ElMessage.warning('请输入资源节点名称')
return
}
nodeSaving.value = true
try {
const data: ResourceNode = {
name: nodeForm.name.trim(),
nodeType: nodeForm.nodeType.trim() || undefined,
category: nodeForm.category.trim() || undefined,
linkUrl: nodeForm.linkUrl.trim() || undefined,
sortNo: nodeForm.sortNo,
status: nodeForm.status,
}
if (nodeForm.id) {
await updateResourceNode(nodeForm.id, data)
} else {
await createResourceNode(data)
}
ElMessage.success('保存成功')
nodeDialog.value = false
fetchNodes()
} finally {
nodeSaving.value = false
}
}
async function deleteNode(row: ResourceNode) {
await ElMessageBox.confirm(`确认删除资源节点「${row.name}」?`, '提示', { type: 'warning' })
await removeResourceNode(row.id!)
ElMessage.success('删除成功')
fetchNodes()
}
async function batchDeleteNodes() {
const ids = nodeSelection.value.map((r) => r.id!)
if (!ids.length) {
ElMessage.warning('请先勾选要删除的资源节点')
return
}
await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 个资源节点?`, '提示', { type: 'warning' })
await batchRemoveResourceNodes(ids)
ElMessage.success('批量删除成功')
fetchNodes()
}
onMounted(() => {
fetchWords()
fetchHits()
fetchNodes()
fetchStats()
})
</script>
<template>
<div class="admin-page">
<h2 class="page-title">后台管理</h2>
<el-tabs v-model="activeTab" class="admin-tabs">
<!-- ==================== 敏感词库 ==================== -->
<el-tab-pane label="敏感词库" name="words">
<div class="toolbar">
<el-input
v-model="wordQuery.keyword"
placeholder="按敏感词 / 拼音搜索"
clearable
style="width: 240px"
@keyup.enter="searchWords"
@clear="searchWords"
/>
<el-button type="primary" @click="searchWords">查询</el-button>
<el-button type="success" @click="openWordCreate">新增敏感词</el-button>
<el-button type="danger" plain :disabled="!wordSelection.length" @click="batchDeleteWords">
批量删除
</el-button>
</div>
<el-table
v-loading="wordLoading"
:data="wordList"
border
stripe
@selection-change="(rows: SensitiveWord[]) => (wordSelection = rows)"
>
<el-table-column type="selection" width="45" />
<el-table-column prop="word" label="敏感词(中文)" min-width="180" />
<el-table-column prop="pinyin" label="拼音" min-width="160" />
<el-table-column prop="createTime" label="创建时间" width="180" />
<el-table-column label="操作" width="140" fixed="right">
<template #default="{ row }">
<el-button link type="primary" size="small" @click="openWordEdit(row)">编辑</el-button>
<el-button link type="danger" size="small" @click="deleteWord(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
class="pager"
background
layout="total, sizes, prev, pager, next, jumper"
:total="wordTotal"
v-model:current-page="wordQuery.current"
v-model:page-size="wordQuery.size"
:page-sizes="[10, 20, 50, 100]"
@current-change="fetchWords"
@size-change="fetchWords"
/>
</el-tab-pane>
<!-- ==================== 敏感词命中处置 ==================== -->
<el-tab-pane label="敏感词命中处置" name="hits">
<el-alert
class="hint"
type="info"
:closable="false"
title="以下元数据(题名/摘要/主题词/附注)命中了敏感词库中的词。可对单条或批量记录执行:屏蔽(检索与索引中隐藏)、下架、恢复正常、删除。"
/>
<div class="toolbar">
<el-button type="danger" plain :disabled="!hitSelection.length" @click="batchHit('MASK', '屏蔽')">
批量屏蔽
</el-button>
<el-button type="warning" plain :disabled="!hitSelection.length" @click="batchHit('OFFLINE', '下架')">
批量下架
</el-button>
<el-button type="success" plain :disabled="!hitSelection.length" @click="batchHit('RESTORE', '恢复正常')">
批量恢复
</el-button>
<el-button type="danger" :disabled="!hitSelection.length" @click="batchHit('DELETE', '删除')">
批量删除
</el-button>
<el-button @click="fetchHits">刷新</el-button>
</div>
<el-table
v-loading="hitLoading"
:data="hitList"
border
stripe
@selection-change="(rows: SensitiveHit[]) => (hitSelection = rows)"
>
<el-table-column type="selection" width="45" />
<el-table-column prop="title" label="正题名" min-width="200" show-overflow-tooltip />
<el-table-column prop="author" label="责任者" width="120" show-overflow-tooltip />
<el-table-column prop="sourceLibrary" label="来源馆" width="150" show-overflow-tooltip />
<el-table-column prop="mediaType" label="媒体类型" width="90" />
<el-table-column label="命中敏感词" min-width="150">
<template #default="{ row }">
<el-tag v-for="w in row.matchedWords" :key="w" size="small" type="danger" class="hit-tag">
{{ w }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="管理状态" width="100">
<template #default="{ row }">
<el-tag size="small" :type="manageStatusTag[row.manageStatus ?? 0]">
{{ manageStatusText[row.manageStatus ?? 0] }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="200" fixed="right">
<template #default="{ row }">
<el-button link type="danger" size="small" @click="handleHit(row, 'MASK', '屏蔽')">屏蔽</el-button>
<el-button link type="warning" size="small" @click="handleHit(row, 'OFFLINE', '下架')">下架</el-button>
<el-button link type="success" size="small" @click="handleHit(row, 'RESTORE', '恢复正常')">恢复</el-button>
<el-button link type="danger" size="small" @click="handleHit(row, 'DELETE', '删除')">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
class="pager"
background
layout="total, sizes, prev, pager, next, jumper"
:total="hitTotal"
v-model:current-page="hitQuery.current"
v-model:page-size="hitQuery.size"
:page-sizes="[10, 20, 50, 100]"
@current-change="fetchHits"
@size-change="fetchHits"
/>
</el-tab-pane>
<!-- ==================== 院校资源库 ==================== -->
<el-tab-pane label="院校资源库" name="library">
<div class="library-grid">
<!-- 资源数量统计 -->
<div class="panel">
<div class="panel-head">
<span class="panel-title">资源数量统计</span>
<el-radio-group v-model="statDim" size="small" @change="fetchStats">
<el-radio-button v-for="d in statDims" :key="d.value" :value="d.value">
{{ d.label }}
</el-radio-button>
</el-radio-group>
</div>
<el-table v-loading="statLoading" :data="statList" border stripe max-height="480">
<el-table-column type="index" label="#" width="50" />
<el-table-column prop="name" label="名称" min-width="200" show-overflow-tooltip />
<el-table-column prop="count" label="资源数量" width="100" align="right" />
</el-table>
</div>
<!-- 资源节点与链接管理 -->
<div class="panel">
<div class="panel-head">
<span class="panel-title">资源节点与访问链接</span>
<div>
<el-button type="success" size="small" @click="openNodeCreate">新增节点</el-button>
<el-button
type="danger"
size="small"
plain
:disabled="!nodeSelection.length"
@click="batchDeleteNodes"
>
批量删除
</el-button>
</div>
</div>
<el-table
v-loading="nodeLoading"
:data="nodeList"
border
stripe
max-height="480"
@selection-change="(rows: ResourceNode[]) => (nodeSelection = rows)"
>
<el-table-column type="selection" width="45" />
<el-table-column prop="sortNo" label="顺序" width="65" align="center" />
<el-table-column prop="name" label="节点名称" min-width="150" show-overflow-tooltip />
<el-table-column prop="nodeType" label="资源类型" width="100" show-overflow-tooltip />
<el-table-column prop="category" label="类别归属" width="110" show-overflow-tooltip />
<el-table-column label="访问链接" min-width="160" show-overflow-tooltip>
<template #default="{ row }">
<a v-if="row.linkUrl" :href="row.linkUrl" target="_blank" class="link">{{ row.linkUrl }}</a>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column label="状态" width="80">
<template #default="{ row }">
<el-tag size="small" :type="row.status === 1 ? 'success' : 'info'">
{{ row.status === 1 ? '启用' : '停用' }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="130" fixed="right">
<template #default="{ row }">
<el-button link type="primary" size="small" @click="openNodeEdit(row)">编辑</el-button>
<el-button link type="danger" size="small" @click="deleteNode(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
</el-tab-pane>
</el-tabs>
<!-- 敏感词 新增/编辑 弹窗 -->
<el-dialog v-model="wordDialog" :title="wordForm.id ? '编辑敏感词' : '新增敏感词'" width="420px">
<el-form label-width="90px">
<el-form-item label="敏感词" required>
<el-input v-model="wordForm.word" placeholder="中文敏感词" maxlength="100" />
</el-form-item>
<el-form-item label="拼音">
<el-input v-model="wordForm.pinyin" placeholder="如 migan(建议全小写无声调)" maxlength="200" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="wordDialog = false">取消</el-button>
<el-button type="primary" :loading="wordSaving" @click="saveWord">保存</el-button>
</template>
</el-dialog>
<!-- 资源节点 新增/编辑 弹窗 -->
<el-dialog v-model="nodeDialog" :title="nodeForm.id ? '编辑资源节点' : '新增资源节点'" width="520px">
<el-form label-width="90px">
<el-form-item label="节点名称" required>
<el-input v-model="nodeForm.name" maxlength="200" />
</el-form-item>
<el-form-item label="资源类型">
<el-input v-model="nodeForm.nodeType" placeholder="如 古籍善本 / 电子文献" maxlength="50" />
</el-form-item>
<el-form-item label="类别归属">
<el-input v-model="nodeForm.category" placeholder="如 军事理论类" maxlength="100" />
</el-form-item>
<el-form-item label="访问链接">
<el-input v-model="nodeForm.linkUrl" placeholder="http://..." maxlength="500" />
</el-form-item>
<el-form-item label="展示顺序">
<el-input-number v-model="nodeForm.sortNo" :min="0" :max="9999" />
<span class="form-tip">数值小的靠前展示</span>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="nodeForm.status" :active-value="1" :inactive-value="0" active-text="启用" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="nodeDialog = false">取消</el-button>
<el-button type="primary" :loading="nodeSaving" @click="saveNode">保存</el-button>
</template>
</el-dialog>
</div>
</template>
<style scoped lang="scss">
.admin-page {
max-width: 1400px;
margin: 0 auto;
}
.page-title {
margin: 0 0 12px;
font-family: 'Noto Serif SC', 'Songti SC', 'SimSun', serif;
font-size: 22px;
letter-spacing: 2px;
color: #1d3a2a;
}
.admin-tabs {
background: #fff;
border-radius: 10px;
padding: 8px 20px 20px;
box-shadow: 0 2px 10px rgba(20, 45, 30, 0.06);
}
.toolbar {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 14px;
flex-wrap: wrap;
}
.hint {
margin-bottom: 14px;
}
.pager {
margin-top: 14px;
justify-content: flex-end;
}
.hit-tag {
margin: 2px 4px 2px 0;
}
.library-grid {
display: grid;
grid-template-columns: 1fr 1.2fr;
gap: 20px;
@media (max-width: 1100px) {
grid-template-columns: 1fr;
}
}
.panel {
min-width: 0;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.panel-title {
font-weight: 600;
color: #1d3a2a;
}
.link {
color: var(--el-color-primary);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.form-tip {
margin-left: 10px;
font-size: 12px;
color: #999;
}
</style>
+16 -1
View File
@@ -84,6 +84,20 @@ async function openEdit(row: VersionResource) {
} }
} }
/** 新增:复用编辑抽屉,空表单(不带 id,保存时后端走新增) */
function openCreate() {
editForm.value = {
title: '',
governStatus: 'RAW',
abnormalFlag: 0,
sensitiveFlag: 0,
manageStatus: 0,
isSpecial: 0
} as VersionResource
detailLoading.value = false
drawerVisible.value = true
}
async function saveEdit() { async function saveEdit() {
if (!formRef.value) return if (!formRef.value) return
await formRef.value.validate() await formRef.value.validate()
@@ -129,6 +143,7 @@ onMounted(fetchData)
<el-form-item> <el-form-item>
<el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button> <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
<el-button :icon="Refresh" @click="handleReset">重置</el-button> <el-button :icon="Refresh" @click="handleReset">重置</el-button>
<el-button type="danger" plain @click="openCreate">新增</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
@@ -187,7 +202,7 @@ onMounted(fetchData)
<!-- 编辑抽屉:完整元数据 + 是否特藏版本 --> <!-- 编辑抽屉:完整元数据 + 是否特藏版本 -->
<el-drawer <el-drawer
v-model="drawerVisible" v-model="drawerVisible"
:title="editForm.id ? '编辑版本资源' : '版本资源'" :title="editForm.id ? '编辑版本资源' : '新增版本资源'"
size="720px" size="720px"
> >
<div v-loading="detailLoading"> <div v-loading="detailLoading">
+150 -16
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { getSearchDetail, getSimilar, unifiedSearch, type FacetItem, type SearchQuery } from '@/api/search' import { getSearchDetail, getSimilar, unifiedSearch, type FacetItem, type SearchQuery } from '@/api/search'
import type { VersionResource } from '@/api/resource' import type { VersionResource } from '@/api/resource'
@@ -15,17 +15,92 @@ const libraryFacets = ref<FacetItem[]>([])
const query = reactive<SearchQuery>({ const query = reactive<SearchQuery>({
current: 1, current: 1,
size: 20, size: 50,
keyword: '',
mediaType: '' mediaType: ''
}) })
const field = ref('题名') /** 概览页每页条数选项(默认 50,可切 100/200;20 便于数据量小时演示翻页) */
const fields = ['题名', '责任者', '关键词', '出版社', 'ISBN'] const pageSizes = [20, 50, 100, 200]
/** 输入框内容(与查询参数分离,避免按途径分发后被清空) */
const input = ref('')
const field = ref('综合')
const fields = ['综合', '题名', '责任者', '关键词', '出版社', 'ISBN']
/** 检索途径 → 查询参数字段 */
const fieldParamMap: Record<string, 'keyword' | 'title' | 'author' | 'publisher' | 'isbn'> = {
综合: 'keyword',
题名: 'title',
责任者: 'author',
关键词: 'keyword',
出版社: 'publisher',
ISBN: 'isbn'
}
// ==================== 命中位置标注与高亮 ====================
/** 各检索途径对应的检查字段(综合途经覆盖全部文本字段) */
const hitFieldMap: Record<string, string[]> = {
综合: ['title', 'author', 'keywords', 'summary', 'publisher'],
题名: ['title'],
责任者: ['author'],
关键词: ['keywords'],
出版社: ['publisher'],
ISBN: ['isbn']
}
const fieldLabels: Record<string, string> = {
title: '正题名',
author: '责任者',
keywords: '关键词',
summary: '摘要',
publisher: '出版者',
isbn: 'ISBN'
}
/** 当前检索词(空格分词) */
const terms = computed(() => input.value.trim().split(/\s+/).filter(Boolean))
function escapeHtml(s: string) {
return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] as string)
}
/** 文本高亮:命中的关键词包一层 span(先转义再包裹,避免注入) */
function highlight(text?: string): string {
if (!text || !terms.value.length) return escapeHtml(text || '')
let out = escapeHtml(text)
for (const t of terms.value) {
const esc = escapeHtml(t)
if (esc) out = out.split(esc).join(`<span class="hl">${esc}</span>`)
}
return out
}
/** 命中字段的上下文摘录(标题外命中时展示,如「出版者:…军事科学出版社…」) */
function snippets(row: VersionResource): { label: string; html: string }[] {
const keys = (hitFieldMap[field.value] || []).filter((k) => k !== 'title')
const out: { label: string; html: string }[] = []
for (const k of keys) {
const v = (row as unknown as Record<string, string | undefined>)[k]
if (!v) continue
const hit = terms.value.find((t) => v.includes(t))
if (!hit) continue
const idx = v.indexOf(hit)
const start = Math.max(0, idx - 12)
const end = Math.min(v.length, idx + hit.length + 28)
const text = (start > 0 ? '…' : '') + v.slice(start, end) + (end < v.length ? '…' : '')
out.push({ label: fieldLabels[k], html: highlight(text) })
}
return out
}
async function doSearch() { async function doSearch() {
loading.value = true loading.value = true
searched.value = true searched.value = true
// 按所选途径分发检索词;多词用空格分隔,词与词之间为 AND
const kw = input.value.trim()
query.title = query.author = query.publisher = query.isbn = query.keyword = ''
;(query as unknown as Record<string, string>)[fieldParamMap[field.value]] = kw
try { try {
const res = await unifiedSearch({ ...query }) const res = await unifiedSearch({ ...query })
rows.value = res.page?.records || [] rows.value = res.page?.records || []
@@ -47,6 +122,20 @@ function pick(type: 'mediaType' | 'sourceLibrary', v: string) {
function goPage(p: number) { function goPage(p: number) {
query.current = p query.current = p
doSearch() doSearch()
scrollToListTop()
}
/** 切换每页条数:回到第一页重新检索 */
function goSize(s: number) {
query.size = s
query.current = 1
doSearch()
scrollToListTop()
}
/** 翻页后回到结果列表顶部,避免停在长列表中间 */
function scrollToListTop() {
window.scrollTo({ top: 0, behavior: 'smooth' })
} }
const drawer = ref(false) const drawer = ref(false)
@@ -64,8 +153,13 @@ async function openDetail(row: VersionResource) {
onMounted(() => { onMounted(() => {
const kw = route.query.keyword as string const kw = route.query.keyword as string
const f = route.query.field as string
// 主页带来的检索途径(题名/责任者/…),合法则沿用
if (f && fields.includes(f)) {
field.value = f
}
if (kw) { if (kw) {
query.keyword = kw input.value = kw
doSearch() doSearch()
} }
}) })
@@ -74,9 +168,9 @@ onMounted(() => {
<template> <template>
<div class="search-page"> <div class="search-page">
<div class="bar"> <div class="bar">
<el-input v-model="query.keyword" size="large" placeholder="请输入检索词" clearable @keyup.enter="doSearch"> <el-input v-model="input" size="large" placeholder="请输入检索词,支持多词检索(空格分隔,命中任一词即返回)" clearable @keyup.enter="doSearch">
<template #prepend> <template #prepend>
<el-select v-model="field" style="width: 96px"> <el-select v-model="field" style="width: 96px" @change="searched && doSearch()">
<el-option v-for="f in fields" :key="f" :label="f" :value="f" /> <el-option v-for="f in fields" :key="f" :label="f" :value="f" />
</el-select> </el-select>
</template> </template>
@@ -104,14 +198,27 @@ onMounted(() => {
<div v-for="r in rows" :key="r.id" class="card" @click="openDetail(r)"> <div v-for="r in rows" :key="r.id" class="card" @click="openDetail(r)">
<div class="cover">{{ (r.title || '').slice(0, 2) }}</div> <div class="cover">{{ (r.title || '').slice(0, 2) }}</div>
<div class="info"> <div class="info">
<div class="t">{{ r.title }}</div> <div class="t" v-html="highlight(r.title)"></div>
<div class="d">{{ r.author || '-' }} · {{ r.publishYear || '-' }} · {{ r.mediaType || '-' }}</div> <div class="d">
<div class="d">{{ r.sourceLibrary || '-' }}</div> <span v-html="highlight(r.author || '-')"></span> · {{ r.publishYear || '-' }} · {{ r.mediaType || '-' }}
</div>
<div class="d" v-html="highlight(r.sourceLibrary || '-')"></div>
<div v-for="s in snippets(r)" :key="s.label" class="snippet">
<span class="snippet-label">{{ s.label }}:</span>
<span v-html="s.html"></span>
</div>
</div> </div>
</div> </div>
</div> </div>
<el-pagination class="pager" background layout="prev, pager, next" :total="total" <el-pagination class="pager" background
:current-page="query.current" :page-size="query.size" @current-change="goPage" /> layout="total, sizes, prev, pager, next, jumper"
:total="total"
:current-page="query.current"
:page-size="query.size"
:page-sizes="pageSizes"
:pager-count="7"
@current-change="goPage"
@size-change="goSize" />
</section> </section>
</div> </div>
@@ -205,8 +312,8 @@ onMounted(() => {
.meta { font-size: 13px; color: #6b7280; margin-bottom: 10px; } .meta { font-size: 13px; color: #6b7280; margin-bottom: 10px; }
.cards { .cards {
display: grid; display: flex;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); flex-direction: column;
gap: 14px; gap: 14px;
} }
@@ -243,7 +350,34 @@ onMounted(() => {
.d { font-size: 12px; color: #8b93a1; } .d { font-size: 12px; color: #8b93a1; }
} }
.pager { margin-top: 18px; justify-content: center; } /* 命中关键词高亮(v-html 动态插入的节点不带 scoped 属性,需用 :deep 穿透) */
:deep(.hl) {
background: #ffe6a3;
color: #8a4b00;
border-radius: 2px;
padding: 0 1px;
}
.snippet {
margin-top: 4px;
font-size: 12px;
color: #7b8493;
line-height: 1.5;
word-break: break-all;
}
.snippet-label {
color: #4b5563;
}
.pager {
margin-top: 18px;
justify-content: center;
flex-wrap: wrap;
/* 页码较多时自动换行,保证页码按钮与跳转框都能点到 */
:deep(.el-pagination__jump) { margin-left: 12px; }
}
.dt { margin: 0 0 12px; font-size: 17px; } .dt { margin: 0 0 12px; font-size: 17px; }
.sim-item { font-size: 13px; padding: 6px 0; border-bottom: 1px dashed #eee; cursor: pointer; } .sim-item { font-size: 13px; padding: 6px 0; border-bottom: 1px dashed #eee; cursor: pointer; }
</style> </style>
+53 -7
View File
@@ -1,10 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue' import { Download } from '@element-plus/icons-vue'
import { getResource } from '@/api/resource' import { getResource, updateSpecialFlag } from '@/api/resource'
import { getRecommend, type SpecialRecommendItem } from '@/api/special' import { getRecommend, removeSpecial as removeSpecialResource, type SpecialRecommendItem } from '@/api/special'
const route = useRoute() const route = useRoute()
@@ -17,6 +17,7 @@ interface Detail {
author?: string author?: string
publishYear?: string publishYear?: string
fulltextUrl?: string fulltextUrl?: string
cover?: string
} }
const dialogVisible = ref(false) const dialogVisible = ref(false)
@@ -54,10 +55,13 @@ async function openDetail(item: SpecialRecommendItem) {
note: noteOf(item), note: noteOf(item),
author: item.author, author: item.author,
publishYear: item.publishYear, publishYear: item.publishYear,
fulltextUrl: urlOf(item) fulltextUrl: urlOf(item),
cover: item.coverUrl
} }
// 只有来自 version_resource 的记录才有 title,可据此补拉完整著录 // 仅 version_resource 来源(source=VERSION)补拉完整著录;
if (item.id && item.title) { // special_resource 手工特藏(source=MANUAL)的 id 属于特藏表,
// 拿去查 /resource/{id} 会错表错行,直接用列表行数据展示
if (item.id && item.source === 'VERSION') {
try { try {
const full = await getResource(item.id) const full = await getResource(item.id)
current.value = { current.value = {
@@ -65,7 +69,8 @@ async function openDetail(item: SpecialRecommendItem) {
note: full.note, note: full.note,
author: full.author, author: full.author,
publishYear: full.publishYear, publishYear: full.publishYear,
fulltextUrl: full.fulltextUrl fulltextUrl: full.fulltextUrl,
cover: item.coverUrl
} }
} catch { } catch {
/* 保留列表行数据兜底 */ /* 保留列表行数据兜底 */
@@ -83,6 +88,26 @@ function download(item: SpecialRecommendItem) {
} }
} }
/** 从特藏推荐中移除:按数据来源分流 */
async function removeSpecial(item: SpecialRecommendItem) {
if (!item.id) return
if (item.source === 'VERSION') {
// version_resource 特藏:取消 is_special 标记,资源保留在资源管理中
await ElMessageBox.confirm(
`确认将「${titleOf(item)}」从特藏推荐中移除?资源本身仍保留在资源管理中。`,
'提示',
{ type: 'warning' }
)
await updateSpecialFlag(item.id, 0)
} else {
// special_resource 手工维护的特藏:逻辑删除(deleted=1)
await ElMessageBox.confirm(`确认删除特藏「${titleOf(item)}」?`, '提示', { type: 'warning' })
await removeSpecialResource(item.id)
}
ElMessage.success('删除成功')
fetchList()
}
onMounted(async () => { onMounted(async () => {
await fetchList() await fetchList()
// 从首页书架点书进来:自动打开对应特藏的详情 // 从首页书架点书进来:自动打开对应特藏的详情
@@ -126,6 +151,7 @@ onMounted(async () => {
<el-icon :size="14"><Download /></el-icon> <el-icon :size="14"><Download /></el-icon>
下载 下载
</span> </span>
<span v-if="it.id && it.title" class="op del" @click.stop="removeSpecial(it)">删除</span>
</div> </div>
</div> </div>
</div> </div>
@@ -134,6 +160,7 @@ onMounted(async () => {
<!-- 细览弹窗 --> <!-- 细览弹窗 -->
<el-dialog v-model="dialogVisible" :title="current?.title || '特藏细览'" width="620px"> <el-dialog v-model="dialogVisible" :title="current?.title || '特藏细览'" width="620px">
<template v-if="current"> <template v-if="current">
<img v-if="current.cover" :src="current.cover" class="dialog-cover" :alt="current.title" />
<el-descriptions :column="1" border size="small"> <el-descriptions :column="1" border size="small">
<el-descriptions-item label="正题名">{{ current.title || '-' }}</el-descriptions-item> <el-descriptions-item label="正题名">{{ current.title || '-' }}</el-descriptions-item>
<el-descriptions-item label="责任者">{{ current.author || '-' }}</el-descriptions-item> <el-descriptions-item label="责任者">{{ current.author || '-' }}</el-descriptions-item>
@@ -165,6 +192,16 @@ onMounted(async () => {
letter-spacing: 1px; letter-spacing: 1px;
} }
/* 细览弹窗封面图 */
.dialog-cover {
display: block;
max-width: 200px;
max-height: 260px;
margin: 0 auto 16px;
border-radius: 6px;
box-shadow: 0 4px 14px rgba(60, 45, 10, 0.2);
}
/* ---------- 列表(参考站外资源展示样式:图左 · 题名 · 描述 · 右侧入口) ---------- */ /* ---------- 列表(参考站外资源展示样式:图左 · 题名 · 描述 · 右侧入口) ---------- */
.special-list { .special-list {
display: flex; display: flex;
@@ -283,6 +320,15 @@ onMounted(async () => {
color: #8a6d3b; color: #8a6d3b;
text-decoration: underline; text-decoration: underline;
} }
/* 删除:红色示警 */
&.del {
color: #c0392b;
&:hover {
color: #96281b;
}
}
} }
} }