元数据模板导出 excel导入

This commit is contained in:
2026-10-23 18:45:12 +08:00
parent 8b6f00b117
commit ddc0864f06
8 changed files with 805 additions and 4 deletions
+7
View File
@@ -89,6 +89,13 @@
<version>${hutool.version}</version> <version>${hutool.version}</version>
</dependency> </dependency>
<!-- Excel 导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- JWT --> <!-- JWT -->
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
@@ -2,14 +2,22 @@ package com.banben.modules.resource.controller;
import com.banben.common.PageResult; import com.banben.common.PageResult;
import com.banben.common.Result; import com.banben.common.Result;
import com.banben.modules.resource.dto.ImportResult;
import com.banben.modules.resource.dto.VersionResourceQuery; import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource; import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.service.VersionResourceExcelService;
import com.banben.modules.resource.service.VersionResourceService; import com.banben.modules.resource.service.VersionResourceService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; 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 { public class VersionResourceController {
private final VersionResourceService versionResourceService; 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 = "分页查询版本资源") @Operation(summary = "分页查询版本资源")
@GetMapping("/page") @GetMapping("/page")
@@ -0,0 +1,38 @@
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;
/** 失败明细,格式如「第 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,365 @@
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 MAX_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, "选填;是 或 否")
);
// ==================== 模板导出 ====================
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);
// 媒体类型、是否特藏加下拉,避免填错
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 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, MAX_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 = Math.min(sheet.getLastRowNum(), startRow + MAX_ROWS);
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 (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, "未读取到有效数据行,请从第 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;
}
}
+132
View File
@@ -0,0 +1,132 @@
-- =====================================================================
-- 版本资源联合服务系统 - 表与字段注释
-- 兼容 PostgreSQL / 瀚高(HighGo),可重复执行
-- 说明:瀚高基于 PostgreSQL 内核,COMMENT ON 语法与 PG 完全一致
-- =====================================================================
-- ---------------- 1. 系统用户表 ----------------
COMMENT ON TABLE sys_user IS '系统用户表:存放登录账号、角色与所属单位,密码以 BCrypt 加密存储';
COMMENT ON COLUMN sys_user.id IS '主键';
COMMENT ON COLUMN sys_user.username IS '登录账号,全局唯一';
COMMENT ON COLUMN sys_user.password IS 'BCrypt 加密后的密码';
COMMENT ON COLUMN sys_user.real_name IS '姓名';
COMMENT ON COLUMN sys_user.role IS '角色:ADMIN 管理员 / USER 普通用户';
COMMENT ON COLUMN sys_user.org_name IS '所属单位';
COMMENT ON COLUMN sys_user.status IS '状态:1 启用 / 0 停用';
COMMENT ON COLUMN sys_user.last_login_time IS '最近登录时间';
COMMENT ON COLUMN sys_user.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
COMMENT ON COLUMN sys_user.create_time IS '创建时间';
COMMENT ON COLUMN sys_user.update_time IS '更新时间';
-- ---------------- 2. 版本资源元数据主表 ----------------
COMMENT ON TABLE version_resource IS '版本资源元数据主表:依据询价文件《单条版本资源元数据采集要素及存储标准》建表,存储各成员馆汇聚的纸电版本资源';
COMMENT ON COLUMN version_resource.id IS '主键';
COMMENT ON COLUMN version_resource.process_no IS '【必备】加工编号';
COMMENT ON COLUMN version_resource.title IS '【必备】正题名';
COMMENT ON COLUMN version_resource.clc_code IS '【必备】中图分类号(CLC 第五版标引)';
COMMENT ON COLUMN version_resource.keywords IS '【必备】主题词或关键词(CCT 标引),分号分隔';
COMMENT ON COLUMN version_resource.summary IS '【必备】摘要,不少于 100 字';
COMMENT ON COLUMN version_resource.publish_year IS '【必备】出版年份,格式 yyyy';
COMMENT ON COLUMN version_resource.process_date IS '【必备】加工日期,格式 yyyyMMdd';
COMMENT ON COLUMN version_resource.content_form IS '【必备】内容形式,如文本、图像、音视频';
COMMENT ON COLUMN version_resource.media_type IS '【必备】媒体类型:纸质 / 电子';
COMMENT ON COLUMN version_resource.format IS '【必备】文件格式,如 PDF、EPUB';
COMMENT ON COLUMN version_resource.page_count IS '【必备】页码 / 页数';
COMMENT ON COLUMN version_resource.language IS '【必备】语种,三位代码,如 chi、eng';
COMMENT ON COLUMN version_resource.submit_org IS '【必备】数据提交单位';
COMMENT ON COLUMN version_resource.task_year IS '【必备】所属任务年份';
COMMENT ON COLUMN version_resource.source_library IS '【必备】来源馆';
COMMENT ON COLUMN version_resource.source_library_addr IS '【必备】来源馆地址';
COMMENT ON COLUMN version_resource.fulltext_url IS '【必备】全文地址(按 CDOI 生成)';
COMMENT ON COLUMN version_resource.other_title IS '【有则必备】其他题名';
COMMENT ON COLUMN version_resource.author IS '【有则必备】责任者名称';
COMMENT ON COLUMN version_resource.responsibility IS '【有则必备】责任方式';
COMMENT ON COLUMN version_resource.note IS '【有则必备】附注';
COMMENT ON COLUMN version_resource.publisher IS '【有则必备】出版者名称';
COMMENT ON COLUMN version_resource.publish_place IS '【有则必备】出版地';
COMMENT ON COLUMN version_resource.publish_date IS '【有则必备】出版日期';
COMMENT ON COLUMN version_resource.relation IS '【有则必备】关联';
COMMENT ON COLUMN version_resource.time_range IS '【有则必备】时间范围';
COMMENT ON COLUMN version_resource.space_range IS '【有则必备】空间范围';
COMMENT ON COLUMN version_resource.edition IS '【有则必备】版本';
COMMENT ON COLUMN version_resource.isbn IS '【有则必备】ISBN';
COMMENT ON COLUMN version_resource.unified_book_no IS '【有则必备】统一书号';
COMMENT ON COLUMN version_resource.cdoi IS '【有则必备】CDOI';
COMMENT ON COLUMN version_resource.publish_url IS '【有则必备】发布地址';
COMMENT ON COLUMN version_resource.govern_status IS '治理状态:RAW 原始 / MERGED 已聚同 / CLEANED 已优化 / PURIFIED 已提纯';
COMMENT ON COLUMN version_resource.sensitive_flag IS '敏感词命中标记:0 正常 / 1 命中待处理';
COMMENT ON COLUMN version_resource.create_time IS '创建时间';
COMMENT ON COLUMN version_resource.update_time IS '更新时间';
COMMENT ON COLUMN version_resource.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
-- ---------------- 3. 特藏版本资源表 ----------------
COMMENT ON TABLE special_resource IS '特藏版本资源表:首页“特藏版本推荐”展示用,含名称、简介、封面图与电子版下载地址';
COMMENT ON COLUMN special_resource.id IS '主键';
COMMENT ON COLUMN special_resource.name IS '特藏名称';
COMMENT ON COLUMN special_resource.summary IS '简介';
COMMENT ON COLUMN special_resource.category IS '类别,如古籍、地方志、红色文献';
COMMENT ON COLUMN special_resource.cover_url IS '封面图片地址';
COMMENT ON COLUMN special_resource.ebook_url IS '电子版下载地址';
COMMENT ON COLUMN special_resource.sort_no IS '展示排序号,越小越靠前';
COMMENT ON COLUMN special_resource.status IS '状态:1 展示 / 0 隐藏';
COMMENT ON COLUMN special_resource.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
COMMENT ON COLUMN special_resource.create_time IS '创建时间';
COMMENT ON COLUMN special_resource.update_time IS '更新时间';
-- ---------------- 4. 版本资源呈缴记录表 ----------------
COMMENT ON TABLE deposit_record IS '版本资源呈缴记录表:记录单位提交的呈缴申请(单位、联系人、资源元数据、数字版文件)及管理员审核结果';
COMMENT ON COLUMN deposit_record.id IS '主键';
COMMENT ON COLUMN deposit_record.org_name IS '呈缴单位名称';
COMMENT ON COLUMN deposit_record.contact IS '联系人';
COMMENT ON COLUMN deposit_record.phone IS '联系方式';
COMMENT ON COLUMN deposit_record.email IS '邮箱';
COMMENT ON COLUMN deposit_record.resource_title IS '呈缴的版本资源名称';
COMMENT ON COLUMN deposit_record.media_type IS '媒体类型:纸质 / 电子';
COMMENT ON COLUMN deposit_record.summary IS '资源简介';
COMMENT ON COLUMN deposit_record.remark IS '备注';
COMMENT ON COLUMN deposit_record.file_url IS '数字版文件地址';
COMMENT ON COLUMN deposit_record.status IS '审核状态:PENDING 待审核 / ACCEPTED 已接收 / REJECTED 已退回';
COMMENT ON COLUMN deposit_record.audit_remark IS '审核意见';
COMMENT ON COLUMN deposit_record.audit_time IS '审核时间';
COMMENT ON COLUMN deposit_record.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
COMMENT ON COLUMN deposit_record.create_time IS '创建时间';
COMMENT ON COLUMN deposit_record.update_time IS '更新时间';
-- ---------------- 5. 数据采集任务表 ----------------
COMMENT ON TABLE collect_task IS '数据采集任务表:按成员单位记录元数据采集任务的目标量、已采集量与执行状态';
COMMENT ON COLUMN collect_task.id IS '主键';
COMMENT ON COLUMN collect_task.library_code IS '成员单位编码';
COMMENT ON COLUMN collect_task.library_name IS '成员单位名称';
COMMENT ON COLUMN collect_task.source_type IS '数据源类型:MARC / EXCEL / DB / API';
COMMENT ON COLUMN collect_task.target_count IS '目标采集量,默认 20 万条';
COMMENT ON COLUMN collect_task.collected_count IS '已采集量';
COMMENT ON COLUMN collect_task.status IS '任务状态:PENDING 待执行 / RUNNING 执行中 / SUCCESS 成功 / FAILED 失败';
COMMENT ON COLUMN collect_task.message IS '执行信息或失败原因';
COMMENT ON COLUMN collect_task.start_time IS '开始时间';
COMMENT ON COLUMN collect_task.end_time IS '结束时间';
COMMENT ON COLUMN collect_task.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
COMMENT ON COLUMN collect_task.create_time IS '创建时间';
COMMENT ON COLUMN collect_task.update_time IS '更新时间';
-- ---------------- 6. 数据治理任务表 ----------------
COMMENT ON TABLE governance_job IS '数据治理任务表:记录聚同(MERGE)、优化(OPTIMIZE)、提示(HINT)、提纯(PURIFY) 四类治理动作的执行结果';
COMMENT ON COLUMN governance_job.id IS '主键';
COMMENT ON COLUMN governance_job.job_type IS '治理类型:MERGE 聚同 / OPTIMIZE 优化 / HINT 提示 / PURIFY 提纯';
COMMENT ON COLUMN governance_job.status IS '任务状态:PENDING / RUNNING / SUCCESS / FAILED';
COMMENT ON COLUMN governance_job.affected_count IS '本次治理影响的记录数';
COMMENT ON COLUMN governance_job.result_summary IS '治理结果摘要';
COMMENT ON COLUMN governance_job.start_time IS '开始时间';
COMMENT ON COLUMN governance_job.end_time IS '结束时间';
COMMENT ON COLUMN governance_job.deleted IS '逻辑删除标记:0 正常 / 1 已删除';
COMMENT ON COLUMN governance_job.create_time IS '创建时间';
COMMENT ON COLUMN governance_job.update_time IS '更新时间';
-- ---------------- 7. 检索行为日志表 ----------------
COMMENT ON TABLE search_log IS '检索行为日志表:记录每次检索的关键词、IP、来源、结果数与耗时,用于热门检索词排行与统计分析';
COMMENT ON COLUMN search_log.id IS '主键';
COMMENT ON COLUMN search_log.keyword IS '检索关键词';
COMMENT ON COLUMN search_log.user_ip IS '用户 IP';
COMMENT ON COLUMN search_log.source_library IS '来源资源库 / 成员馆';
COMMENT ON COLUMN search_log.result_count IS '本次检索命中结果数';
COMMENT ON COLUMN search_log.cost_ms IS '检索耗时(毫秒)';
COMMENT ON COLUMN search_log.create_time IS '检索时间';
+4
View File
@@ -32,6 +32,10 @@ service.interceptors.request.use(
// 响应拦截器:统一解包 + 错误提示 + 401 处理 // 响应拦截器:统一解包 + 错误提示 + 401 处理
service.interceptors.response.use( service.interceptors.response.use(
(response: AxiosResponse<ApiResult>) => { (response: AxiosResponse<ApiResult>) => {
// 文件流(模板下载等)不做解包,原样返回
if (response.config.responseType === 'blob') {
return response as never
}
const res = response.data const res = response.data
if (res.code !== 200) { if (res.code !== 200) {
ElMessage.error(res.message || '请求失败') ElMessage.error(res.message || '请求失败')
+24
View File
@@ -1,3 +1,4 @@
import type { AxiosResponse } from 'axios'
import request from './request' import request from './request'
import type { PageResult } from './types' import type { PageResult } from './types'
@@ -77,3 +78,26 @@ export function removeResource(id: number) {
export function updateSpecialFlag(id: number, isSpecial: number) { export function updateSpecialFlag(id: number, isSpecial: number) {
return request.put<never, void>(`/resource/${id}/special`, null, { params: { isSpecial } }) return request.put<never, void>(`/resource/${id}/special`, null, { params: { isSpecial } })
} }
/** 下载 Excel 导入模板 */
export function downloadTemplate() {
return request.get<never, AxiosResponse<Blob>>('/resource/template', {
responseType: 'blob'
})
}
/** Excel 导入结果 */
export interface ImportResult {
total: number
inserted: number
updated: number
failed: number
errors: string[]
}
/** Excel 批量导入版本资源 */
export function importResource(file: File) {
const form = new FormData()
form.append('file', file)
return request.post<never, ImportResult>('/resource/import', form)
}
+209 -4
View File
@@ -1,12 +1,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive, ref } from 'vue' import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus' import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue' import { Download, Refresh, Search, Upload } from '@element-plus/icons-vue'
import { import {
downloadTemplate,
getResource, getResource,
importResource,
pageResource, pageResource,
removeResource, removeResource,
saveResource, saveResource,
type ImportResult,
type ResourceQuery, type ResourceQuery,
type VersionResource type VersionResource
} from '@/api/resource' } from '@/api/resource'
@@ -113,6 +116,58 @@ async function saveEdit() {
} }
} }
/* ---------- 模板导出 / Excel 导入 ---------- */
const fileInput = ref<HTMLInputElement>()
const importing = ref(false)
const resultVisible = ref(false)
const importResult = ref<ImportResult | null>(null)
async function handleDownloadTemplate() {
const resp = await downloadTemplate()
const blob = new Blob([resp.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = '版本资源导入模板.xlsx'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
function triggerImport() {
fileInput.value?.click()
}
async function handleFileChange(e: Event) {
const el = e.target as HTMLInputElement
const file = el.files?.[0]
if (!file) return
if (!/\.(xlsx|xls)$/i.test(file.name)) {
ElMessage.error('请选择 Excel 文件(.xlsx / .xls)')
el.value = ''
return
}
importing.value = true
try {
const res = await importResource(file)
importResult.value = res
resultVisible.value = true
if (res.inserted || res.updated) {
ElMessage.success(`导入完成:新增 ${res.inserted} 条,更新 ${res.updated} 条`)
query.current = 1
fetchData()
}
} finally {
importing.value = false
el.value = ''
}
}
onMounted(fetchData) onMounted(fetchData)
</script> </script>
@@ -149,7 +204,28 @@ onMounted(fetchData)
</div> </div>
<div class="page-card"> <div class="page-card">
<h3 class="page-title">版本资源库(元数据)</h3> <div class="table-head">
<h3 class="page-title">版本资源库(元数据)</h3>
<div class="head-actions">
<el-button :icon="Download" @click="handleDownloadTemplate">模板导出</el-button>
<el-button
type="primary"
plain
:icon="Upload"
:loading="importing"
@click="triggerImport"
>
Excel 导入
</el-button>
<input
ref="fileInput"
type="file"
accept=".xlsx,.xls"
class="file-input"
@change="handleFileChange"
/>
</div>
</div>
<el-table v-loading="loading" :data="list" border stripe> <el-table v-loading="loading" :data="list" border stripe>
<el-table-column type="index" label="#" width="50" /> <el-table-column type="index" label="#" width="50" />
<el-table-column prop="title" label="正题名" min-width="200" show-overflow-tooltip> <el-table-column prop="title" label="正题名" min-width="200" show-overflow-tooltip>
@@ -318,6 +394,38 @@ onMounted(fetchData)
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button> <el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
</template> </template>
</el-drawer> </el-drawer>
<!-- 导入结果 -->
<el-dialog v-model="resultVisible" title="导入结果" width="560px">
<div v-if="importResult" class="imp-summary">
<div class="imp-item">
<b>{{ importResult.total }}</b><em>解析行数</em>
</div>
<div class="imp-item ok">
<b>{{ importResult.inserted }}</b><em>新增</em>
</div>
<div class="imp-item upd">
<b>{{ importResult.updated }}</b><em>更新</em>
</div>
<div class="imp-item err">
<b>{{ importResult.failed }}</b><em>失败</em>
</div>
</div>
<div v-if="importResult?.errors?.length" class="imp-errors">
<div class="imp-errors-title">失败明细</div>
<ul>
<li v-for="(msg, i) in importResult.errors" :key="i">{{ msg }}</li>
</ul>
</div>
<p v-else-if="importResult && !importResult.failed" class="imp-ok-tip">
全部数据导入成功。
</p>
<template #footer>
<el-button type="primary" @click="resultVisible = false">知道了</el-button>
</template>
</el-dialog>
</div> </div>
</template> </template>
@@ -327,10 +435,107 @@ onMounted(fetchData)
justify-content: flex-end; justify-content: flex-end;
} }
.table-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 16px;
.page-title {
margin: 0;
}
}
.head-actions {
display: flex;
align-items: center;
gap: 10px;
}
.file-input {
display: none;
}
/* 导入结果 */
.imp-summary {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
margin-bottom: 16px;
}
.imp-item {
padding: 14px 8px;
text-align: center;
background: var(--brand-light);
border: 1px solid var(--card-border);
border-radius: var(--radius-sm);
b {
display: block;
font-family: 'Noto Serif SC', 'Songti SC', serif;
font-size: 22px;
line-height: 1.3;
color: var(--brand-primary-deep);
}
em {
font-style: normal;
font-size: 12px;
color: var(--text-muted);
}
&.ok b {
color: #3f7d5c;
}
&.upd b {
color: #a3703f;
}
&.err b {
color: #c0392b;
}
}
.imp-errors {
max-height: 220px;
overflow-y: auto;
padding: 10px 12px;
background: #fdf6f4;
border: 1px solid #f2dcd6;
border-radius: var(--radius-sm);
.imp-errors-title {
margin-bottom: 6px;
font-size: 13px;
font-weight: 600;
color: #b03a2e;
}
ul {
margin: 0;
padding-left: 18px;
}
li {
font-size: 12px;
line-height: 1.9;
color: #8a5a50;
}
}
.imp-ok-tip {
margin: 0;
font-size: 13px;
color: #3f7d5c;
}
.special-tag { .special-tag {
margin-right: 6px; margin-right: 6px;
background: var(--brand-gold-deep); background: var(--brand-primary);
border-color: var(--brand-gold-deep); border-color: var(--brand-primary);
color: #fff; color: #fff;
} }