Compare commits
15 Commits
8bdaafb69b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| eb985706c4 | |||
| 37566e9d7e | |||
| f1765c039c | |||
| 7794716861 | |||
| 3d2a3e7766 | |||
| 5cf7b35a58 | |||
| 7438f558e2 | |||
| 0b5c0a40e9 | |||
| 4f3fc578d0 | |||
| 0d8fdbd35a | |||
| b76a7ccce4 | |||
| f4f24398ee | |||
| 8546afa24e | |||
| 3dca829cf3 | |||
| a2ea2389e5 |
@@ -68,6 +68,24 @@
|
|||||||
<artifactId>mysql-connector-j</artifactId>
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- 现场外部库可能是 Oracle / SQL Server,驱动随包提供,连接信息仍从配置表读取 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.oracle.database.jdbc</groupId>
|
||||||
|
<artifactId>ojdbc11</artifactId>
|
||||||
|
<version>23.4.0.24.05</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.microsoft.sqlserver</groupId>
|
||||||
|
<artifactId>mssql-jdbc</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- 南昌总库汇总用 Elasticsearch。连不上时开发配置可改走本地表,避免拖垮已有业务。 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>co.elastic.clients</groupId>
|
||||||
|
<artifactId>elasticsearch-java</artifactId>
|
||||||
|
<version>8.13.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- 连接池 -->
|
<!-- 连接池 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.banben.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
|
||||||
|
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一 java.time 类型的 JSON 序列化格式。
|
||||||
|
*
|
||||||
|
* <p>Spring 的 {@code spring.jackson.date-format} 只作用于 {@code java.util.Date},
|
||||||
|
* 对 {@code LocalDateTime/LocalDate/LocalTime} 默认序列化为带 T 的 ISO-8601(如 2026-11-04T10:30:00),
|
||||||
|
* 前端展示与解析都不友好。这里统一改为可读格式:</p>
|
||||||
|
* <ul>
|
||||||
|
* <li>LocalDateTime → yyyy-MM-dd HH:mm:ss</li>
|
||||||
|
* <li>LocalDate → yyyy-MM-dd</li>
|
||||||
|
* <li>LocalTime → HH:mm:ss</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class JacksonConfig {
|
||||||
|
|
||||||
|
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
|
||||||
|
private static final String DATE_PATTERN = "yyyy-MM-dd";
|
||||||
|
private static final String TIME_PATTERN = "HH:mm:ss";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
|
||||||
|
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
|
||||||
|
DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERN);
|
||||||
|
DateTimeFormatter tf = DateTimeFormatter.ofPattern(TIME_PATTERN);
|
||||||
|
return builder -> builder
|
||||||
|
.serializerByType(java.time.LocalDateTime.class, new LocalDateTimeSerializer(dtf))
|
||||||
|
.serializerByType(java.time.LocalDate.class, new LocalDateSerializer(df))
|
||||||
|
.serializerByType(java.time.LocalTime.class, new LocalTimeSerializer(tf))
|
||||||
|
.deserializerByType(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(dtf))
|
||||||
|
.deserializerByType(java.time.LocalDate.class, new LocalDateDeserializer(df))
|
||||||
|
.deserializerByType(java.time.LocalTime.class, new LocalTimeDeserializer(tf));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.banben.config;
|
package com.banben.config;
|
||||||
|
|
||||||
import com.banben.modules.auth.interceptor.AuthInterceptor;
|
import com.banben.modules.auth.interceptor.AuthInterceptor;
|
||||||
|
import com.banben.modules.synchub.config.HubTokenInterceptor;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
@@ -22,6 +23,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|||||||
public class WebMvcConfig implements WebMvcConfigurer {
|
public class WebMvcConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
private final AuthInterceptor authInterceptor;
|
private final AuthInterceptor authInterceptor;
|
||||||
|
private final HubTokenInterceptor hubTokenInterceptor;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 跨域配置。
|
* 跨域配置。
|
||||||
@@ -46,6 +48,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||||||
* <li>{@code /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
|
* <li>{@code /api/auth/logout} —— 登出由前端清令牌,网络异常时也应能调用</li>
|
||||||
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
|
* <li>{@code /swagger-ui/**}、{@code /v3/api-docs/**} —— 接口文档</li>
|
||||||
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
|
* <li>{@code /actuator/**} —— 健康检查(容器探针需要)</li>
|
||||||
|
* <li>{@code /api/hub/**} —— 节点与总库互调用同步口令,不用用户登录令牌</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
@@ -58,7 +61,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||||||
"/api/auth/logout",
|
"/api/auth/logout",
|
||||||
"/swagger-ui/**",
|
"/swagger-ui/**",
|
||||||
"/v3/api-docs/**",
|
"/v3/api-docs/**",
|
||||||
"/actuator/**"
|
"/actuator/**",
|
||||||
|
"/api/hub/**"
|
||||||
);
|
);
|
||||||
|
registry.addInterceptor(hubTokenInterceptor)
|
||||||
|
.addPathPatterns("/api/hub/**");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import jakarta.validation.constraints.Pattern;
|
|||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 新增或修改角色。
|
* 新增或修改角色。
|
||||||
*/
|
*/
|
||||||
@@ -25,4 +27,7 @@ public class RoleSaveRequest {
|
|||||||
|
|
||||||
/** 1启用 0停用 */
|
/** 1启用 0停用 */
|
||||||
private Integer status;
|
private Integer status;
|
||||||
|
|
||||||
|
/** 顶部导航编码。空列表表示该角色看不到任何顶部栏目。 */
|
||||||
|
private List<String> menuCodes;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import lombok.Data;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 角色。内置角色不可删除,编码供登录令牌使用。
|
* 角色。内置角色不可删除,编码供登录令牌使用。
|
||||||
@@ -38,6 +40,13 @@ public class SysRole implements Serializable {
|
|||||||
@Schema(description = "1内置 0自建")
|
@Schema(description = "1内置 0自建")
|
||||||
private Integer builtin;
|
private Integer builtin;
|
||||||
|
|
||||||
|
@Schema(description = "1表示顶部导航已初始化")
|
||||||
|
private Integer menuInited;
|
||||||
|
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "可访问的顶部导航编码")
|
||||||
|
private List<String> menuCodes = new ArrayList<>();
|
||||||
|
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@TableField(fill = FieldFill.INSERT)
|
||||||
private LocalDateTime createTime;
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.banben.modules.admin.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色与顶部导航的对应关系。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sys_role_menu")
|
||||||
|
public class SysRoleMenu implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private Long roleId;
|
||||||
|
|
||||||
|
private String menuCode;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.admin.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色导航权限。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> {
|
||||||
|
}
|
||||||
@@ -5,15 +5,22 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
|||||||
import com.banben.common.BusinessException;
|
import com.banben.common.BusinessException;
|
||||||
import com.banben.modules.admin.dto.RoleSaveRequest;
|
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||||
import com.banben.modules.admin.entity.SysRole;
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
import com.banben.modules.admin.service.RoleService;
|
import com.banben.modules.admin.service.RoleService;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import com.banben.modules.auth.nav.NavMenus;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 角色增删改。ADMIN、USER 为内置角色。
|
* 角色增删改。ADMIN、USER 为内置角色。
|
||||||
@@ -23,13 +30,28 @@ import java.util.List;
|
|||||||
public class RoleServiceImpl implements RoleService {
|
public class RoleServiceImpl implements RoleService {
|
||||||
|
|
||||||
private final SysRoleMapper roleMapper;
|
private final SysRoleMapper roleMapper;
|
||||||
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
private final SysUserMapper userMapper;
|
private final SysUserMapper userMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<SysRole> listAll() {
|
public List<SysRole> listAll() {
|
||||||
return roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
|
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
|
||||||
.orderByDesc(SysRole::getBuiltin)
|
.orderByDesc(SysRole::getBuiltin)
|
||||||
.orderByAsc(SysRole::getId));
|
.orderByAsc(SysRole::getId));
|
||||||
|
Map<Long, List<String>> menus = roleMenuMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||||
|
.collect(Collectors.groupingBy(SysRoleMenu::getRoleId,
|
||||||
|
Collectors.mapping(SysRoleMenu::getMenuCode, Collectors.toList())));
|
||||||
|
for (SysRole role : roles) {
|
||||||
|
if (isAdminCode(role)) {
|
||||||
|
role.setMenuCodes(new ArrayList<>(NavMenus.CODES));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
role.setMenuCodes(menus.getOrDefault(role.getId(), List.of()).stream()
|
||||||
|
.filter(NavMenus::contains)
|
||||||
|
.distinct()
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
return roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -38,6 +60,8 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
role.setBuiltin(0);
|
role.setBuiltin(0);
|
||||||
fill(role, request, null);
|
fill(role, request, null);
|
||||||
roleMapper.insert(role);
|
roleMapper.insert(role);
|
||||||
|
replaceMenus(role.getId(), request.getMenuCodes());
|
||||||
|
markMenusInited(role.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -59,6 +83,13 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
.set(SysUser::getRole, role.getCode())
|
.set(SysUser::getRole, role.getCode())
|
||||||
.eq(SysUser::getRoleId, id));
|
.eq(SysUser::getRoleId, id));
|
||||||
}
|
}
|
||||||
|
if (isAdminCode(role)) {
|
||||||
|
replaceMenus(id, NavMenus.CODES);
|
||||||
|
markMenusInited(id);
|
||||||
|
} else if (request.getMenuCodes() != null) {
|
||||||
|
replaceMenus(id, request.getMenuCodes());
|
||||||
|
markMenusInited(id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -72,6 +103,7 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
throw new BusinessException("该角色下还有用户,不能删除");
|
throw new BusinessException("该角色下还有用户,不能删除");
|
||||||
}
|
}
|
||||||
roleMapper.deleteById(id);
|
roleMapper.deleteById(id);
|
||||||
|
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -81,8 +113,12 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void ensure(String code, String name, String remark) {
|
private void ensure(String code, String name, String remark) {
|
||||||
Long count = roleMapper.selectCount(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
|
SysRole existing = roleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
|
||||||
if (count != null && count > 0) {
|
if (existing != null) {
|
||||||
|
if ("ADMIN".equalsIgnoreCase(code)) {
|
||||||
|
replaceMenus(existing.getId(), NavMenus.CODES);
|
||||||
|
markMenusInited(existing.getId());
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
SysRole role = new SysRole();
|
SysRole role = new SysRole();
|
||||||
@@ -92,6 +128,8 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
role.setStatus(1);
|
role.setStatus(1);
|
||||||
role.setBuiltin(1);
|
role.setBuiltin(1);
|
||||||
roleMapper.insert(role);
|
roleMapper.insert(role);
|
||||||
|
replaceMenus(role.getId(), NavMenus.CODES);
|
||||||
|
markMenusInited(role.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
|
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
|
||||||
@@ -121,4 +159,35 @@ public class RoleServiceImpl implements RoleService {
|
|||||||
private boolean isBuiltin(SysRole role) {
|
private boolean isBuiltin(SysRole role) {
|
||||||
return role.getBuiltin() != null && role.getBuiltin() == 1;
|
return role.getBuiltin() != null && role.getBuiltin() == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isAdminCode(SysRole role) {
|
||||||
|
return role.getCode() != null && "ADMIN".equalsIgnoreCase(role.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void replaceMenus(Long roleId, List<String> menuCodes) {
|
||||||
|
List<String> codes = menuCodes == null ? new ArrayList<>(NavMenus.CODES) : normalize(menuCodes);
|
||||||
|
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
|
||||||
|
for (String code : codes) {
|
||||||
|
SysRoleMenu row = new SysRoleMenu();
|
||||||
|
row.setRoleId(roleId);
|
||||||
|
row.setMenuCode(code);
|
||||||
|
roleMenuMapper.insert(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> normalize(List<String> menuCodes) {
|
||||||
|
LinkedHashSet<String> codes = new LinkedHashSet<>();
|
||||||
|
for (String code : menuCodes) {
|
||||||
|
if (NavMenus.contains(code)) {
|
||||||
|
codes.add(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ArrayList<>(codes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markMenusInited(Long roleId) {
|
||||||
|
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
|
||||||
|
.eq(SysRole::getId, roleId)
|
||||||
|
.set(SysRole::getMenuInited, 1));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,59 @@
|
|||||||
package com.banben.modules.admin.support;
|
package com.banben.modules.admin.support;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.banben.common.BusinessException;
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
import com.banben.modules.auth.context.LoginUser;
|
import com.banben.modules.auth.context.LoginUser;
|
||||||
import com.banben.modules.auth.context.UserContext;
|
import com.banben.modules.auth.context.UserContext;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 组织、角色、用户管理只允许管理员调用。
|
* 后台管理接口:角色勾选了「后台管理」栏目才能调用。
|
||||||
|
* 权限表暂时不可用时,仍放行角色编码为 ADMIN 的账号,避免把管理员锁在外面。
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class AdminAccess {
|
public class AdminAccess {
|
||||||
|
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
|
|
||||||
public void require() {
|
public void require() {
|
||||||
LoginUser user = UserContext.get();
|
LoginUser login = UserContext.get();
|
||||||
if (user == null || user.role() == null || !"ADMIN".equalsIgnoreCase(user.role())) {
|
if (login == null || login.id() == null || !allowed(login.id(), login.role())) {
|
||||||
throw new BusinessException(403, "需要管理员权限");
|
throw new BusinessException(403, "需要后台管理权限");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean allowed(Long userId, String roleCode) {
|
||||||
|
if (isAdminCode(roleCode)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
SysUser user = userMapper.selectById(userId);
|
||||||
|
if (user == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isAdminCode(user.getRole())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (user.getRoleId() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Long count = roleMenuMapper.selectCount(new LambdaQueryWrapper<SysRoleMenu>()
|
||||||
|
.eq(SysRoleMenu::getRoleId, user.getRoleId())
|
||||||
|
.eq(SysRoleMenu::getMenuCode, "admin"));
|
||||||
|
return count != null && count > 0;
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
return isAdminCode(roleCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAdminCode(String roleCode) {
|
||||||
|
return roleCode != null && "ADMIN".equalsIgnoreCase(roleCode);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.banben.modules.auth;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志表自举建表。
|
||||||
|
*
|
||||||
|
* <p>应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
|
||||||
|
* 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
|
||||||
|
* 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。</p>
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class LoginLogTableInitializer {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public LoginLogTableInitializer(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS login_log ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "user_id BIGINT, "
|
||||||
|
+ "username VARCHAR(128), "
|
||||||
|
+ "real_name VARCHAR(128), "
|
||||||
|
+ "org_name VARCHAR(256), "
|
||||||
|
+ "ip VARCHAR(64), "
|
||||||
|
+ "user_agent VARCHAR(512), "
|
||||||
|
+ "login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "logout_time TIMESTAMP, "
|
||||||
|
+ "online SMALLINT DEFAULT 1, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online)");
|
||||||
|
log.info("登录日志表 login_log 已就绪(不存在则已自动创建)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 建表失败不应阻断启动;缺表时登录日志接口已做优雅降级
|
||||||
|
log.warn("自动创建 login_log 表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,12 +5,16 @@ import com.banben.modules.auth.dto.LoginRequest;
|
|||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.dto.LoginResponse;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
import com.banben.modules.auth.service.AuthService;
|
import com.banben.modules.auth.service.AuthService;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.context.UserContext;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
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 java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证接口。
|
* 认证接口。
|
||||||
*/
|
*/
|
||||||
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private final AuthService authService;
|
private final AuthService authService;
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
|
||||||
@Operation(summary = "登录")
|
@Operation(summary = "登录")
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
@@ -34,10 +39,17 @@ public class AuthController {
|
|||||||
return Result.success(authService.currentUser());
|
return Result.success(authService.currentUser());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "当前用户可见的顶部导航")
|
||||||
|
@GetMapping("/menus")
|
||||||
|
public Result<List<String>> menus() {
|
||||||
|
return Result.success(authService.currentMenus());
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "登出")
|
@Operation(summary = "登出")
|
||||||
@PostMapping("/logout")
|
@PostMapping("/logout")
|
||||||
public Result<Void> logout() {
|
public Result<Void> logout() {
|
||||||
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
|
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
|
||||||
|
loginLogService.recordLogout(UserContext.currentUserId());
|
||||||
return Result.success();
|
return Result.success();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.banben.modules.auth.controller;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.support.AdminAccess;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.vo.AccessDimensionItem;
|
||||||
|
import com.banben.modules.auth.vo.AccessOverview;
|
||||||
|
import com.banben.modules.auth.vo.AccessTrendPoint;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台管理 - 登录日志。
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-登录日志")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/login-logs")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoginLogController {
|
||||||
|
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
private final AdminAccess adminAccess;
|
||||||
|
|
||||||
|
@Operation(summary = "登录日志分页(支持账号/姓名/单位关键字、在线状态、登录时间区间)")
|
||||||
|
@GetMapping("/page")
|
||||||
|
public Result<PageResult<LoginLog>> page(LoginLogQuery query) {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.page(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "登录日志概览:会话总数 / 当前在线 / 今日登录")
|
||||||
|
@GetMapping("/summary")
|
||||||
|
public Result<LoginLogSummary> summary() {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.summary());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "网络访问概览:历史/本月/本周/今日 的人次与人数")
|
||||||
|
@GetMapping("/access-overview")
|
||||||
|
public Result<AccessOverview> accessOverview() {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.accessOverview());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "网络访问趋势:按 小时/日/周/月/年 分桶(可指定时段)")
|
||||||
|
@GetMapping("/access-trend")
|
||||||
|
public Result<List<AccessTrendPoint>> accessTrend(
|
||||||
|
@RequestParam(defaultValue = "hour") String granularity,
|
||||||
|
@RequestParam(required = false) String start,
|
||||||
|
@RequestParam(required = false) String end) {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.accessTrend(granularity, start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "网络访问维度统计:按 IP/单位/账号/类型 分组(可指定时段)")
|
||||||
|
@GetMapping("/access-dimension")
|
||||||
|
public Result<List<AccessDimensionItem>> accessDimension(
|
||||||
|
@RequestParam(defaultValue = "ip") String dimension,
|
||||||
|
@RequestParam(required = false) String start,
|
||||||
|
@RequestParam(required = false) String end,
|
||||||
|
@RequestParam(defaultValue = "20") int limit) {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.accessDimension(dimension, start, end, limit));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.banben.modules.auth.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志查询条件。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "登录日志查询条件")
|
||||||
|
public class LoginLogQuery {
|
||||||
|
|
||||||
|
@Schema(description = "页码,从1开始", example = "1")
|
||||||
|
private Long current = 1L;
|
||||||
|
|
||||||
|
@Schema(description = "每页条数", example = "20")
|
||||||
|
private Long size = 20L;
|
||||||
|
|
||||||
|
@Schema(description = "关键字:匹配账号 / 姓名 / 单位")
|
||||||
|
private String keyword;
|
||||||
|
|
||||||
|
/** ONLINE 在线 / OFFLINE 离线 / 空 全部 */
|
||||||
|
@Schema(description = "状态:ONLINE 在线 / OFFLINE 离线 / 空 全部")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间起(含,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss)")
|
||||||
|
private String loginStart;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间止(含)")
|
||||||
|
private String loginEnd;
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ package com.banben.modules.auth.dto;
|
|||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 登录响应。
|
* 登录响应。
|
||||||
*/
|
*/
|
||||||
@@ -27,4 +29,7 @@ public class LoginResponse {
|
|||||||
|
|
||||||
@Schema(description = "所属单位")
|
@Schema(description = "所属单位")
|
||||||
private String orgName;
|
private String orgName;
|
||||||
|
|
||||||
|
@Schema(description = "可见的顶部导航编码")
|
||||||
|
private List<String> menus;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.banben.modules.auth.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志(会话维度)。
|
||||||
|
*
|
||||||
|
* <p>一次成功登录产生一条会话记录:{@code online=1}、{@code logoutTime=null};
|
||||||
|
* 用户主动退出时回填 {@code logoutTime} 并置 {@code online=0}。
|
||||||
|
* 「在线」状态以 {@code logoutTime 为 null} 为准,前端据此展示在线/离线。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("login_log")
|
||||||
|
@Schema(description = "用户登录日志(会话维度:一次登录一条,登出置 logout_time)")
|
||||||
|
public class LoginLog implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "主键")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "用户ID")
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
@Schema(description = "登录账号")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Schema(description = "姓名")
|
||||||
|
private String realName;
|
||||||
|
|
||||||
|
@Schema(description = "所属单位")
|
||||||
|
private String orgName;
|
||||||
|
|
||||||
|
@Schema(description = "登录IP")
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
@Schema(description = "浏览器/客户端标识")
|
||||||
|
private String userAgent;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间")
|
||||||
|
private LocalDateTime loginTime;
|
||||||
|
|
||||||
|
@Schema(description = "退出时间,未退出为 null")
|
||||||
|
private LocalDateTime logoutTime;
|
||||||
|
|
||||||
|
@Schema(description = "是否在线:1在线 0离线")
|
||||||
|
private Integer online;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.banben.modules.auth.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志 Mapper。
|
||||||
|
*/
|
||||||
|
public interface LoginLogMapper extends BaseMapper<LoginLog> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.auth.nav;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 顶部导航。编码与前端路由一致,角色按编码授权。
|
||||||
|
*/
|
||||||
|
public final class NavMenus {
|
||||||
|
|
||||||
|
public static final List<String> CODES = List.of(
|
||||||
|
"dashboard",
|
||||||
|
"search",
|
||||||
|
"hotwords",
|
||||||
|
"special",
|
||||||
|
"deposit",
|
||||||
|
"analysis",
|
||||||
|
"resource",
|
||||||
|
"collect",
|
||||||
|
"sync",
|
||||||
|
"governance",
|
||||||
|
"admin"
|
||||||
|
);
|
||||||
|
|
||||||
|
private NavMenus() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean contains(String code) {
|
||||||
|
return code != null && CODES.contains(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import com.banben.modules.auth.dto.LoginRequest;
|
|||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.dto.LoginResponse;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证服务。
|
* 认证服务。
|
||||||
*/
|
*/
|
||||||
@@ -18,4 +20,9 @@ public interface AuthService {
|
|||||||
* 查询当前登录用户完整信息。
|
* 查询当前登录用户完整信息。
|
||||||
*/
|
*/
|
||||||
SysUser currentUser();
|
SysUser currentUser();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前用户可见的顶部导航编码。
|
||||||
|
*/
|
||||||
|
List<String> currentMenus();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.banben.modules.auth.service;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.vo.AccessDimensionItem;
|
||||||
|
import com.banben.modules.auth.vo.AccessOverview;
|
||||||
|
import com.banben.modules.auth.vo.AccessTrendPoint;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志服务。
|
||||||
|
*/
|
||||||
|
public interface LoginLogService {
|
||||||
|
|
||||||
|
/** 记录一次成功登录(会话开始)。 */
|
||||||
|
void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent);
|
||||||
|
|
||||||
|
/** 记录退出:回填该用户最近一条未退出的会话。 */
|
||||||
|
void recordLogout(Long userId);
|
||||||
|
|
||||||
|
/** 分页查询登录日志。 */
|
||||||
|
PageResult<LoginLog> page(LoginLogQuery query);
|
||||||
|
|
||||||
|
/** 概览统计:总数 / 在线 / 今日登录。 */
|
||||||
|
LoginLogSummary summary();
|
||||||
|
|
||||||
|
/** 网络访问概览:历史 / 本月 / 本周 / 今日 的人次与人数。 */
|
||||||
|
AccessOverview accessOverview();
|
||||||
|
|
||||||
|
/** 网络访问趋势:按 小时/日/周/月/年 分桶统计。 */
|
||||||
|
List<AccessTrendPoint> accessTrend(String granularity, String start, String end);
|
||||||
|
|
||||||
|
/** 网络访问维度统计:按 IP / 单位 / 账号 / 类型 分组。 */
|
||||||
|
List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit);
|
||||||
|
}
|
||||||
@@ -1,22 +1,32 @@
|
|||||||
package com.banben.modules.auth.service.impl;
|
package com.banben.modules.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.banben.common.BusinessException;
|
import com.banben.common.BusinessException;
|
||||||
import com.banben.modules.auth.context.UserContext;
|
import com.banben.modules.auth.context.UserContext;
|
||||||
import com.banben.modules.auth.dto.LoginRequest;
|
import com.banben.modules.auth.dto.LoginRequest;
|
||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.dto.LoginResponse;
|
||||||
import com.banben.modules.admin.entity.SysRole;
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import com.banben.modules.auth.nav.NavMenus;
|
||||||
import com.banben.modules.auth.service.AuthService;
|
import com.banben.modules.auth.service.AuthService;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
import com.banben.modules.auth.util.JwtUtil;
|
import com.banben.modules.auth.util.JwtUtil;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证服务实现。
|
* 认证服务实现。
|
||||||
@@ -28,8 +38,10 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
|
|
||||||
private final SysUserMapper sysUserMapper;
|
private final SysUserMapper sysUserMapper;
|
||||||
private final SysRoleMapper sysRoleMapper;
|
private final SysRoleMapper sysRoleMapper;
|
||||||
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final JwtUtil jwtUtil;
|
private final JwtUtil jwtUtil;
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LoginResponse login(LoginRequest request) {
|
public LoginResponse login(LoginRequest request) {
|
||||||
@@ -54,6 +66,12 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
user.setLastLoginTime(LocalDateTime.now());
|
user.setLastLoginTime(LocalDateTime.now());
|
||||||
sysUserMapper.updateById(user);
|
sysUserMapper.updateById(user);
|
||||||
|
|
||||||
|
// 记录登录日志(会话维度):取客户端 IP 与 UA
|
||||||
|
HttpServletRequest httpReq = currentRequest();
|
||||||
|
String ip = httpReq == null ? null : clientIp(httpReq);
|
||||||
|
String ua = httpReq == null ? null : httpReq.getHeader("User-Agent");
|
||||||
|
loginLogService.recordLogin(user.getId(), user.getUsername(), user.getRealName(), user.getOrgName(), ip, ua);
|
||||||
|
|
||||||
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
|
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
|
||||||
|
|
||||||
LoginResponse response = new LoginResponse();
|
LoginResponse response = new LoginResponse();
|
||||||
@@ -63,9 +81,23 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
response.setRealName(user.getRealName());
|
response.setRealName(user.getRealName());
|
||||||
response.setRole(user.getRole());
|
response.setRole(user.getRole());
|
||||||
response.setOrgName(user.getOrgName());
|
response.setOrgName(user.getOrgName());
|
||||||
|
response.setMenus(menusOf(user));
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> currentMenus() {
|
||||||
|
Long userId = UserContext.currentUserId();
|
||||||
|
if (userId == null) {
|
||||||
|
throw new BusinessException("未登录");
|
||||||
|
}
|
||||||
|
SysUser user = sysUserMapper.selectById(userId);
|
||||||
|
if (user == null) {
|
||||||
|
throw new BusinessException("未登录");
|
||||||
|
}
|
||||||
|
return menusOf(user);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SysUser currentUser() {
|
public SysUser currentUser() {
|
||||||
Long userId = UserContext.currentUserId();
|
Long userId = UserContext.currentUserId();
|
||||||
@@ -78,4 +110,59 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
}
|
}
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<String> menusOf(SysUser user) {
|
||||||
|
if (isAdmin(user)) {
|
||||||
|
return new ArrayList<>(NavMenus.CODES);
|
||||||
|
}
|
||||||
|
if (user.getRoleId() == null) {
|
||||||
|
return new ArrayList<>(NavMenus.CODES);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return roleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, user.getRoleId()))
|
||||||
|
.stream()
|
||||||
|
.map(SysRoleMenu::getMenuCode)
|
||||||
|
.filter(NavMenus::contains)
|
||||||
|
.distinct()
|
||||||
|
.toList();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("读取导航权限失败,暂时开放全部栏目:{}", e.getMessage());
|
||||||
|
return new ArrayList<>(NavMenus.CODES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAdmin(SysUser user) {
|
||||||
|
if (user.getRole() != null && "ADMIN".equalsIgnoreCase(user.getRole())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (user.getRoleId() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
SysRole role = sysRoleMapper.selectById(user.getRoleId());
|
||||||
|
return role != null && "ADMIN".equalsIgnoreCase(role.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从请求上下文取当前 HttpServletRequest(非 Web 请求线程下为 null)。 */
|
||||||
|
private HttpServletRequest currentRequest() {
|
||||||
|
try {
|
||||||
|
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||||
|
return attrs == null ? null : attrs.getRequest();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取真实客户端 IP,兼容反向代理的 X-Forwarded-For。 */
|
||||||
|
private String clientIp(HttpServletRequest request) {
|
||||||
|
String forwarded = request.getHeader("X-Forwarded-For");
|
||||||
|
if (StrUtil.isNotBlank(forwarded)) {
|
||||||
|
// X-Forwarded-For 格式:client, proxy1, proxy2
|
||||||
|
return StrUtil.subPre(forwarded.trim(), forwarded.indexOf(',') < 0 ? forwarded.length() : forwarded.indexOf(',')).trim();
|
||||||
|
}
|
||||||
|
String realIp = request.getHeader("X-Real-IP");
|
||||||
|
if (StrUtil.isNotBlank(realIp)) {
|
||||||
|
return realIp.trim();
|
||||||
|
}
|
||||||
|
return request.getRemoteAddr();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package com.banben.modules.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.mapper.LoginLogMapper;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.vo.AccessDimensionItem;
|
||||||
|
import com.banben.modules.auth.vo.AccessOverview;
|
||||||
|
import com.banben.modules.auth.vo.AccessTrendPoint;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志服务实现。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoginLogServiceImpl implements LoginLogService {
|
||||||
|
|
||||||
|
private final LoginLogMapper logMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent) {
|
||||||
|
try {
|
||||||
|
LoginLog entity = new LoginLog();
|
||||||
|
entity.setUserId(userId);
|
||||||
|
entity.setUsername(username);
|
||||||
|
entity.setRealName(realName);
|
||||||
|
entity.setOrgName(orgName);
|
||||||
|
entity.setIp(ip);
|
||||||
|
entity.setUserAgent(userAgent == null ? null : StrUtil.subPre(userAgent, 500));
|
||||||
|
entity.setLoginTime(LocalDateTime.now());
|
||||||
|
entity.setOnline(1);
|
||||||
|
logMapper.insert(entity);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 日志写入失败不应影响登录主流程
|
||||||
|
log.warn("记录登录日志失败(不影响登录):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void recordLogout(Long userId) {
|
||||||
|
if (userId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
LoginLog entity = new LoginLog();
|
||||||
|
entity.setLogoutTime(LocalDateTime.now());
|
||||||
|
entity.setOnline(0);
|
||||||
|
// 仅关闭该用户最近一条尚未退出的会话
|
||||||
|
logMapper.update(entity, new QueryWrapper<LoginLog>()
|
||||||
|
.eq("user_id", userId)
|
||||||
|
.isNull("logout_time")
|
||||||
|
.orderByDesc("login_time")
|
||||||
|
.last("LIMIT 1"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("记录退出日志失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<LoginLog> page(LoginLogQuery q) {
|
||||||
|
long current = q.getCurrent() == null ? 1L : q.getCurrent();
|
||||||
|
long size = q.getSize() == null ? 20L : q.getSize();
|
||||||
|
try {
|
||||||
|
QueryWrapper<LoginLog> w = new QueryWrapper<>();
|
||||||
|
if (StrUtil.isNotBlank(q.getKeyword())) {
|
||||||
|
String kw = q.getKeyword().trim();
|
||||||
|
w.and(x -> x.like("username", kw).or().like("real_name", kw).or().like("org_name", kw));
|
||||||
|
}
|
||||||
|
if ("ONLINE".equalsIgnoreCase(q.getStatus())) {
|
||||||
|
w.eq("online", 1).isNull("logout_time");
|
||||||
|
} else if ("OFFLINE".equalsIgnoreCase(q.getStatus())) {
|
||||||
|
w.isNotNull("logout_time");
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(q.getLoginStart())) {
|
||||||
|
w.ge("login_time", q.getLoginStart().trim());
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(q.getLoginEnd())) {
|
||||||
|
// 结束日期按当天 23:59:59 包含整日,避免漏掉结束日当天的记录
|
||||||
|
String end = q.getLoginEnd().trim();
|
||||||
|
if (end.length() == 10) {
|
||||||
|
end = end + " 23:59:59";
|
||||||
|
}
|
||||||
|
w.le("login_time", end);
|
||||||
|
}
|
||||||
|
w.orderByDesc("login_time");
|
||||||
|
Page<LoginLog> page = logMapper.selectPage(Page.of(current, size), w);
|
||||||
|
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 表缺失等异常时降级为空结果,避免进入后台管理时整页报「操作失败」
|
||||||
|
log.warn("分页查询登录日志失败:{}", e.getMessage());
|
||||||
|
return PageResult.of(new ArrayList<>(), 0L, current, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public LoginLogSummary summary() {
|
||||||
|
LoginLogSummary s = new LoginLogSummary();
|
||||||
|
try {
|
||||||
|
s.setTotal(logMapper.selectCount(new QueryWrapper<>()));
|
||||||
|
s.setOnline(logMapper.selectCount(new QueryWrapper<LoginLog>().eq("online", 1).isNull("logout_time")));
|
||||||
|
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
|
||||||
|
s.setToday(logMapper.selectCount(new QueryWrapper<LoginLog>().ge("login_time", startOfToday)));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计登录日志概览失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 网络访问统计 ====================
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AccessOverview accessOverview() {
|
||||||
|
AccessOverview o = new AccessOverview();
|
||||||
|
try {
|
||||||
|
long[] history = countPair(null);
|
||||||
|
o.setHistoryCount(history[0]);
|
||||||
|
o.setHistoryUsers(history[1]);
|
||||||
|
|
||||||
|
long[] month = countPair(LocalDate.now().withDayOfMonth(1).atStartOfDay());
|
||||||
|
o.setMonthCount(month[0]);
|
||||||
|
o.setMonthUsers(month[1]);
|
||||||
|
|
||||||
|
long[] week = countPair(LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay());
|
||||||
|
o.setWeekCount(week[0]);
|
||||||
|
o.setWeekUsers(week[1]);
|
||||||
|
|
||||||
|
long[] today = countPair(LocalDate.now().atStartOfDay());
|
||||||
|
o.setTodayCount(today[0]);
|
||||||
|
o.setTodayUsers(today[1]);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计网络访问概览失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AccessTrendPoint> accessTrend(String granularity, String start, String end) {
|
||||||
|
String expr = granularityExpr(granularity);
|
||||||
|
QueryWrapper<LoginLog> w = new QueryWrapper<>();
|
||||||
|
w.select(expr + " AS bucket", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
|
||||||
|
applyRange(w, start, end);
|
||||||
|
w.groupBy(expr).orderByAsc("bucket");
|
||||||
|
List<AccessTrendPoint> list = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
for (Map<String, Object> m : logMapper.selectMaps(w)) {
|
||||||
|
Object b = m.get("bucket");
|
||||||
|
list.add(new AccessTrendPoint(b == null ? "" : b.toString(),
|
||||||
|
toLong(m.get("cnt")), toLong(m.get("users"))));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计网络访问趋势失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AccessDimensionItem> accessDimension(String dimension, String start, String end, int limit) {
|
||||||
|
String col = "ip";
|
||||||
|
if ("org".equals(dimension)) {
|
||||||
|
col = "org_name";
|
||||||
|
} else if ("account".equals(dimension)) {
|
||||||
|
col = "username";
|
||||||
|
} else if ("type".equals(dimension)) {
|
||||||
|
col = "online";
|
||||||
|
}
|
||||||
|
QueryWrapper<LoginLog> w = new QueryWrapper<>();
|
||||||
|
w.select(col + " AS name", "COUNT(*) AS cnt", "COUNT(DISTINCT user_id) AS users");
|
||||||
|
// 字符串维度排除空值;type 维度(online 为整数)仅排除 NULL,避免 integer <> '' 报错
|
||||||
|
if ("type".equals(dimension)) {
|
||||||
|
w.isNotNull(col);
|
||||||
|
} else {
|
||||||
|
w.isNotNull(col).ne(col, "");
|
||||||
|
}
|
||||||
|
applyRange(w, start, end);
|
||||||
|
w.groupBy(col).orderByDesc("cnt").last("LIMIT " + Math.max(1, limit));
|
||||||
|
List<AccessDimensionItem> list = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
for (Map<String, Object> m : logMapper.selectMaps(w)) {
|
||||||
|
Object raw = m.get("name");
|
||||||
|
String name = raw == null ? "未知" : raw.toString();
|
||||||
|
if ("type".equals(dimension)) {
|
||||||
|
name = "1".equals(name) ? "在线" : "0".equals(name) ? "离线" : name;
|
||||||
|
}
|
||||||
|
list.add(new AccessDimensionItem(name, toLong(m.get("cnt")), toLong(m.get("users"))));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计网络访问维度失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 人次 + 去重人数(按给定起始时间)。 */
|
||||||
|
private long[] countPair(LocalDateTime ge) {
|
||||||
|
QueryWrapper<LoginLog> w = new QueryWrapper<>();
|
||||||
|
w.select("COUNT(*) AS c", "COUNT(DISTINCT user_id) AS u");
|
||||||
|
if (ge != null) {
|
||||||
|
w.ge("login_time", ge);
|
||||||
|
}
|
||||||
|
List<Map<String, Object>> maps = logMapper.selectMaps(w);
|
||||||
|
long c = 0, u = 0;
|
||||||
|
if (!maps.isEmpty()) {
|
||||||
|
Map<String, Object> m = maps.get(0);
|
||||||
|
c = toLong(m.get("c"));
|
||||||
|
u = toLong(m.get("u"));
|
||||||
|
}
|
||||||
|
return new long[]{c, u};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 时间分桶表达式(PostgreSQL)。 */
|
||||||
|
private String granularityExpr(String g) {
|
||||||
|
if ("day".equals(g)) {
|
||||||
|
return "to_char(login_time, 'YYYY-MM-DD')";
|
||||||
|
}
|
||||||
|
if ("week".equals(g)) {
|
||||||
|
return "to_char(date_trunc('week', login_time), 'YYYY-MM-DD')";
|
||||||
|
}
|
||||||
|
if ("month".equals(g)) {
|
||||||
|
return "to_char(login_time, 'YYYY-MM')";
|
||||||
|
}
|
||||||
|
if ("year".equals(g)) {
|
||||||
|
return "to_char(login_time, 'YYYY')";
|
||||||
|
}
|
||||||
|
// 默认按小时(含日期,避免跨天合并)
|
||||||
|
return "to_char(login_time, 'YYYY-MM-DD HH24')";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 时间区间条件:start 含当天 00:00,end 含当天 23:59:59。 */
|
||||||
|
private void applyRange(QueryWrapper<LoginLog> w, String start, String end) {
|
||||||
|
if (StrUtil.isNotBlank(start)) {
|
||||||
|
w.ge("login_time", start.trim());
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(end)) {
|
||||||
|
String e = end.trim();
|
||||||
|
if (e.length() == 10) {
|
||||||
|
e = e + " 23:59:59";
|
||||||
|
}
|
||||||
|
w.le("login_time", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long toLong(Object value) {
|
||||||
|
return value instanceof Number number ? number.longValue() : 0L;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.auth.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络访问维度统计项(按 IP / 单位 / 账号 / 类型)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "网络访问维度统计项")
|
||||||
|
public class AccessDimensionItem {
|
||||||
|
|
||||||
|
@Schema(description = "维度值(IP / 单位 / 账号 / 在线状态)")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "访问人次")
|
||||||
|
private long count;
|
||||||
|
|
||||||
|
@Schema(description = "访问人数(去重)")
|
||||||
|
private long users;
|
||||||
|
|
||||||
|
public AccessDimensionItem() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public AccessDimensionItem(String name, long count, long users) {
|
||||||
|
this.name = name;
|
||||||
|
this.count = count;
|
||||||
|
this.users = users;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.banben.modules.auth.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络访问统计概览。
|
||||||
|
*
|
||||||
|
* <p>人次 = 登录会话记录数;人数 = 去重用户数(按 user_id)。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "网络访问统计概览")
|
||||||
|
public class AccessOverview {
|
||||||
|
|
||||||
|
@Schema(description = "历史访问人次")
|
||||||
|
private long historyCount;
|
||||||
|
|
||||||
|
@Schema(description = "历史访问人数(去重)")
|
||||||
|
private long historyUsers;
|
||||||
|
|
||||||
|
@Schema(description = "本月访问人次")
|
||||||
|
private long monthCount;
|
||||||
|
|
||||||
|
@Schema(description = "本月访问人数(去重)")
|
||||||
|
private long monthUsers;
|
||||||
|
|
||||||
|
@Schema(description = "本周访问人次")
|
||||||
|
private long weekCount;
|
||||||
|
|
||||||
|
@Schema(description = "本周访问人数(去重)")
|
||||||
|
private long weekUsers;
|
||||||
|
|
||||||
|
@Schema(description = "今日访问人次")
|
||||||
|
private long todayCount;
|
||||||
|
|
||||||
|
@Schema(description = "今日访问人数(去重)")
|
||||||
|
private long todayUsers;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.auth.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络访问趋势(按时间分桶)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "网络访问趋势(按时间分桶)")
|
||||||
|
public class AccessTrendPoint {
|
||||||
|
|
||||||
|
@Schema(description = "时间桶,如 2026-11-04 08 / 2026-11 / 2026")
|
||||||
|
private String bucket;
|
||||||
|
|
||||||
|
@Schema(description = "访问人次")
|
||||||
|
private long count;
|
||||||
|
|
||||||
|
@Schema(description = "访问人数(去重)")
|
||||||
|
private long users;
|
||||||
|
|
||||||
|
public AccessTrendPoint() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public AccessTrendPoint(String bucket, long count, long users) {
|
||||||
|
this.bucket = bucket;
|
||||||
|
this.count = count;
|
||||||
|
this.users = users;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.banben.modules.auth.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志概览统计。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "登录日志概览统计")
|
||||||
|
public class LoginLogSummary {
|
||||||
|
|
||||||
|
@Schema(description = "会话总数")
|
||||||
|
private long total;
|
||||||
|
|
||||||
|
@Schema(description = "当前在线人数(未退出的会话数)")
|
||||||
|
private long online;
|
||||||
|
|
||||||
|
@Schema(description = "今日登录次数")
|
||||||
|
private long today;
|
||||||
|
}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
package com.banben.modules.resource.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.resource.entity.ResourceSource;
|
||||||
|
import com.banben.modules.resource.mapper.ResourceSourceMapper;
|
||||||
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
|
import com.banben.modules.resource.mapper.VersionResourceMapper;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源多来源管理接口。
|
||||||
|
*
|
||||||
|
* <p>对应检索概览页「一条结果可有多个来源,点击可下载」的能力:
|
||||||
|
* 一条文献可挂载到多个资源库 / 来源馆,概览页据此渲染多个来源并分别下载。</p>
|
||||||
|
*/
|
||||||
|
@Tag(name = "版本资源-多来源管理", description = "文献多来源(资源库)的增删改查")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/resource")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ResourceSourceController {
|
||||||
|
|
||||||
|
private final ResourceSourceMapper sourceMapper;
|
||||||
|
private final VersionResourceMapper resourceMapper;
|
||||||
|
|
||||||
|
@Operation(summary = "查询某条文献的全部来源(按展示顺序)")
|
||||||
|
@GetMapping("/{id}/sources")
|
||||||
|
public Result<List<ResourceSource>> list(@PathVariable Long id) {
|
||||||
|
QueryWrapper<ResourceSource> w = new QueryWrapper<>();
|
||||||
|
w.eq("resource_id", id).eq("deleted", 0).orderByAsc("sort_no");
|
||||||
|
return Result.success(sourceMapper.selectList(w));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "为某条文献新增一个来源")
|
||||||
|
@PostMapping("/{id}/sources")
|
||||||
|
public Result<Long> add(@PathVariable Long id, @RequestBody ResourceSource source) {
|
||||||
|
VersionResource r = resourceMapper.selectById(id);
|
||||||
|
if (r == null) {
|
||||||
|
return Result.failed("文献不存在:" + id);
|
||||||
|
}
|
||||||
|
source.setId(null);
|
||||||
|
source.setResourceId(id);
|
||||||
|
sourceMapper.insert(source);
|
||||||
|
return Result.success(source.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "更新某个来源")
|
||||||
|
@PutMapping("/sources/{sourceId}")
|
||||||
|
public Result<Void> update(@PathVariable Long sourceId, @RequestBody ResourceSource source) {
|
||||||
|
source.setId(sourceId);
|
||||||
|
source.setResourceId(null); // 不允许跨文献改归属
|
||||||
|
sourceMapper.updateById(source);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除某个来源(逻辑删除)")
|
||||||
|
@DeleteMapping("/sources/{sourceId}")
|
||||||
|
public Result<Void> remove(@PathVariable Long sourceId) {
|
||||||
|
sourceMapper.deleteById(sourceId);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.banben.modules.resource.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源多来源(一条文献可来自多个资源库 / 来源馆)。
|
||||||
|
*
|
||||||
|
* <p>对应招标文件检索结果概览页要求:「一条结果可有多个来源,按资源库图标+名称展示,点击可下载」。
|
||||||
|
* 主表 {@link VersionResource} 上的 source_library / source_repo / fulltext_url 等字段作为
|
||||||
|
* 「主来源」兜底;本表保存该文献的全部来源,概览页据此渲染多个可分别下载的来源。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("resource_source")
|
||||||
|
@Schema(description = "版本资源多来源")
|
||||||
|
public class ResourceSource implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "来源记录主键")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "关联版本资源主记录ID(version_resource.id)")
|
||||||
|
private Long resourceId;
|
||||||
|
|
||||||
|
@Schema(description = "来源资源库名")
|
||||||
|
private String sourceRepo;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆")
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆地址(IP:端口或域名)")
|
||||||
|
private String sourceLibraryAddr;
|
||||||
|
|
||||||
|
@Schema(description = "全文地址(下载地址)")
|
||||||
|
private String fulltextUrl;
|
||||||
|
|
||||||
|
@Schema(description = "加工编号(该来源库内的编号)")
|
||||||
|
private String processNo;
|
||||||
|
|
||||||
|
@Schema(description = "媒体类型(纸质/电子,可选,便于概览页区分)")
|
||||||
|
private String mediaType;
|
||||||
|
|
||||||
|
@Schema(description = "展示顺序,数值小的靠前")
|
||||||
|
private Integer sortNo;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
@Schema(description = "更新时间")
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
@Schema(description = "逻辑删除:0未删 1已删")
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -153,9 +153,17 @@ public class VersionResource implements Serializable {
|
|||||||
@Schema(description = "作者单位(责任者所属机构)")
|
@Schema(description = "作者单位(责任者所属机构)")
|
||||||
private String authorOrg;
|
private String authorOrg;
|
||||||
|
|
||||||
@Schema(description = "来源资源库名")
|
@Schema(description = "来源资源库名(主来源兜底,多来源详见 sources)")
|
||||||
private String sourceRepo;
|
private String sourceRepo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多来源列表(一条文献可来自多个资源库)。
|
||||||
|
* 非数据库字段,由检索/细览接口按 resource_id 批量挂载,供概览页按来源展示并分别下载。
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "多来源列表:一条文献可来自多个资源库,概览页按来源图标+名称展示并可分别下载")
|
||||||
|
private java.util.List<ResourceSource> sources;
|
||||||
|
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@TableField(fill = FieldFill.INSERT)
|
||||||
@Schema(description = "创建时间")
|
@Schema(description = "创建时间")
|
||||||
private LocalDateTime createTime;
|
private LocalDateTime createTime;
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.resource.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.resource.entity.ResourceSource;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源多来源 Mapper。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface ResourceSourceMapper extends BaseMapper<ResourceSource> {
|
||||||
|
}
|
||||||
+45
-66
@@ -36,45 +36,30 @@ public class VersionResourceExcelService {
|
|||||||
BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
|
BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 模板列定义,严格按询价文件给出的著录要素顺序排列(共 32 个 + 是否特藏)。
|
|
||||||
* header 中的「*」表示必备;导入时按 header 名称匹配,调整列顺序不影响解析。
|
|
||||||
* 字段顺序与 {@link #SAMPLES} 严格一一对应。
|
|
||||||
*/
|
|
||||||
private static final List<Column> COLUMNS = List.of(
|
private static final List<Column> COLUMNS = List.of(
|
||||||
new Column("加工编号*", "processNo", VersionResource::setProcessNo, 128, "必备;著录资源的加工编号,系统中已存在则更新该条"),
|
new Column("正题名*", "title", VersionResource::setTitle, 512, "必填;示例行可覆盖或直接删除"),
|
||||||
new Column("正题名*", "title", VersionResource::setTitle, 512, "必备;资源主要名称,示例行可覆盖或直接删除"),
|
new Column("加工编号", "processNo", VersionResource::setProcessNo, 128, "选填;系统中已存在则更新该条"),
|
||||||
new Column("其他题名", "otherTitle", VersionResource::setOtherTitle, 512, "有则必备;其他语种题名或限定/补充/解释正题名的题名信息"),
|
new Column("责任者", "author", VersionResource::setAuthor, 512, "选填;多人用 ; 分隔"),
|
||||||
new Column("责任者名称", "author", VersionResource::setAuthor, 512, "有则必备;主要责任者或贡献者,多人用 ; 分隔"),
|
new Column("责任方式", "responsibility", VersionResource::setResponsibility, 256, "选填;如 著、编、译"),
|
||||||
new Column("责任方式", "responsibility", VersionResource::setResponsibility, 256, "有则必备;如 著、编、译、主编"),
|
new Column("中图分类", "clcCode", VersionResource::setClcCode, 64, "选填;如 G250.7"),
|
||||||
new Column("中图分类*", "clcCode", VersionResource::setClcCode, 64, "必备;CLC第五版类号,如 G250.7"),
|
new Column("主题词", "keywords", VersionResource::setKeywords, 512, "选填;多个用 ; 分隔"),
|
||||||
new Column("主题词或关键词*", "keywords", VersionResource::setKeywords, 512, "必备;多个用 ; 分隔,受控词依 CCT 标引"),
|
new Column("摘要", "summary", VersionResource::setSummary, 2000, "选填;建议不少于 100 字"),
|
||||||
new Column("摘要*", "summary", VersionResource::setSummary, 4000, "必备;自由行文概括描述,建议不少于 100 字"),
|
new Column("出版年份", "publishYear", VersionResource::setPublishYear, 8, "选填;格式 yyyy"),
|
||||||
new Column("附注", "note", VersionResource::setNote, 4000, "有则必备;其他补充说明,版权信息著录于此,不同类型信息重复本字段"),
|
new Column("出版者", "publisher", VersionResource::setPublisher, 256, "选填"),
|
||||||
new Column("出版者名称", "publisher", VersionResource::setPublisher, 256, "有则必备;出版者或颁布者"),
|
new Column("出版地", "publishPlace", VersionResource::setPublishPlace, 128, "选填"),
|
||||||
new Column("出版地", "publishPlace", VersionResource::setPublishPlace, 128, "有则必备;出版者所在城市,不详可著录省名或国名"),
|
new Column("出版日期", "publishDate", VersionResource::setPublishDate, 32, "选填;如 2026-01-01"),
|
||||||
new Column("出版日期", "publishDate", VersionResource::setPublishDate, 32, "有则必备;如 2026-01-01 或 2026"),
|
new Column("版本版次", "edition", VersionResource::setEdition, 128, "选填"),
|
||||||
new Column("出版年份*", "publishYear", VersionResource::setPublishYear, 8, "必备;格式 yyyy,根据出版日期生成"),
|
new Column("ISBN", "isbn", VersionResource::setIsbn, 64, "选填"),
|
||||||
new Column("加工日期*", "processDate", VersionResource::setProcessDate, 16, "必备;格式 yyyyMMdd,数据加工时间"),
|
new Column("内容形式", "contentForm", VersionResource::setContentForm, 64, "选填;如 文本"),
|
||||||
new Column("内容形式*", "contentForm", VersionResource::setContentForm, 64, "必备;GB/T 3469-2013,如 文本、图像(测绘型)"),
|
new Column("媒体类型", "mediaType", VersionResource::setMediaType, 32, "选填;纸质 或 电子"),
|
||||||
new Column("媒体类型*", "mediaType", VersionResource::setMediaType, 32, "必备;纸质 或 电子"),
|
new Column("格式", "format", VersionResource::setFormat, 64, "选填;如 PDF"),
|
||||||
new Column("格式*", "format", VersionResource::setFormat, 64, "必备;英文大写,如 TIF;PDF"),
|
new Column("页码", "pageCount", VersionResource::setPageCount, 64, "选填"),
|
||||||
new Column("页码*", "pageCount", VersionResource::setPageCount, 64, "必备;如 2 册(116 页)、132-423 页"),
|
new Column("语种", "language", VersionResource::setLanguage, 16, "选填;三位代码,如 chi"),
|
||||||
new Column("语种*", "language", VersionResource::setLanguage, 16, "必备;3 位语种代码,如 chi"),
|
new Column("来源馆", "sourceLibrary", VersionResource::setSourceLibrary, 256, "选填"),
|
||||||
new Column("关联", "relation", VersionResource::setRelation, 512, "有则必备;相关资源名称或标识符,如丛编、合订"),
|
new Column("数据提交单位", "submitOrg", VersionResource::setSubmitOrg, 256, "选填"),
|
||||||
new Column("时间范围", "timeRange", VersionResource::setTimeRange, 256, "有则必备;内容涉及的时间特征,时代/日期/时间段"),
|
new Column("任务年份", "taskYear", VersionResource::setTaskYear, 8, "选填;格式 yyyy"),
|
||||||
new Column("空间范围", "spaceRange", VersionResource::setSpaceRange, 256, "有则必备;内容涉及的空间特征,地点/地理坐标"),
|
new Column("全文地址", "fulltextUrl", VersionResource::setFulltextUrl, 1024, "选填"),
|
||||||
new Column("版本", "edition", VersionResource::setEdition, 128, "有则必备;如 修订版、影印本、第3版"),
|
new Column("是否特藏", "isSpecial", (r, v) -> { }, 4, "选填;是 或 否")
|
||||||
new Column("ISBN", "isbn", VersionResource::setIsbn, 64, "有则必备;国际标准书号"),
|
|
||||||
new Column("统一书号", "unifiedBookNo", VersionResource::setUnifiedBookNo, 64, "有则必备;统一书号"),
|
|
||||||
new Column("CDOI", "cdoi", VersionResource::setCdoi, 256, "有则必备;数字对象唯一标识"),
|
|
||||||
new Column("发布地址", "publishUrl", VersionResource::setPublishUrl, 1024, "有则必备;因特网或局域网发布地址"),
|
|
||||||
new Column("数据提交单位*", "submitOrg", VersionResource::setSubmitOrg, 256, "必备;提交该数据的单位"),
|
|
||||||
new Column("所属任务年份*", "taskYear", VersionResource::setTaskYear, 8, "必备;联建工作任务年度,格式 yyyy"),
|
|
||||||
new Column("来源馆*", "sourceLibrary", VersionResource::setSourceLibrary, 256, "必备;数据来源馆"),
|
|
||||||
new Column("来源馆地址*", "sourceLibraryAddr", VersionResource::setSourceLibraryAddr, 256, "必备;来源馆远程获取地址,IP:端口或域名"),
|
|
||||||
new Column("全文地址*", "fulltextUrl", VersionResource::setFulltextUrl, 1024, "必备;根据 CDOI 生成,下载全文地址"),
|
|
||||||
new Column("是否特藏", "isSpecial", (r, v) -> { }, 4, "选填;是 或 否,是则展示在特藏推荐模块")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,36 +67,31 @@ public class VersionResourceExcelService {
|
|||||||
* 正题名统一以「示例:」开头,导入时会被自动跳过。
|
* 正题名统一以「示例:」开头,导入时会被自动跳过。
|
||||||
*/
|
*/
|
||||||
private static final String[][] SAMPLES = {
|
private static final String[][] SAMPLES = {
|
||||||
{"EX-2026-0001", "示例:军事理论教程", "军事思想基础", "张明", "著", "E0-43", "军事理论;教程",
|
{"示例:军事理论教程", "EX-2026-0001", "张明", "著", "E0-43", "军事理论;教程",
|
||||||
"系统介绍军事理论的基本概念、发展脉络与研究方法,适用于院校教学参考。",
|
"系统介绍军事理论的基本概念、发展脉络与研究方法,适用于院校教学参考。",
|
||||||
"授权", "军事科学出版社", "北京", "2026-03-01", "2026", "20260301", "文本", "纸质", "PDF", "286", "chi",
|
"2026", "军事科学出版社", "北京", "2026-03-01", "第2版", "978-7-80137-001-1",
|
||||||
"丛书《军事文库》之一", "2020-2026", "中国", "第2版", "978-7-80137-001-1", "", "10.1234/cdoi/EX-2026-0001",
|
"文本", "纸质", "PDF", "286", "chi", "陆军步兵学院图书馆", "陆军步兵学院",
|
||||||
"http://example.org/pub/EX-2026-0001", "陆军步兵学院", "2026", "陆军步兵学院图书馆", "10.1.1.14:5866",
|
"2026", "", "否"},
|
||||||
"http://cdio.example.org/fulltext/EX-2026-0001", "否"},
|
{"示例:版本资源元数据著录规范", "EX-2026-0002", "李华", "编", "G254.3", "元数据;著录",
|
||||||
{"EX-2026-0002", "示例:版本资源元数据著录规范", "元数据标准手册", "李华", "编", "G254.3", "元数据;著录",
|
|
||||||
"依据国家与军队相关标准,规范版本资源元数据的著录字段、格式与质量控制要求。",
|
"依据国家与军队相关标准,规范版本资源元数据的著录字段、格式与质量控制要求。",
|
||||||
"版权所有,仅供内部使用", "国防大学出版社", "北京", "2025-09-15", "2025", "20250915", "文本", "电子", "PDF", "210", "chi",
|
"2025", "国防大学出版社", "北京", "2025-09-15", "第1版", "978-7-5626-002-2",
|
||||||
"", "", "", "第1版", "978-7-5626-002-2", "", "10.1234/cdoi/EX-2026-0002",
|
"文本", "电子", "PDF", "210", "chi", "南京某院校图书馆", "陆军步兵学院",
|
||||||
"http://example.org/pub/EX-2026-0002", "陆军步兵学院", "2026", "南京某院校图书馆", "10.1.1.15:5866",
|
"2026", "http://cdio.example.org/fulltext/EX-2026-0002", "否"},
|
||||||
"http://cdio.example.org/fulltext/EX-2026-0002", "否"},
|
{"示例:中国古代兵书辑要", "EX-2026-0003", "王强", "整理", "E892", "兵书;古籍",
|
||||||
{"EX-2026-0003", "示例:中国古代兵书辑要", "兵书丛刊", "王强", "整理", "E892", "兵书;古籍",
|
|
||||||
"收录先秦至明清重要兵书,附版本源流考述与校勘记,供版本比对研究使用。",
|
"收录先秦至明清重要兵书,附版本源流考述与校勘记,供版本比对研究使用。",
|
||||||
"影印底本藏于国家图书馆", "中华书局", "北京", "2024-06-20", "2024", "20240620", "文本", "纸质", "PDF", "520", "chi",
|
"2024", "中华书局", "北京", "2024-06-20", "影印本", "978-7-101-0033-3",
|
||||||
"合订《武经七书》", "", "", "影印本", "978-7-101-0033-3", "", "10.1234/cdoi/EX-2026-0003",
|
"文本", "纸质", "PDF", "520", "chi", "陆军勤务学院图书馆", "陆军勤务学院",
|
||||||
"", "陆军勤务学院", "2025", "陆军勤务学院图书馆", "10.1.1.16:5866",
|
"2025", "", "是"},
|
||||||
"", "是"},
|
{"示例:数字图书馆建设实践", "EX-2026-0004", "赵敏", "著", "G250.76", "数字图书馆;建设",
|
||||||
{"EX-2026-0004", "示例:数字图书馆建设实践", "", "赵敏", "著", "G250.76", "数字图书馆;建设",
|
|
||||||
"围绕数字图书馆的资源组织、平台架构与服务模式展开,含多个建设案例分析。",
|
"围绕数字图书馆的资源组织、平台架构与服务模式展开,含多个建设案例分析。",
|
||||||
"", "国家图书馆出版社", "北京", "2023-11-10", "2023", "20231110", "文本", "电子", "EPUB", "340", "chi",
|
"2023", "国家图书馆出版社", "北京", "2023-11-10", "第1版", "978-7-5013-0044-4",
|
||||||
"", "", "", "第1版", "978-7-5013-0044-4", "", "10.1234/cdoi/EX-2026-0004",
|
"文本", "电子", "EPUB", "340", "chi", "陆军指挥学院图书馆", "陆军指挥学院",
|
||||||
"http://example.org/pub/EX-2026-0004", "陆军指挥学院", "2025", "陆军指挥学院图书馆", "10.1.1.17:5866",
|
"2025", "", "否"},
|
||||||
"", "否"},
|
{"示例:外军装备发展研究", "EX-2026-0005", "陈刚", "主编", "E92", "装备;外军",
|
||||||
{"EX-2026-0005", "示例:外军装备发展研究", "装备技术译文集", "陈刚", "主编", "E92", "装备;外军",
|
|
||||||
"分析外军主战装备的发展路径、技术特点与体系构成,供装备论证参考。",
|
"分析外军主战装备的发展路径、技术特点与体系构成,供装备论证参考。",
|
||||||
"内部资料", "国防工业出版社", "北京", "2025-05-08", "2025", "20250508", "文本", "纸质", "PDF", "415", "chi",
|
"2025", "国防工业出版社", "北京", "2025-05-08", "", "978-7-118-0055-5",
|
||||||
"", "", "", "", "978-7-118-0055-5", "", "10.1234/cdoi/EX-2026-0005",
|
"文本", "纸质", "PDF", "415", "chi", "陆军航空兵学院图书馆", "陆军航空兵学院",
|
||||||
"", "陆军航空兵学院", "2026", "陆军航空兵学院图书馆", "10.1.1.18:5866",
|
"2026", "", "否"}
|
||||||
"", "否"}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ==================== 模板导出 ====================
|
// ==================== 模板导出 ====================
|
||||||
@@ -273,13 +253,12 @@ public class VersionResourceExcelService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2) 判断第 2 行是否为说明行(说明行首格以 必备 / 有则必备 / 选填 开头)
|
// 2) 判断第 2 行是否为说明行
|
||||||
int startRow = 1;
|
int startRow = 1;
|
||||||
Row second = sheet.getRow(1);
|
Row second = sheet.getRow(1);
|
||||||
if (second != null) {
|
if (second != null) {
|
||||||
String first = cellText(second.getCell(0));
|
String first = cellText(second.getCell(0));
|
||||||
if (first != null && (first.startsWith("必备") || first.startsWith("有则必备")
|
if (first != null && (first.startsWith("必填") || first.startsWith("选填"))) {
|
||||||
|| first.startsWith("选填") || first.startsWith("必填"))) {
|
|
||||||
startRow = 2;
|
startRow = 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ public class SearchQuery {
|
|||||||
@Schema(description = "媒体类型:纸质/电子")
|
@Schema(description = "媒体类型:纸质/电子")
|
||||||
private String mediaType;
|
private String mediaType;
|
||||||
|
|
||||||
|
@Schema(description = "媒体类型(多选,in):纸质/电子")
|
||||||
|
private List<String> mediaTypes;
|
||||||
|
|
||||||
@Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)")
|
@Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)")
|
||||||
private String languageGroup;
|
private String languageGroup;
|
||||||
|
|
||||||
@@ -61,6 +64,9 @@ public class SearchQuery {
|
|||||||
@Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)")
|
@Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)")
|
||||||
private String sourceLibrary;
|
private String sourceLibrary;
|
||||||
|
|
||||||
|
@Schema(description = "来源资源库名(多选,in)")
|
||||||
|
private List<String> sourceRepos;
|
||||||
|
|
||||||
/** ---------------- 限定出版时段 ---------------- */
|
/** ---------------- 限定出版时段 ---------------- */
|
||||||
@Schema(description = "出版年份起(含)", example = "2000")
|
@Schema(description = "出版年份起(含)", example = "2000")
|
||||||
private String publishYearStart;
|
private String publishYearStart;
|
||||||
@@ -72,6 +78,9 @@ public class SearchQuery {
|
|||||||
@Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)")
|
@Schema(description = "匹配精度:EQ 精确 / LEFT 前方一致 / RIGHT 后方一致 / LIKE 模糊(默认)")
|
||||||
private String matchType = "LIKE";
|
private String matchType = "LIKE";
|
||||||
|
|
||||||
|
@Schema(description = "在结果中搜索:新增关键词必须同时命中(AND 收窄当前结果集)")
|
||||||
|
private String withinKeyword;
|
||||||
|
|
||||||
@Schema(description = "多字段逻辑:AND(默认) / OR")
|
@Schema(description = "多字段逻辑:AND(默认) / OR")
|
||||||
private String logic = "AND";
|
private String logic = "AND";
|
||||||
|
|
||||||
|
|||||||
+89
-10
@@ -7,7 +7,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|||||||
import com.banben.common.PageResult;
|
import com.banben.common.PageResult;
|
||||||
import com.banben.modules.admin.entity.SensitiveWord;
|
import com.banben.modules.admin.entity.SensitiveWord;
|
||||||
import com.banben.modules.admin.mapper.SensitiveWordMapper;
|
import com.banben.modules.admin.mapper.SensitiveWordMapper;
|
||||||
|
import com.banben.modules.resource.entity.ResourceSource;
|
||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
|
import com.banben.modules.resource.mapper.ResourceSourceMapper;
|
||||||
import com.banben.modules.resource.mapper.VersionResourceMapper;
|
import com.banben.modules.resource.mapper.VersionResourceMapper;
|
||||||
import com.banben.modules.search.dto.SearchQuery;
|
import com.banben.modules.search.dto.SearchQuery;
|
||||||
import com.banben.modules.search.entity.ClcCategory;
|
import com.banben.modules.search.entity.ClcCategory;
|
||||||
@@ -26,8 +28,11 @@ import org.springframework.stereotype.Service;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检索发现服务实现。
|
* 检索发现服务实现。
|
||||||
@@ -45,6 +50,7 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
private static final int FACET_TOP = 20;
|
private static final int FACET_TOP = 20;
|
||||||
|
|
||||||
private final VersionResourceMapper resourceMapper;
|
private final VersionResourceMapper resourceMapper;
|
||||||
|
private final ResourceSourceMapper sourceMapper;
|
||||||
private final SearchLogMapper searchLogMapper;
|
private final SearchLogMapper searchLogMapper;
|
||||||
private final ClcCategoryMapper clcCategoryMapper;
|
private final ClcCategoryMapper clcCategoryMapper;
|
||||||
private final SensitiveWordMapper sensitiveWordMapper;
|
private final SensitiveWordMapper sensitiveWordMapper;
|
||||||
@@ -74,6 +80,7 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
Page.of(query.getCurrent(), query.getSize()), wrapper);
|
Page.of(query.getCurrent(), query.getSize()), wrapper);
|
||||||
|
|
||||||
SearchResultVO vo = new SearchResultVO();
|
SearchResultVO vo = new SearchResultVO();
|
||||||
|
attachSources(page.getRecords());
|
||||||
vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize()));
|
vo.setPage(PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize()));
|
||||||
|
|
||||||
// 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。
|
// 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。
|
||||||
@@ -92,6 +99,7 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
|
|
||||||
vo.setMediaTypeFacets(facet(query, "media_type"));
|
vo.setMediaTypeFacets(facet(query, "media_type"));
|
||||||
vo.setSourceLibraryFacets(facet(query, "source_library"));
|
vo.setSourceLibraryFacets(facet(query, "source_library"));
|
||||||
|
vo.setSourceRepoFacets(facet(query, "source_repo"));
|
||||||
vo.setClcFacets(clcFacet(query));
|
vo.setClcFacets(clcFacet(query));
|
||||||
vo.setYearStats(yearStats(query));
|
vo.setYearStats(yearStats(query));
|
||||||
|
|
||||||
@@ -110,7 +118,11 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public VersionResource detail(Long id) {
|
public VersionResource detail(Long id) {
|
||||||
return resourceMapper.selectById(id);
|
VersionResource r = resourceMapper.selectById(id);
|
||||||
|
if (r != null) {
|
||||||
|
attachSources(List.of(r));
|
||||||
|
}
|
||||||
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -141,7 +153,9 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit));
|
wrapper.orderByDesc("publish_year").last("limit " + Math.max(1, limit));
|
||||||
return resourceMapper.selectList(wrapper);
|
List<VersionResource> list = resourceMapper.selectList(wrapper);
|
||||||
|
attachSources(list);
|
||||||
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -149,7 +163,51 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
|
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
|
||||||
applyOrder(wrapper, query);
|
applyOrder(wrapper, query);
|
||||||
wrapper.last("limit " + Math.max(1, limit));
|
wrapper.last("limit " + Math.max(1, limit));
|
||||||
return resourceMapper.selectList(wrapper);
|
List<VersionResource> list = resourceMapper.selectList(wrapper);
|
||||||
|
attachSources(list);
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量挂载多来源:按主记录 ID 一次查出全部来源,挂到各 {@link VersionResource#sources} 上。
|
||||||
|
*
|
||||||
|
* <p>来源为空(旧数据未维护多来源)时,{@code sources} 保持为空列表,
|
||||||
|
* 前端会回退到主表单来源字段展示与下载。</p>
|
||||||
|
*/
|
||||||
|
private void attachSources(List<VersionResource> records) {
|
||||||
|
if (records == null || records.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<Long> ids = records.stream()
|
||||||
|
.map(VersionResource::getId)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.distinct()
|
||||||
|
.toList();
|
||||||
|
if (ids.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
List<ResourceSource> all = sourceMapper.selectList(
|
||||||
|
new QueryWrapper<ResourceSource>()
|
||||||
|
.in("resource_id", ids)
|
||||||
|
.eq("deleted", 0)
|
||||||
|
.orderByAsc("sort_no"));
|
||||||
|
Map<Long, List<ResourceSource>> byRes = all.stream()
|
||||||
|
.collect(Collectors.groupingBy(
|
||||||
|
ResourceSource::getResourceId,
|
||||||
|
LinkedHashMap::new,
|
||||||
|
Collectors.toList()));
|
||||||
|
for (VersionResource r : records) {
|
||||||
|
r.setSources(byRes.getOrDefault(r.getId(), List.of()));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("批量挂载多来源失败(不影响主结果返回):{}", e.getMessage());
|
||||||
|
for (VersionResource r : records) {
|
||||||
|
if (r.getSources() == null) {
|
||||||
|
r.setSources(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== 内部方法 ====================
|
// ==================== 内部方法 ====================
|
||||||
@@ -190,8 +248,11 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
|| StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher())
|
|| StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher())
|
||||||
|| StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi())
|
|| StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi())
|
||||||
|| StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes())
|
|| StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes())
|
||||||
|| StrUtil.isNotBlank(q.getMediaType()) || StrUtil.isNotBlank(q.getLanguageGroup())
|
|| StrUtil.isNotBlank(q.getMediaType()) || CollectionUtil.isNotEmpty(q.getMediaTypes())
|
||||||
|
|| StrUtil.isNotBlank(q.getLanguageGroup())
|
||||||
|| StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries())
|
|| StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries())
|
||||||
|
|| CollectionUtil.isNotEmpty(q.getSourceRepos())
|
||||||
|
|| StrUtil.isNotBlank(q.getWithinKeyword())
|
||||||
|| StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd());
|
|| StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,6 +309,14 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 在结果中搜索:每个新增关键词都必须命中(AND 收窄当前结果集)
|
||||||
|
if (StrUtil.isNotBlank(q.getWithinKeyword())) {
|
||||||
|
for (String kw : splitTerms(q.getWithinKeyword())) {
|
||||||
|
w.and(x -> x.nested(y -> y.like("title", kw).or().like("author", kw).or()
|
||||||
|
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
applyMatch(w, "title", q.getTitle(), q.getMatchType());
|
applyMatch(w, "title", q.getTitle(), q.getMatchType());
|
||||||
applyMatch(w, "author", q.getAuthor(), q.getMatchType());
|
applyMatch(w, "author", q.getAuthor(), q.getMatchType());
|
||||||
applyMatch(w, "publisher", q.getPublisher(), q.getMatchType());
|
applyMatch(w, "publisher", q.getPublisher(), q.getMatchType());
|
||||||
@@ -255,7 +324,7 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
|
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
|
||||||
|
|
||||||
if (!excludeClc && StrUtil.isNotBlank(q.getClcCode())) {
|
if (!excludeClc && StrUtil.isNotBlank(q.getClcCode())) {
|
||||||
w.likeRight("clc_code", q.getClcCode().trim());
|
w.likeRight("clc_code", q.getClcCode().trim().toUpperCase());
|
||||||
}
|
}
|
||||||
// 中图法树导航:点部类时传入其下所有大类号,任一命中即可
|
// 中图法树导航:点部类时传入其下所有大类号,任一命中即可
|
||||||
if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) {
|
if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) {
|
||||||
@@ -269,13 +338,18 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
x.or();
|
x.or();
|
||||||
}
|
}
|
||||||
first = false;
|
first = false;
|
||||||
x.likeRight("clc_code", c.trim());
|
x.likeRight("clc_code", c.trim().toUpperCase());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (StrUtil.isNotBlank(q.getMediaType()) && !"media_type".equals(excludeColumn)) {
|
// 资源类型:单选或罗列多选(分面排除时跳过本列过滤,便于切换)
|
||||||
|
if (!"media_type".equals(excludeColumn)) {
|
||||||
|
if (CollectionUtil.isNotEmpty(q.getMediaTypes())) {
|
||||||
|
w.in("media_type", q.getMediaTypes());
|
||||||
|
} else if (StrUtil.isNotBlank(q.getMediaType())) {
|
||||||
w.eq("media_type", q.getMediaType());
|
w.eq("media_type", q.getMediaType());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据);
|
// 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据);
|
||||||
// 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组)
|
// 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组)
|
||||||
if ("chi".equalsIgnoreCase(q.getLanguageGroup())) {
|
if ("chi".equalsIgnoreCase(q.getLanguageGroup())) {
|
||||||
@@ -283,13 +357,18 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
} else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) {
|
} else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) {
|
||||||
w.notIn("language", List.of("chi", "zh", "中文"));
|
w.notIn("language", List.of("chi", "zh", "中文"));
|
||||||
}
|
}
|
||||||
|
// 来源院校:多选(IN)或单选(分面排除时跳过本列过滤)
|
||||||
|
if (!"source_library".equals(excludeColumn)) {
|
||||||
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
|
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
|
||||||
w.in("source_library", q.getSourceLibraries());
|
w.in("source_library", q.getSourceLibraries());
|
||||||
}
|
} else if (StrUtil.isNotBlank(q.getSourceLibrary())) {
|
||||||
// 来源院校分面单选(前端点选传单数字段)
|
|
||||||
if (StrUtil.isNotBlank(q.getSourceLibrary()) && !"source_library".equals(excludeColumn)) {
|
|
||||||
w.eq("source_library", q.getSourceLibrary().trim());
|
w.eq("source_library", q.getSourceLibrary().trim());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
// 资源库名:多选(IN)
|
||||||
|
if (CollectionUtil.isNotEmpty(q.getSourceRepos()) && !"source_repo".equals(excludeColumn)) {
|
||||||
|
w.in("source_repo", q.getSourceRepos());
|
||||||
|
}
|
||||||
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
|
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
|
||||||
w.ge("publish_year", q.getPublishYearStart().trim());
|
w.ge("publish_year", q.getPublishYearStart().trim());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ public class SearchResultVO {
|
|||||||
@Schema(description = "来源院校分面")
|
@Schema(description = "来源院校分面")
|
||||||
private List<FacetItem> sourceLibraryFacets;
|
private List<FacetItem> sourceLibraryFacets;
|
||||||
|
|
||||||
|
@Schema(description = "资源库名分面")
|
||||||
|
private List<FacetItem> sourceRepoFacets;
|
||||||
|
|
||||||
@Schema(description = "中图分类分面")
|
@Schema(description = "中图分类分面")
|
||||||
private List<FacetItem> clcFacets;
|
private List<FacetItem> clcFacets;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.sync;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开 Spring 定时调度,供同步任务按配置里的 cron 执行。
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@EnableScheduling
|
||||||
|
public class SyncScheduleConfig {
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.banben.modules.sync;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||||
|
import com.banben.modules.sync.service.SyncService;
|
||||||
|
import com.banben.modules.sync.support.SyncRunner;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.scheduling.support.CronExpression;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每 30 秒看一次已启用定时的任务。cron 存在任务配置里,改完不用重启。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncScheduler {
|
||||||
|
|
||||||
|
private final SyncTaskMapper taskMapper;
|
||||||
|
private final SyncService syncService;
|
||||||
|
private final SyncRunner syncRunner;
|
||||||
|
|
||||||
|
@Scheduled(initialDelay = 20000, fixedDelay = 30000)
|
||||||
|
public void tick() {
|
||||||
|
List<SyncTask> tasks = taskMapper.selectList(new LambdaQueryWrapper<SyncTask>()
|
||||||
|
.eq(SyncTask::getEnabled, 1)
|
||||||
|
.eq(SyncTask::getScheduleEnabled, 1));
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
for (SyncTask task : tasks) {
|
||||||
|
if (task.getCronExpr() == null || task.getCronExpr().isBlank() || syncRunner.isRunning(task.getId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
CronExpression cron = CronExpression.parse(task.getCronExpr().trim());
|
||||||
|
LocalDateTime base = task.getLastScheduleTime() != null
|
||||||
|
? task.getLastScheduleTime()
|
||||||
|
: (task.getCreateTime() == null ? now.minusMinutes(1) : task.getCreateTime());
|
||||||
|
LocalDateTime next = cron.next(base);
|
||||||
|
if (next != null && !next.isAfter(now)) {
|
||||||
|
task.setLastScheduleTime(now);
|
||||||
|
taskMapper.updateById(task);
|
||||||
|
syncService.runTask(task.getId(), "SCHEDULE");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("定时同步任务 {} 未触发:{}", task.getId(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package com.banben.modules.sync;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步相关表自举。开发库和现场库都可能没有这些表,启动时缺了就建,已有数据不动。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class SyncTableInitializer {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public SyncTableInitializer(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_datasource ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "name VARCHAR(128) NOT NULL, "
|
||||||
|
+ "db_type VARCHAR(32) NOT NULL, "
|
||||||
|
+ "host VARCHAR(256) NOT NULL, "
|
||||||
|
+ "port INTEGER NOT NULL, "
|
||||||
|
+ "db_name VARCHAR(128) NOT NULL, "
|
||||||
|
+ "username VARCHAR(128) NOT NULL, "
|
||||||
|
+ "password VARCHAR(256), "
|
||||||
|
+ "jdbc_params VARCHAR(1000), "
|
||||||
|
+ "enabled SMALLINT DEFAULT 1, "
|
||||||
|
+ "remark VARCHAR(500), "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "deleted SMALLINT DEFAULT 0)");
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_task ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "name VARCHAR(128) NOT NULL, "
|
||||||
|
+ "datasource_id BIGINT NOT NULL, "
|
||||||
|
+ "query_sql TEXT NOT NULL, "
|
||||||
|
+ "target_table VARCHAR(64) NOT NULL DEFAULT 'version_resource', "
|
||||||
|
+ "batch_size INTEGER DEFAULT 200, "
|
||||||
|
+ "retry_times INTEGER DEFAULT 1, "
|
||||||
|
+ "cron_expr VARCHAR(64), "
|
||||||
|
+ "schedule_enabled SMALLINT DEFAULT 0, "
|
||||||
|
+ "sync_mode VARCHAR(16) DEFAULT 'FULL', "
|
||||||
|
+ "increment_column VARCHAR(64), "
|
||||||
|
+ "increment_value VARCHAR(128), "
|
||||||
|
+ "unique_fields VARCHAR(256), "
|
||||||
|
+ "enabled SMALLINT DEFAULT 1, "
|
||||||
|
+ "last_schedule_time TIMESTAMP, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "deleted SMALLINT DEFAULT 0)");
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_field_map ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "task_id BIGINT NOT NULL, "
|
||||||
|
+ "source_field VARCHAR(128) NOT NULL, "
|
||||||
|
+ "target_field VARCHAR(64) NOT NULL, "
|
||||||
|
+ "data_type VARCHAR(16) DEFAULT 'STRING', "
|
||||||
|
+ "clean_rule VARCHAR(32) DEFAULT 'TRIM', "
|
||||||
|
+ "required_flag SMALLINT DEFAULT 0, "
|
||||||
|
+ "default_value VARCHAR(256), "
|
||||||
|
+ "sort_no INTEGER DEFAULT 0)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_field_task ON sync_field_map (task_id)");
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_log ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "task_id BIGINT, "
|
||||||
|
+ "datasource_id BIGINT, "
|
||||||
|
+ "task_name VARCHAR(128), "
|
||||||
|
+ "datasource_name VARCHAR(128), "
|
||||||
|
+ "trigger_type VARCHAR(16), "
|
||||||
|
+ "status VARCHAR(16), "
|
||||||
|
+ "start_time TIMESTAMP, "
|
||||||
|
+ "end_time TIMESTAMP, "
|
||||||
|
+ "success_count INTEGER DEFAULT 0, "
|
||||||
|
+ "fail_count INTEGER DEFAULT 0, "
|
||||||
|
+ "skip_count INTEGER DEFAULT 0, "
|
||||||
|
+ "error_message TEXT, "
|
||||||
|
+ "detail TEXT, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_log_task ON sync_log (task_id)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_log_start ON sync_log (start_time)");
|
||||||
|
log.info("数据同步表已就绪");
|
||||||
|
grantMenu();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("自动创建数据同步表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 已有「数据采集」权限的角色补上「数据同步」,管理员本身不受角色栏目限制。 */
|
||||||
|
private void grantMenu() {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"INSERT INTO sys_role_menu (role_id, menu_code) "
|
||||||
|
+ "SELECT DISTINCT role_id, 'sync' FROM sys_role_menu existing "
|
||||||
|
+ "WHERE existing.menu_code = 'collect' "
|
||||||
|
+ "AND NOT EXISTS (SELECT 1 FROM sys_role_menu s "
|
||||||
|
+ "WHERE s.role_id = existing.role_id AND s.menu_code = 'sync')");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("补充数据同步栏目权限失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.banben.modules.sync.controller;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
import com.banben.modules.sync.entity.SyncLog;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
import com.banben.modules.sync.service.SyncService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.Data;
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异构数据同步接口。连接、SQL 和字段映射都由调用方传入,服务端只负责保存和按配置执行。
|
||||||
|
*/
|
||||||
|
@Tag(name = "数据同步", description = "外部数据源配置、同步任务、手动同步与日志")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/sync")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncController {
|
||||||
|
|
||||||
|
private final SyncService syncService;
|
||||||
|
|
||||||
|
@Operation(summary = "数据源列表")
|
||||||
|
@GetMapping("/datasource")
|
||||||
|
public Result<List<SyncDatasource>> listDatasources() {
|
||||||
|
return Result.success(syncService.listDatasources());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增数据源")
|
||||||
|
@PostMapping("/datasource")
|
||||||
|
public Result<Long> createDatasource(@RequestBody SyncDatasource source) {
|
||||||
|
source.setId(null);
|
||||||
|
return Result.success(syncService.saveDatasource(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改数据源")
|
||||||
|
@PutMapping("/datasource/{id}")
|
||||||
|
public Result<Void> updateDatasource(@PathVariable Long id, @RequestBody SyncDatasource source) {
|
||||||
|
source.setId(id);
|
||||||
|
syncService.saveDatasource(source);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除数据源")
|
||||||
|
@DeleteMapping("/datasource/{id}")
|
||||||
|
public Result<Void> removeDatasource(@PathVariable Long id) {
|
||||||
|
syncService.removeDatasource(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "测试数据源连通性")
|
||||||
|
@PostMapping("/datasource/test")
|
||||||
|
public Result<String> testDatasource(@RequestBody SyncDatasource source) {
|
||||||
|
syncService.testDatasource(source);
|
||||||
|
return Result.success("连接成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "按查询 SQL 读取外部列名,供配置映射")
|
||||||
|
@PostMapping("/preview")
|
||||||
|
public Result<List<String>> preview(@RequestBody PreviewRequest request) {
|
||||||
|
return Result.success(syncService.previewColumns(request.getDatasource(), request.getQuerySql()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "可写入的业务表")
|
||||||
|
@GetMapping("/target/tables")
|
||||||
|
public Result<List<String>> targetTables() {
|
||||||
|
return Result.success(syncService.listTargetTables());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "目标表字段")
|
||||||
|
@GetMapping("/target/columns")
|
||||||
|
public Result<List<TargetColumnVO>> targetColumns(@RequestParam(defaultValue = "version_resource") String table) {
|
||||||
|
return Result.success(syncService.listTargetColumns(table));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "同步任务列表")
|
||||||
|
@GetMapping("/task")
|
||||||
|
public Result<List<SyncTask>> listTasks() {
|
||||||
|
return Result.success(syncService.listTasks());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增同步任务")
|
||||||
|
@PostMapping("/task")
|
||||||
|
public Result<Long> createTask(@RequestBody SyncTask task) {
|
||||||
|
task.setId(null);
|
||||||
|
return Result.success(syncService.saveTask(task));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改同步任务")
|
||||||
|
@PutMapping("/task/{id}")
|
||||||
|
public Result<Void> updateTask(@PathVariable Long id, @RequestBody SyncTask task) {
|
||||||
|
task.setId(id);
|
||||||
|
syncService.saveTask(task);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除同步任务")
|
||||||
|
@DeleteMapping("/task/{id}")
|
||||||
|
public Result<Void> removeTask(@PathVariable Long id) {
|
||||||
|
syncService.removeTask(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "手动触发同步")
|
||||||
|
@PostMapping("/task/{id}/run")
|
||||||
|
public Result<Long> run(@PathVariable Long id) {
|
||||||
|
return Result.success(syncService.runTask(id, "MANUAL"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "同步日志")
|
||||||
|
@GetMapping("/log")
|
||||||
|
public Result<PageResult<SyncLog>> logs(@RequestParam(required = false) Long taskId,
|
||||||
|
@RequestParam(defaultValue = "1") long current,
|
||||||
|
@RequestParam(defaultValue = "10") long size) {
|
||||||
|
return Result.success(syncService.pageLogs(taskId, current, size));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "同步日志详情")
|
||||||
|
@GetMapping("/log/{id}")
|
||||||
|
public Result<SyncLog> log(@PathVariable Long id) {
|
||||||
|
return Result.success(syncService.getLog(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class PreviewRequest {
|
||||||
|
private SyncDatasource datasource;
|
||||||
|
private String querySql;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.banben.modules.sync.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 业务库目标表的一列,供页面做字段映射下拉。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class TargetColumnVO {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private String comment;
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.banben.modules.sync.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 com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部数据源连接。地址、账号、库类型都从本表读取,代码里不写死任何外部库。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sync_datasource")
|
||||||
|
@Schema(description = "同步数据源")
|
||||||
|
public class SyncDatasource implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "数据源名称")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "数据库类型:MYSQL / ORACLE / SQLSERVER / POSTGRESQL / HIGHGO")
|
||||||
|
private String dbType;
|
||||||
|
|
||||||
|
@Schema(description = "主机地址")
|
||||||
|
private String host;
|
||||||
|
|
||||||
|
@Schema(description = "端口")
|
||||||
|
private Integer port;
|
||||||
|
|
||||||
|
@Schema(description = "库名。Oracle 填服务名")
|
||||||
|
private String dbName;
|
||||||
|
|
||||||
|
@Schema(description = "用户名")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||||
|
@Schema(description = "密码,只用于连接,接口不回传")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@Schema(description = "附加 JDBC 参数,空则用该类型的默认参数")
|
||||||
|
private String jdbcParams;
|
||||||
|
|
||||||
|
@Schema(description = "1 启用 0 停用")
|
||||||
|
private Integer enabled;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.banben.modules.sync.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 一条字段映射:外部结果列 → 我方目标列,以及清洗、类型和是否必填。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sync_field_map")
|
||||||
|
@Schema(description = "同步字段映射")
|
||||||
|
public class SyncFieldMap implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private Long taskId;
|
||||||
|
|
||||||
|
@Schema(description = "查询结果中的列名")
|
||||||
|
private String sourceField;
|
||||||
|
|
||||||
|
@Schema(description = "目标表列名")
|
||||||
|
private String targetField;
|
||||||
|
|
||||||
|
@Schema(description = "STRING / INTEGER / LONG / DECIMAL / DATE / DATETIME")
|
||||||
|
private String dataType;
|
||||||
|
|
||||||
|
@Schema(description = "NONE / TRIM / UPPER / LOWER / DIGITS / COMPACT_DATE")
|
||||||
|
private String cleanRule;
|
||||||
|
|
||||||
|
@Schema(description = "1 必填,空值记失败并不写入该行")
|
||||||
|
private Integer requiredFlag;
|
||||||
|
|
||||||
|
@Schema(description = "源值为空时的默认值,支持 ${uuid} ${today} ${year} ${seq} ${task}")
|
||||||
|
private String defaultValue;
|
||||||
|
|
||||||
|
private Integer sortNo;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.banben.modules.sync.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 一次同步的执行结果。失败原因写在 errorMessage,单行错误样例写在 detail。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sync_log")
|
||||||
|
@Schema(description = "同步日志")
|
||||||
|
public class SyncLog implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private Long taskId;
|
||||||
|
|
||||||
|
private Long datasourceId;
|
||||||
|
|
||||||
|
private String taskName;
|
||||||
|
|
||||||
|
private String datasourceName;
|
||||||
|
|
||||||
|
@Schema(description = "MANUAL / SCHEDULE")
|
||||||
|
private String triggerType;
|
||||||
|
|
||||||
|
@Schema(description = "RUNNING / SUCCESS / PARTIAL / FAILED")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
private Integer successCount;
|
||||||
|
|
||||||
|
private Integer failCount;
|
||||||
|
|
||||||
|
private Integer skipCount;
|
||||||
|
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
private String detail;
|
||||||
|
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.banben.modules.sync.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步任务配置。查询语句和目标表都由现场填写。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sync_task")
|
||||||
|
@Schema(description = "同步任务")
|
||||||
|
public class SyncTask implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "任务名称")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "数据源 ID")
|
||||||
|
private Long datasourceId;
|
||||||
|
|
||||||
|
@Schema(description = "外部库查询 SQL,只允许单条 SELECT")
|
||||||
|
private String querySql;
|
||||||
|
|
||||||
|
@Schema(description = "写入的业务表,默认 version_resource")
|
||||||
|
private String targetTable;
|
||||||
|
|
||||||
|
@Schema(description = "每批写入条数")
|
||||||
|
private Integer batchSize;
|
||||||
|
|
||||||
|
@Schema(description = "连接或查询失败时的重试次数")
|
||||||
|
private Integer retryTimes;
|
||||||
|
|
||||||
|
@Schema(description = "定时表达式,6 位:秒 分 时 日 月 周")
|
||||||
|
private String cronExpr;
|
||||||
|
|
||||||
|
@Schema(description = "1 启用定时 0 仅手动")
|
||||||
|
private Integer scheduleEnabled;
|
||||||
|
|
||||||
|
@Schema(description = "FULL 全量 / INCREMENT 增量")
|
||||||
|
private String syncMode;
|
||||||
|
|
||||||
|
@Schema(description = "增量水位列,预留")
|
||||||
|
private String incrementColumn;
|
||||||
|
|
||||||
|
@Schema(description = "上次水位")
|
||||||
|
private String incrementValue;
|
||||||
|
|
||||||
|
@Schema(description = "去重用的目标字段,逗号分隔")
|
||||||
|
private String uniqueFields;
|
||||||
|
|
||||||
|
@Schema(description = "1 启用 0 停用")
|
||||||
|
private Integer enabled;
|
||||||
|
|
||||||
|
@Schema(description = "上次定时触发时间")
|
||||||
|
private LocalDateTime lastScheduleTime;
|
||||||
|
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "数据源名称,仅展示")
|
||||||
|
private String datasourceName;
|
||||||
|
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "字段映射,保存任务时一并提交")
|
||||||
|
private List<SyncFieldMap> mappings;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.banben.modules.sync.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
|
||||||
|
public interface SyncDatasourceMapper extends BaseMapper<SyncDatasource> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.banben.modules.sync.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||||
|
|
||||||
|
public interface SyncFieldMapMapper extends BaseMapper<SyncFieldMap> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.banben.modules.sync.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.sync.entity.SyncLog;
|
||||||
|
|
||||||
|
public interface SyncLogMapper extends BaseMapper<SyncLog> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.banben.modules.sync.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
|
||||||
|
public interface SyncTaskMapper extends BaseMapper<SyncTask> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.banben.modules.sync.service;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
import com.banben.modules.sync.entity.SyncLog;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异构数据同步:数据源、任务、手动执行和日志都从这里进出。
|
||||||
|
*/
|
||||||
|
public interface SyncService {
|
||||||
|
|
||||||
|
List<SyncDatasource> listDatasources();
|
||||||
|
|
||||||
|
Long saveDatasource(SyncDatasource source);
|
||||||
|
|
||||||
|
void removeDatasource(Long id);
|
||||||
|
|
||||||
|
void testDatasource(SyncDatasource source);
|
||||||
|
|
||||||
|
List<String> previewColumns(SyncDatasource source, String querySql);
|
||||||
|
|
||||||
|
List<String> listTargetTables();
|
||||||
|
|
||||||
|
List<TargetColumnVO> listTargetColumns(String table);
|
||||||
|
|
||||||
|
List<SyncTask> listTasks();
|
||||||
|
|
||||||
|
Long saveTask(SyncTask task);
|
||||||
|
|
||||||
|
void removeTask(Long id);
|
||||||
|
|
||||||
|
Long runTask(Long id, String triggerType);
|
||||||
|
|
||||||
|
PageResult<SyncLog> pageLogs(Long taskId, long current, long size);
|
||||||
|
|
||||||
|
SyncLog getLog(Long id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,385 @@
|
|||||||
|
package com.banben.modules.sync.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.sync.dto.TargetColumnVO;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||||
|
import com.banben.modules.sync.entity.SyncLog;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
import com.banben.modules.sync.mapper.SyncDatasourceMapper;
|
||||||
|
import com.banben.modules.sync.mapper.SyncFieldMapMapper;
|
||||||
|
import com.banben.modules.sync.mapper.SyncLogMapper;
|
||||||
|
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||||
|
import com.banben.modules.sync.service.SyncService;
|
||||||
|
import com.banben.modules.sync.support.JdbcSources;
|
||||||
|
import com.banben.modules.sync.support.SqlGuard;
|
||||||
|
import com.banben.modules.sync.support.SyncRunner;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.scheduling.support.CronExpression;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置的增删改查。真正抽取数据由 {@link SyncRunner} 按库里的 SQL 和映射执行。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncServiceImpl implements SyncService {
|
||||||
|
|
||||||
|
private static final Set<String> BLOCKED_TABLES = Set.of(
|
||||||
|
"sync_datasource", "sync_task", "sync_field_map", "sync_log",
|
||||||
|
"sys_user", "sys_role", "sys_role_menu"
|
||||||
|
);
|
||||||
|
|
||||||
|
private final SyncDatasourceMapper datasourceMapper;
|
||||||
|
private final SyncTaskMapper taskMapper;
|
||||||
|
private final SyncFieldMapMapper fieldMapMapper;
|
||||||
|
private final SyncLogMapper logMapper;
|
||||||
|
private final SyncRunner syncRunner;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SyncDatasource> listDatasources() {
|
||||||
|
return datasourceMapper.selectList(new LambdaQueryWrapper<SyncDatasource>()
|
||||||
|
.orderByDesc(SyncDatasource::getCreateTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long saveDatasource(SyncDatasource source) {
|
||||||
|
source.setDbType(JdbcSources.normalize(source.getDbType()));
|
||||||
|
if (source.getName() == null || source.getName().isBlank()) {
|
||||||
|
throw new BusinessException("请填写数据源名称");
|
||||||
|
}
|
||||||
|
if (source.getHost() == null || source.getHost().isBlank()) {
|
||||||
|
throw new BusinessException("请填写数据库地址");
|
||||||
|
}
|
||||||
|
if (source.getPort() == null || source.getPort() < 1) {
|
||||||
|
throw new BusinessException("请填写端口");
|
||||||
|
}
|
||||||
|
if (source.getDbName() == null || source.getDbName().isBlank()) {
|
||||||
|
throw new BusinessException("请填写数据库名");
|
||||||
|
}
|
||||||
|
if (source.getUsername() == null || source.getUsername().isBlank()) {
|
||||||
|
throw new BusinessException("请填写用户名");
|
||||||
|
}
|
||||||
|
if (source.getEnabled() == null) {
|
||||||
|
source.setEnabled(1);
|
||||||
|
}
|
||||||
|
if (source.getId() == null) {
|
||||||
|
if (source.getPassword() == null || source.getPassword().isBlank()) {
|
||||||
|
throw new BusinessException("请填写密码");
|
||||||
|
}
|
||||||
|
datasourceMapper.insert(source);
|
||||||
|
return source.getId();
|
||||||
|
}
|
||||||
|
SyncDatasource stored = requireDatasource(source.getId());
|
||||||
|
if (source.getPassword() == null || source.getPassword().isBlank()) {
|
||||||
|
source.setPassword(stored.getPassword());
|
||||||
|
}
|
||||||
|
datasourceMapper.updateById(source);
|
||||||
|
return source.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void removeDatasource(Long id) {
|
||||||
|
Long used = taskMapper.selectCount(new LambdaQueryWrapper<SyncTask>().eq(SyncTask::getDatasourceId, id));
|
||||||
|
if (used != null && used > 0) {
|
||||||
|
throw new BusinessException("该数据源下还有同步任务,请先删除任务");
|
||||||
|
}
|
||||||
|
datasourceMapper.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void testDatasource(SyncDatasource source) {
|
||||||
|
fillPassword(source);
|
||||||
|
saveDatasourceShape(source);
|
||||||
|
try (Connection connection = JdbcSources.open(source)) {
|
||||||
|
if (!connection.isValid(5)) {
|
||||||
|
throw new BusinessException("连接未通过校验");
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new BusinessException(JdbcSources.safeMessage(e, source.getPassword()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> previewColumns(SyncDatasource source, String querySql) {
|
||||||
|
fillPassword(source);
|
||||||
|
saveDatasourceShape(source);
|
||||||
|
return syncRunner.previewColumns(source, querySql);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> listTargetTables() {
|
||||||
|
return jdbcTemplate.query(
|
||||||
|
"SELECT table_name FROM information_schema.tables "
|
||||||
|
+ "WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name",
|
||||||
|
(rs, rowNum) -> rs.getString(1))
|
||||||
|
.stream()
|
||||||
|
.filter(name -> !BLOCKED_TABLES.contains(name.toLowerCase(Locale.ROOT)))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<TargetColumnVO> listTargetColumns(String table) {
|
||||||
|
String name = SqlGuard.identifier(table, "目标表").toLowerCase(Locale.ROOT);
|
||||||
|
if (BLOCKED_TABLES.contains(name)) {
|
||||||
|
throw new BusinessException("不能选择系统配置表");
|
||||||
|
}
|
||||||
|
return jdbcTemplate.query(
|
||||||
|
"SELECT a.attname AS name, col_description(a.attrelid, a.attnum) AS comment "
|
||||||
|
+ "FROM pg_catalog.pg_attribute a "
|
||||||
|
+ "JOIN pg_catalog.pg_class t ON a.attrelid = t.oid "
|
||||||
|
+ "JOIN pg_catalog.pg_namespace n ON t.relnamespace = n.oid "
|
||||||
|
+ "WHERE n.nspname = 'public' AND t.relname = ? "
|
||||||
|
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attname <> 'id' "
|
||||||
|
+ "ORDER BY a.attnum",
|
||||||
|
(rs, rowNum) -> {
|
||||||
|
TargetColumnVO column = new TargetColumnVO();
|
||||||
|
column.setName(rs.getString("name"));
|
||||||
|
column.setComment(rs.getString("comment"));
|
||||||
|
return column;
|
||||||
|
},
|
||||||
|
name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SyncTask> listTasks() {
|
||||||
|
List<SyncTask> tasks = taskMapper.selectList(new LambdaQueryWrapper<SyncTask>()
|
||||||
|
.orderByDesc(SyncTask::getCreateTime));
|
||||||
|
for (SyncTask task : tasks) {
|
||||||
|
SyncDatasource source = datasourceMapper.selectById(task.getDatasourceId());
|
||||||
|
task.setDatasourceName(source == null ? "" : source.getName());
|
||||||
|
task.setMappings(mappingsOf(task.getId()));
|
||||||
|
}
|
||||||
|
return tasks;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public Long saveTask(SyncTask task) {
|
||||||
|
if (task.getName() == null || task.getName().isBlank()) {
|
||||||
|
throw new BusinessException("请填写任务名称");
|
||||||
|
}
|
||||||
|
if (task.getDatasourceId() == null || datasourceMapper.selectById(task.getDatasourceId()) == null) {
|
||||||
|
throw new BusinessException("请选择数据源");
|
||||||
|
}
|
||||||
|
task.setQuerySql(SqlGuard.selectSql(task.getQuerySql()));
|
||||||
|
String table = SqlGuard.identifier(
|
||||||
|
task.getTargetTable() == null || task.getTargetTable().isBlank() ? "version_resource" : task.getTargetTable(),
|
||||||
|
"目标表").toLowerCase(Locale.ROOT);
|
||||||
|
if (BLOCKED_TABLES.contains(table)) {
|
||||||
|
throw new BusinessException("不能写入系统配置表");
|
||||||
|
}
|
||||||
|
if (listTargetColumns(table).isEmpty()) {
|
||||||
|
throw new BusinessException("业务库中不存在表 " + table);
|
||||||
|
}
|
||||||
|
task.setTargetTable(table);
|
||||||
|
if (task.getMappings() == null || task.getMappings().isEmpty()) {
|
||||||
|
throw new BusinessException("请至少配置一条字段映射");
|
||||||
|
}
|
||||||
|
if (task.getBatchSize() == null || task.getBatchSize() < 1) {
|
||||||
|
task.setBatchSize(200);
|
||||||
|
}
|
||||||
|
task.setBatchSize(Math.min(task.getBatchSize(), 2000));
|
||||||
|
if (task.getRetryTimes() == null || task.getRetryTimes() < 0) {
|
||||||
|
task.setRetryTimes(1);
|
||||||
|
}
|
||||||
|
task.setRetryTimes(Math.min(task.getRetryTimes(), 5));
|
||||||
|
if (task.getScheduleEnabled() != null && task.getScheduleEnabled() == 1) {
|
||||||
|
if (task.getCronExpr() == null || task.getCronExpr().isBlank()) {
|
||||||
|
throw new BusinessException("启用定时时请填写 cron");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
CronExpression.parse(task.getCronExpr().trim());
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new BusinessException("cron 不正确,格式为:秒 分 时 日 月 周");
|
||||||
|
}
|
||||||
|
task.setCronExpr(task.getCronExpr().trim());
|
||||||
|
}
|
||||||
|
if (task.getSyncMode() == null || task.getSyncMode().isBlank()) {
|
||||||
|
task.setSyncMode("FULL");
|
||||||
|
}
|
||||||
|
task.setSyncMode(task.getSyncMode().trim().toUpperCase(Locale.ROOT));
|
||||||
|
if (!"FULL".equals(task.getSyncMode()) && !"INCREMENT".equals(task.getSyncMode())) {
|
||||||
|
throw new BusinessException("同步方式只能是全量或增量");
|
||||||
|
}
|
||||||
|
if ("INCREMENT".equals(task.getSyncMode()) && (task.getQuerySql() == null || !task.getQuerySql().contains("${watermark}"))) {
|
||||||
|
throw new BusinessException("增量同步的 SQL 需要包含 ${watermark} 占位符");
|
||||||
|
}
|
||||||
|
if (task.getEnabled() == null) {
|
||||||
|
task.setEnabled(1);
|
||||||
|
}
|
||||||
|
if (task.getScheduleEnabled() == null) {
|
||||||
|
task.setScheduleEnabled(0);
|
||||||
|
}
|
||||||
|
if (task.getId() == null) {
|
||||||
|
taskMapper.insert(task);
|
||||||
|
} else {
|
||||||
|
SyncTask stored = requireTask(task.getId());
|
||||||
|
if (task.getIncrementValue() == null || task.getIncrementValue().isBlank()) {
|
||||||
|
task.setIncrementValue(stored.getIncrementValue());
|
||||||
|
}
|
||||||
|
task.setLastScheduleTime(stored.getLastScheduleTime());
|
||||||
|
taskMapper.updateById(task);
|
||||||
|
fieldMapMapper.delete(new LambdaQueryWrapper<SyncFieldMap>().eq(SyncFieldMap::getTaskId, task.getId()));
|
||||||
|
}
|
||||||
|
int sort = 0;
|
||||||
|
for (SyncFieldMap map : task.getMappings()) {
|
||||||
|
if (map.getSourceField() == null || map.getSourceField().isBlank()
|
||||||
|
|| map.getTargetField() == null || map.getTargetField().isBlank()) {
|
||||||
|
throw new BusinessException("字段映射的源字段和目标字段都不能为空");
|
||||||
|
}
|
||||||
|
map.setId(null);
|
||||||
|
map.setTaskId(task.getId());
|
||||||
|
map.setSortNo(sort++);
|
||||||
|
if (map.getDataType() == null || map.getDataType().isBlank()) {
|
||||||
|
map.setDataType("STRING");
|
||||||
|
}
|
||||||
|
if (map.getCleanRule() == null || map.getCleanRule().isBlank()) {
|
||||||
|
map.setCleanRule("TRIM");
|
||||||
|
}
|
||||||
|
if (map.getRequiredFlag() == null) {
|
||||||
|
map.setRequiredFlag(0);
|
||||||
|
}
|
||||||
|
fieldMapMapper.insert(map);
|
||||||
|
}
|
||||||
|
return task.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void removeTask(Long id) {
|
||||||
|
if (syncRunner.isRunning(id)) {
|
||||||
|
throw new BusinessException("任务正在同步,不能删除");
|
||||||
|
}
|
||||||
|
requireTask(id);
|
||||||
|
taskMapper.deleteById(id);
|
||||||
|
fieldMapMapper.delete(new LambdaQueryWrapper<SyncFieldMap>().eq(SyncFieldMap::getTaskId, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long runTask(Long id, String triggerType) {
|
||||||
|
SyncTask task = requireTask(id);
|
||||||
|
if (task.getEnabled() != null && task.getEnabled() == 0) {
|
||||||
|
throw new BusinessException("任务已停用");
|
||||||
|
}
|
||||||
|
if (syncRunner.isRunning(id)) {
|
||||||
|
throw new BusinessException("该任务正在同步");
|
||||||
|
}
|
||||||
|
SyncDatasource source = requireDatasource(task.getDatasourceId());
|
||||||
|
if (source.getEnabled() != null && source.getEnabled() == 0) {
|
||||||
|
throw new BusinessException("数据源已停用");
|
||||||
|
}
|
||||||
|
List<SyncFieldMap> mappings = mappingsOf(id);
|
||||||
|
if (mappings.isEmpty()) {
|
||||||
|
throw new BusinessException("请先配置字段映射");
|
||||||
|
}
|
||||||
|
SyncLog syncLog = new SyncLog();
|
||||||
|
syncLog.setTaskId(task.getId());
|
||||||
|
syncLog.setDatasourceId(source.getId());
|
||||||
|
syncLog.setTaskName(task.getName());
|
||||||
|
syncLog.setDatasourceName(source.getName());
|
||||||
|
syncLog.setTriggerType(triggerType);
|
||||||
|
syncLog.setStatus("RUNNING");
|
||||||
|
syncLog.setStartTime(LocalDateTime.now());
|
||||||
|
syncLog.setSuccessCount(0);
|
||||||
|
syncLog.setFailCount(0);
|
||||||
|
syncLog.setSkipCount(0);
|
||||||
|
syncLog.setCreateTime(LocalDateTime.now());
|
||||||
|
logMapper.insert(syncLog);
|
||||||
|
syncRunner.submit(task, source, mappings, syncLog);
|
||||||
|
return syncLog.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<SyncLog> pageLogs(Long taskId, long current, long size) {
|
||||||
|
LambdaQueryWrapper<SyncLog> wrapper = new LambdaQueryWrapper<SyncLog>().orderByDesc(SyncLog::getStartTime);
|
||||||
|
if (taskId != null) {
|
||||||
|
wrapper.eq(SyncLog::getTaskId, taskId);
|
||||||
|
}
|
||||||
|
Page<SyncLog> page = logMapper.selectPage(new Page<>(current, size), wrapper);
|
||||||
|
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SyncLog getLog(Long id) {
|
||||||
|
SyncLog log = logMapper.selectById(id);
|
||||||
|
if (log == null) {
|
||||||
|
throw new BusinessException("同步日志不存在");
|
||||||
|
}
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fillPassword(SyncDatasource source) {
|
||||||
|
if (source.getPassword() != null && !source.getPassword().isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (source.getId() == null) {
|
||||||
|
throw new BusinessException("请填写密码");
|
||||||
|
}
|
||||||
|
SyncDatasource stored = requireDatasource(source.getId());
|
||||||
|
source.setPassword(stored.getPassword());
|
||||||
|
if (source.getHost() == null) {
|
||||||
|
source.setHost(stored.getHost());
|
||||||
|
}
|
||||||
|
if (source.getDbType() == null) {
|
||||||
|
source.setDbType(stored.getDbType());
|
||||||
|
}
|
||||||
|
if (source.getPort() == null) {
|
||||||
|
source.setPort(stored.getPort());
|
||||||
|
}
|
||||||
|
if (source.getDbName() == null) {
|
||||||
|
source.setDbName(stored.getDbName());
|
||||||
|
}
|
||||||
|
if (source.getUsername() == null) {
|
||||||
|
source.setUsername(stored.getUsername());
|
||||||
|
}
|
||||||
|
if (source.getJdbcParams() == null) {
|
||||||
|
source.setJdbcParams(stored.getJdbcParams());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试和预览只校验形态,不把未保存的连接写进库。 */
|
||||||
|
private void saveDatasourceShape(SyncDatasource source) {
|
||||||
|
JdbcSources.normalize(source.getDbType());
|
||||||
|
if (source.getHost() == null || source.getHost().isBlank()
|
||||||
|
|| source.getPort() == null || source.getDbName() == null || source.getDbName().isBlank()
|
||||||
|
|| source.getUsername() == null || source.getUsername().isBlank()) {
|
||||||
|
throw new BusinessException("请把地址、端口、库名和用户名填写完整");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<SyncFieldMap> mappingsOf(Long taskId) {
|
||||||
|
return fieldMapMapper.selectList(new LambdaQueryWrapper<SyncFieldMap>()
|
||||||
|
.eq(SyncFieldMap::getTaskId, taskId)
|
||||||
|
.orderByAsc(SyncFieldMap::getSortNo)
|
||||||
|
.orderByAsc(SyncFieldMap::getId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private SyncDatasource requireDatasource(Long id) {
|
||||||
|
SyncDatasource source = datasourceMapper.selectById(id);
|
||||||
|
if (source == null) {
|
||||||
|
throw new BusinessException("数据源不存在");
|
||||||
|
}
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SyncTask requireTask(Long id) {
|
||||||
|
SyncTask task = taskMapper.selectById(id);
|
||||||
|
if (task == null) {
|
||||||
|
throw new BusinessException("同步任务不存在");
|
||||||
|
}
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package com.banben.modules.sync.support;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按数据源配置拼出 JDBC 连接。类型决定驱动和 URL 形态,地址账号全部来自配置表。
|
||||||
|
*/
|
||||||
|
public final class JdbcSources {
|
||||||
|
|
||||||
|
private JdbcSources() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection open(SyncDatasource source) throws SQLException {
|
||||||
|
String type = normalize(source.getDbType());
|
||||||
|
loadDriver(type);
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.setProperty("user", source.getUsername() == null ? "" : source.getUsername().trim());
|
||||||
|
props.setProperty("password", source.getPassword() == null ? "" : source.getPassword());
|
||||||
|
return DriverManager.getConnection(buildUrl(source, type), props);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalize(String dbType) {
|
||||||
|
if (dbType == null || dbType.isBlank()) {
|
||||||
|
throw new BusinessException("请选择数据库类型");
|
||||||
|
}
|
||||||
|
return dbType.trim().toUpperCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String safeMessage(SQLException exception, String password) {
|
||||||
|
String message = exception.getMessage() == null ? "连接失败" : exception.getMessage();
|
||||||
|
String lower = message.toLowerCase(Locale.ROOT);
|
||||||
|
String text;
|
||||||
|
if (lower.contains("access denied") || lower.contains("password authentication failed")
|
||||||
|
|| lower.contains("login failed") || lower.contains("ora-01017")) {
|
||||||
|
text = "用户名或密码错误";
|
||||||
|
} else if (lower.contains("unknown database") || lower.contains("does not exist")
|
||||||
|
|| lower.contains("ora-12514") || lower.contains("cannot open database")) {
|
||||||
|
text = "数据库不存在或服务名不正确";
|
||||||
|
} else if (lower.contains("connection refused") || lower.contains("communications link failure")
|
||||||
|
|| lower.contains("connect timed out") || lower.contains("the network adapter")
|
||||||
|
|| lower.contains("timeout")) {
|
||||||
|
text = "连接被拒绝或超时,请确认现场网络和地址端口";
|
||||||
|
} else {
|
||||||
|
text = message;
|
||||||
|
}
|
||||||
|
if (password != null && !password.isBlank() && text.contains(password)) {
|
||||||
|
text = text.replace(password, "******");
|
||||||
|
}
|
||||||
|
return clip(text, 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String buildUrl(SyncDatasource source, String type) {
|
||||||
|
String host = required(source.getHost(), "数据库地址");
|
||||||
|
int port = source.getPort() == null ? 0 : source.getPort();
|
||||||
|
if (port <= 0 || port > 65535) {
|
||||||
|
throw new BusinessException("端口不正确");
|
||||||
|
}
|
||||||
|
String db = required(source.getDbName(), "数据库名");
|
||||||
|
String extra = source.getJdbcParams() == null ? "" : source.getJdbcParams().trim();
|
||||||
|
return switch (type) {
|
||||||
|
case "MYSQL" -> "jdbc:mysql://" + host + ":" + port + "/" + db + "?"
|
||||||
|
+ (extra.isEmpty()
|
||||||
|
? "useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&connectTimeout=8000"
|
||||||
|
: extra);
|
||||||
|
case "ORACLE" -> "jdbc:oracle:thin:@//" + host + ":" + port + "/" + db
|
||||||
|
+ (extra.isEmpty() ? "" : "?" + extra);
|
||||||
|
case "SQLSERVER" -> "jdbc:sqlserver://" + host + ":" + port
|
||||||
|
+ ";databaseName=" + db
|
||||||
|
+ ";encrypt=false;trustServerCertificate=true;loginTimeout=8"
|
||||||
|
+ (extra.isEmpty() ? "" : ";" + extra.replace('&', ';'));
|
||||||
|
case "POSTGRESQL", "HIGHGO" -> "jdbc:postgresql://" + host + ":" + port + "/" + db
|
||||||
|
+ "?connectTimeout=8" + (extra.isEmpty() ? "" : "&" + extra);
|
||||||
|
default -> throw new BusinessException("数据库类型只支持 MySQL、Oracle、SQL Server、PostgreSQL、瀚高");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void loadDriver(String type) {
|
||||||
|
String className = switch (type) {
|
||||||
|
case "MYSQL" -> "com.mysql.cj.jdbc.Driver";
|
||||||
|
case "ORACLE" -> "oracle.jdbc.OracleDriver";
|
||||||
|
case "SQLSERVER" -> "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
||||||
|
case "POSTGRESQL", "HIGHGO" -> "org.postgresql.Driver";
|
||||||
|
default -> throw new BusinessException("数据库类型只支持 MySQL、Oracle、SQL Server、PostgreSQL、瀚高");
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
Class.forName(className);
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
throw new BusinessException("未加载 " + type + " 驱动:" + className);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String required(String value, String label) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new BusinessException("请填写" + label);
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String clip(String text, int max) {
|
||||||
|
if (text == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String flat = text.replace('\r', ' ').replace('\n', ' ').trim();
|
||||||
|
return flat.length() <= max ? flat : flat.substring(0, max);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package com.banben.modules.sync.support;
|
||||||
|
|
||||||
|
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Date;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字段清洗、默认值和类型转换。规则来自字段映射配置,不针对某一家外部库写死。
|
||||||
|
*/
|
||||||
|
public final class RowConverter {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||||
|
|
||||||
|
private RowConverter() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return 可直接交给 JDBC 的值;转换失败时抛出 IllegalArgumentException
|
||||||
|
*/
|
||||||
|
public static Object convert(SyncFieldMap map, Object raw, long taskId, int sequence) {
|
||||||
|
String text = raw == null ? "" : String.valueOf(raw).trim();
|
||||||
|
text = clean(text, map.getCleanRule());
|
||||||
|
if (text.isEmpty()) {
|
||||||
|
text = applyDefault(map.getDefaultValue(), taskId, sequence);
|
||||||
|
}
|
||||||
|
if (text.isEmpty()) {
|
||||||
|
if (map.getRequiredFlag() != null && map.getRequiredFlag() == 1) {
|
||||||
|
throw new IllegalArgumentException("必填字段 " + label(map) + " 为空");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String type = map.getDataType() == null ? "STRING" : map.getDataType().trim().toUpperCase(Locale.ROOT);
|
||||||
|
try {
|
||||||
|
return switch (type) {
|
||||||
|
case "INTEGER" -> Integer.valueOf(text);
|
||||||
|
case "LONG" -> Long.valueOf(text);
|
||||||
|
case "DECIMAL" -> new BigDecimal(text);
|
||||||
|
case "DATE" -> Date.valueOf(parseDate(text));
|
||||||
|
case "DATETIME" -> Timestamp.valueOf(parseDateTime(text));
|
||||||
|
default -> text;
|
||||||
|
};
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
throw new IllegalArgumentException("字段 " + label(map) + " 无法转成 " + type + ":" + text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String label(SyncFieldMap map) {
|
||||||
|
return map.getTargetField() + "(" + map.getSourceField() + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String clean(String text, String rule) {
|
||||||
|
if (text == null || text.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String name = rule == null ? "TRIM" : rule.trim().toUpperCase(Locale.ROOT);
|
||||||
|
return switch (name) {
|
||||||
|
case "NONE" -> text;
|
||||||
|
case "UPPER" -> text.toUpperCase(Locale.ROOT);
|
||||||
|
case "LOWER" -> text.toLowerCase(Locale.ROOT);
|
||||||
|
case "DIGITS" -> text.replaceAll("\\D", "");
|
||||||
|
case "COMPACT_DATE" -> compactDate(text);
|
||||||
|
default -> text.trim();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String applyDefault(String template, long taskId, int sequence) {
|
||||||
|
if (template == null || template.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
LocalDate today = LocalDate.now();
|
||||||
|
return template
|
||||||
|
.replace("${uuid}", UUID.randomUUID().toString().replace("-", ""))
|
||||||
|
.replace("${today}", today.format(DAY))
|
||||||
|
.replace("${year}", String.valueOf(today.getYear()))
|
||||||
|
.replace("${seq}", String.valueOf(sequence))
|
||||||
|
.replace("${task}", String.valueOf(taskId))
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String compactDate(String text) {
|
||||||
|
String digits = text.replaceAll("\\D", "");
|
||||||
|
if (digits.length() >= 8) {
|
||||||
|
return digits.substring(0, 8);
|
||||||
|
}
|
||||||
|
if (digits.length() == 6) {
|
||||||
|
return digits + "01";
|
||||||
|
}
|
||||||
|
if (digits.length() == 4) {
|
||||||
|
return digits + "0101";
|
||||||
|
}
|
||||||
|
return digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LocalDate parseDate(String text) {
|
||||||
|
String digits = text.replaceAll("\\D", "");
|
||||||
|
if (digits.length() >= 8) {
|
||||||
|
return LocalDate.parse(digits.substring(0, 8), DAY);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return LocalDate.parse(text);
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
throw new IllegalArgumentException(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LocalDateTime parseDateTime(String text) {
|
||||||
|
String normalized = text.replace('T', ' ').replace('/', '-');
|
||||||
|
try {
|
||||||
|
if (normalized.length() == 10) {
|
||||||
|
return LocalDate.parse(normalized).atStartOfDay();
|
||||||
|
}
|
||||||
|
return LocalDateTime.parse(normalized, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
return parseDate(text).atStartOfDay();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.banben.modules.sync.support;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询语句和目标表名的约束。SQL 由配置提供,这里只挡住多语句和明显的写操作。
|
||||||
|
*/
|
||||||
|
public final class SqlGuard {
|
||||||
|
|
||||||
|
private static final Pattern IDENT = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
|
||||||
|
|
||||||
|
private SqlGuard() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String selectSql(String sql) {
|
||||||
|
if (sql == null || sql.isBlank()) {
|
||||||
|
throw new BusinessException("请填写查询 SQL");
|
||||||
|
}
|
||||||
|
String text = sql.trim();
|
||||||
|
if (text.endsWith(";")) {
|
||||||
|
text = text.substring(0, text.length() - 1).trim();
|
||||||
|
}
|
||||||
|
if (text.indexOf(';') >= 0) {
|
||||||
|
throw new BusinessException("查询 SQL 只能有一条语句");
|
||||||
|
}
|
||||||
|
String head = text.toLowerCase(Locale.ROOT);
|
||||||
|
if (!head.startsWith("select") && !head.startsWith("with")) {
|
||||||
|
throw new BusinessException("查询 SQL 只能是 SELECT");
|
||||||
|
}
|
||||||
|
if (text.length() > 20000) {
|
||||||
|
throw new BusinessException("查询 SQL 过长");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String identifier(String name, String label) {
|
||||||
|
if (name == null || !IDENT.matcher(name.trim()).matches()) {
|
||||||
|
throw new BusinessException(label + "只能使用字母、数字和下划线");
|
||||||
|
}
|
||||||
|
return name.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String quote(String identifier) {
|
||||||
|
return "\"" + identifier(identifier, "字段名") + "\"";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,495 @@
|
|||||||
|
package com.banben.modules.sync.support;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.sync.entity.SyncDatasource;
|
||||||
|
import com.banben.modules.sync.entity.SyncFieldMap;
|
||||||
|
import com.banben.modules.sync.entity.SyncLog;
|
||||||
|
import com.banben.modules.sync.entity.SyncTask;
|
||||||
|
import com.banben.modules.sync.mapper.SyncLogMapper;
|
||||||
|
import com.banben.modules.sync.mapper.SyncTaskMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按任务配置抽取、转换、校验、去重并写入业务库。
|
||||||
|
* 连接失败会按任务上的重试次数重试;已经写入过数据后不再整批重跑,避免重复插入。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncRunner {
|
||||||
|
|
||||||
|
private static final Set<String> BLOCKED_TABLES = Set.of(
|
||||||
|
"sync_datasource", "sync_task", "sync_field_map", "sync_log",
|
||||||
|
"sys_user", "sys_role", "sys_role_menu"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final List<String> SYSTEM_COLUMNS = List.of(
|
||||||
|
"govern_status", "deleted", "create_time", "update_time",
|
||||||
|
"abnormal_flag", "sensitive_flag", "is_special", "manage_status"
|
||||||
|
);
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final SyncLogMapper logMapper;
|
||||||
|
private final SyncTaskMapper taskMapper;
|
||||||
|
private final ExecutorService workers = Executors.newFixedThreadPool(2, runnable -> {
|
||||||
|
Thread thread = new Thread(runnable, "sync-worker");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
});
|
||||||
|
private final Set<Long> running = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
|
public void submit(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings, SyncLog syncLog) {
|
||||||
|
if (!running.add(task.getId())) {
|
||||||
|
syncLog.setStatus("FAILED");
|
||||||
|
syncLog.setEndTime(LocalDateTime.now());
|
||||||
|
syncLog.setErrorMessage("该任务正在同步");
|
||||||
|
logMapper.updateById(syncLog);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
workers.submit(() -> {
|
||||||
|
try {
|
||||||
|
execute(task, source, mappings, syncLog);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("同步任务 {} 执行失败", task.getId(), e);
|
||||||
|
finish(syncLog, task, 0, 0, 0, null, e.getMessage(), null);
|
||||||
|
} finally {
|
||||||
|
running.remove(task.getId());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isRunning(Long taskId) {
|
||||||
|
return running.contains(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> previewColumns(SyncDatasource source, String sql) {
|
||||||
|
String query = applyWatermark(SqlGuard.selectSql(sql), null, "FULL");
|
||||||
|
try (Connection connection = JdbcSources.open(source);
|
||||||
|
Statement statement = connection.createStatement()) {
|
||||||
|
statement.setMaxRows(1);
|
||||||
|
statement.setQueryTimeout(20);
|
||||||
|
try (ResultSet rs = statement.executeQuery(query)) {
|
||||||
|
ResultSetMetaData meta = rs.getMetaData();
|
||||||
|
List<String> columns = new ArrayList<>();
|
||||||
|
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||||
|
columns.add(meta.getColumnLabel(i));
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new BusinessException(JdbcSources.safeMessage(e, source.getPassword()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void execute(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings, SyncLog syncLog) {
|
||||||
|
String table = SqlGuard.identifier(task.getTargetTable(), "目标表");
|
||||||
|
if (BLOCKED_TABLES.contains(table.toLowerCase(Locale.ROOT))) {
|
||||||
|
finish(syncLog, task, 0, 0, 0, null, "不能写入系统配置表 " + table, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Set<String> targetColumns = loadColumns(table);
|
||||||
|
if (targetColumns.isEmpty()) {
|
||||||
|
finish(syncLog, task, 0, 0, 0, null, "业务库中不存在表 " + table, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<String> uniqueFields = uniqueFields(task, targetColumns);
|
||||||
|
String sql = applyWatermark(SqlGuard.selectSql(task.getQuerySql()), task.getIncrementValue(), task.getSyncMode());
|
||||||
|
int batchSize = task.getBatchSize() == null || task.getBatchSize() < 1 ? 200 : Math.min(task.getBatchSize(), 2000);
|
||||||
|
int retries = task.getRetryTimes() == null || task.getRetryTimes() < 0 ? 0 : Math.min(task.getRetryTimes(), 5);
|
||||||
|
|
||||||
|
Extracted extracted = new Extracted();
|
||||||
|
extracted.watermark = task.getIncrementValue();
|
||||||
|
StringBuilder detail = new StringBuilder();
|
||||||
|
int attempt = 0;
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
readAndWrite(task, source, mappings, table, targetColumns, uniqueFields, sql, batchSize, detail, extracted);
|
||||||
|
break;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
attempt++;
|
||||||
|
String message = JdbcSources.safeMessage(e, source.getPassword());
|
||||||
|
log.warn("同步任务 {} 第 {} 次失败:{}", task.getId(), attempt, message);
|
||||||
|
if (extracted.success > 0 || attempt > retries) {
|
||||||
|
finish(syncLog, task, extracted.success, extracted.failed, extracted.skipped,
|
||||||
|
extracted.watermark, message, detail.toString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sleep(attempt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finish(syncLog, task, extracted.success, extracted.failed, extracted.skipped,
|
||||||
|
extracted.watermark, null, detail.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void readAndWrite(SyncTask task, SyncDatasource source, List<SyncFieldMap> mappings,
|
||||||
|
String table, Set<String> targetColumns, List<String> uniqueFields,
|
||||||
|
String sql, int batchSize, StringBuilder detail, Extracted extracted) throws SQLException {
|
||||||
|
InsertPlan plan = insertPlan(task.getId(), table, mappings, targetColumns);
|
||||||
|
List<Map<String, Object>> batch = new ArrayList<>();
|
||||||
|
int sequence = 0;
|
||||||
|
try (Connection connection = JdbcSources.open(source);
|
||||||
|
Statement statement = connection.createStatement()) {
|
||||||
|
statement.setFetchSize(batchSize);
|
||||||
|
statement.setQueryTimeout(300);
|
||||||
|
try (ResultSet rs = statement.executeQuery(sql)) {
|
||||||
|
Map<String, Integer> labels = columnIndex(rs.getMetaData());
|
||||||
|
while (rs.next()) {
|
||||||
|
sequence++;
|
||||||
|
try {
|
||||||
|
Map<String, Object> row = new LinkedHashMap<>();
|
||||||
|
for (SyncFieldMap map : mappings) {
|
||||||
|
Object raw = readRaw(rs, labels, map.getSourceField());
|
||||||
|
row.put(map.getTargetField().toLowerCase(Locale.ROOT),
|
||||||
|
RowConverter.convert(map, raw, task.getId(), sequence));
|
||||||
|
}
|
||||||
|
fillSystem(row, targetColumns);
|
||||||
|
String nextWatermark = readWatermark(rs, labels, task.getIncrementColumn());
|
||||||
|
if (nextWatermark != null) {
|
||||||
|
extracted.watermark = maxWatermark(extracted.watermark, nextWatermark);
|
||||||
|
}
|
||||||
|
batch.add(row);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
extracted.failed++;
|
||||||
|
appendDetail(detail, sequence, e.getMessage());
|
||||||
|
}
|
||||||
|
if (batch.size() >= batchSize) {
|
||||||
|
writeBatch(plan, uniqueFields, batch, extracted, detail);
|
||||||
|
batch.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!batch.isEmpty()) {
|
||||||
|
writeBatch(plan, uniqueFields, batch, extracted, detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeBatch(InsertPlan plan, List<String> uniqueFields, List<Map<String, Object>> batch,
|
||||||
|
Extracted extracted, StringBuilder detail) {
|
||||||
|
List<Map<String, Object>> fresh = dropDuplicates(plan.table, uniqueFields, batch, extracted);
|
||||||
|
if (fresh.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<Object[]> args = new ArrayList<>();
|
||||||
|
for (Map<String, Object> row : fresh) {
|
||||||
|
Object[] values = new Object[plan.columns.size()];
|
||||||
|
for (int i = 0; i < plan.columns.size(); i++) {
|
||||||
|
values[i] = row.get(plan.columns.get(i));
|
||||||
|
}
|
||||||
|
args.add(values);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
jdbcTemplate.batchUpdate(plan.sql, args);
|
||||||
|
extracted.success += args.size();
|
||||||
|
} catch (DataAccessException batchError) {
|
||||||
|
for (int i = 0; i < args.size(); i++) {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.update(plan.sql, args.get(i));
|
||||||
|
extracted.success++;
|
||||||
|
} catch (DataAccessException rowError) {
|
||||||
|
extracted.failed++;
|
||||||
|
appendDetail(detail, 0, JdbcSources.clip(rowError.getMostSpecificCause().getMessage(), 180));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> dropDuplicates(String table, List<String> uniqueFields,
|
||||||
|
List<Map<String, Object>> batch, Extracted extracted) {
|
||||||
|
if (uniqueFields.isEmpty()) {
|
||||||
|
return batch;
|
||||||
|
}
|
||||||
|
Set<String> seen = new LinkedHashSet<>();
|
||||||
|
List<Map<String, Object>> distinct = new ArrayList<>();
|
||||||
|
for (Map<String, Object> row : batch) {
|
||||||
|
String key = keyOf(row, uniqueFields);
|
||||||
|
if (key == null || !seen.add(key)) {
|
||||||
|
extracted.skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
distinct.add(row);
|
||||||
|
}
|
||||||
|
if (distinct.isEmpty()) {
|
||||||
|
return distinct;
|
||||||
|
}
|
||||||
|
Set<String> existing = loadExisting(table, uniqueFields, distinct);
|
||||||
|
List<Map<String, Object>> fresh = new ArrayList<>();
|
||||||
|
for (Map<String, Object> row : distinct) {
|
||||||
|
if (existing.contains(keyOf(row, uniqueFields))) {
|
||||||
|
extracted.skipped++;
|
||||||
|
} else {
|
||||||
|
fresh.add(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fresh;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> loadExisting(String table, List<String> uniqueFields, List<Map<String, Object>> rows) {
|
||||||
|
StringBuilder sql = new StringBuilder("SELECT ");
|
||||||
|
for (int i = 0; i < uniqueFields.size(); i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
sql.append(", ");
|
||||||
|
}
|
||||||
|
sql.append(SqlGuard.quote(uniqueFields.get(i)));
|
||||||
|
}
|
||||||
|
sql.append(" FROM ").append(SqlGuard.quote(table)).append(" WHERE (");
|
||||||
|
for (int i = 0; i < uniqueFields.size(); i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
sql.append(", ");
|
||||||
|
}
|
||||||
|
sql.append(SqlGuard.quote(uniqueFields.get(i)));
|
||||||
|
}
|
||||||
|
sql.append(") IN (");
|
||||||
|
List<Object> args = new ArrayList<>();
|
||||||
|
for (int r = 0; r < rows.size(); r++) {
|
||||||
|
if (r > 0) {
|
||||||
|
sql.append(", ");
|
||||||
|
}
|
||||||
|
sql.append("(");
|
||||||
|
for (int c = 0; c < uniqueFields.size(); c++) {
|
||||||
|
if (c > 0) {
|
||||||
|
sql.append(", ");
|
||||||
|
}
|
||||||
|
sql.append("?");
|
||||||
|
args.add(rows.get(r).get(uniqueFields.get(c)));
|
||||||
|
}
|
||||||
|
sql.append(")");
|
||||||
|
}
|
||||||
|
sql.append(")");
|
||||||
|
if (columnExists(table, "deleted")) {
|
||||||
|
sql.append(" AND deleted = 0");
|
||||||
|
}
|
||||||
|
Set<String> found = new LinkedHashSet<>();
|
||||||
|
jdbcTemplate.query(sql.toString(), rs -> {
|
||||||
|
Map<String, Object> row = new LinkedHashMap<>();
|
||||||
|
for (String field : uniqueFields) {
|
||||||
|
row.put(field, rs.getObject(field));
|
||||||
|
}
|
||||||
|
found.add(keyOf(row, uniqueFields));
|
||||||
|
}, args.toArray());
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
private InsertPlan insertPlan(long taskId, String table, List<SyncFieldMap> mappings, Set<String> targetColumns) {
|
||||||
|
List<String> columns = new ArrayList<>();
|
||||||
|
for (SyncFieldMap map : mappings) {
|
||||||
|
String field = SqlGuard.identifier(map.getTargetField(), "目标字段").toLowerCase(Locale.ROOT);
|
||||||
|
if (!targetColumns.contains(field)) {
|
||||||
|
throw new BusinessException("目标表 " + table + " 没有字段 " + field);
|
||||||
|
}
|
||||||
|
if (!columns.contains(field)) {
|
||||||
|
columns.add(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InsertPlan plan = new InsertPlan();
|
||||||
|
plan.table = table;
|
||||||
|
plan.columns = new ArrayList<>(columns);
|
||||||
|
for (String system : SYSTEM_COLUMNS) {
|
||||||
|
if (targetColumns.contains(system) && !plan.columns.contains(system)) {
|
||||||
|
plan.columns.add(system);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StringBuilder sql = new StringBuilder("INSERT INTO ").append(SqlGuard.quote(table)).append(" (");
|
||||||
|
StringBuilder holders = new StringBuilder();
|
||||||
|
for (int i = 0; i < plan.columns.size(); i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
sql.append(", ");
|
||||||
|
holders.append(", ");
|
||||||
|
}
|
||||||
|
sql.append(SqlGuard.quote(plan.columns.get(i)));
|
||||||
|
holders.append("?");
|
||||||
|
}
|
||||||
|
sql.append(") VALUES (").append(holders).append(")");
|
||||||
|
plan.sql = sql.toString();
|
||||||
|
log.debug("任务 {} 写入语句 {}", taskId, plan.sql);
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fillSystem(Map<String, Object> row, Set<String> targetColumns) {
|
||||||
|
Timestamp now = Timestamp.valueOf(LocalDateTime.now());
|
||||||
|
putIfAbsent(row, targetColumns, "govern_status", "RAW");
|
||||||
|
putIfAbsent(row, targetColumns, "deleted", 0);
|
||||||
|
putIfAbsent(row, targetColumns, "abnormal_flag", 0);
|
||||||
|
putIfAbsent(row, targetColumns, "sensitive_flag", 0);
|
||||||
|
putIfAbsent(row, targetColumns, "is_special", 0);
|
||||||
|
putIfAbsent(row, targetColumns, "manage_status", 0);
|
||||||
|
putIfAbsent(row, targetColumns, "create_time", now);
|
||||||
|
putIfAbsent(row, targetColumns, "update_time", now);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void putIfAbsent(Map<String, Object> row, Set<String> columns, String name, Object value) {
|
||||||
|
if (columns.contains(name) && !row.containsKey(name)) {
|
||||||
|
row.put(name, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> loadColumns(String table) {
|
||||||
|
List<String> names = jdbcTemplate.query(
|
||||||
|
"SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ?",
|
||||||
|
(rs, rowNum) -> rs.getString(1).toLowerCase(Locale.ROOT),
|
||||||
|
table.toLowerCase(Locale.ROOT));
|
||||||
|
return new LinkedHashSet<>(names);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean columnExists(String table, String column) {
|
||||||
|
Integer count = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ? AND column_name = ?",
|
||||||
|
Integer.class, table.toLowerCase(Locale.ROOT), column.toLowerCase(Locale.ROOT));
|
||||||
|
return count != null && count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> uniqueFields(SyncTask task, Set<String> targetColumns) {
|
||||||
|
if (task.getUniqueFields() == null || task.getUniqueFields().isBlank()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
List<String> fields = new ArrayList<>();
|
||||||
|
for (String part : task.getUniqueFields().split(",")) {
|
||||||
|
if (part.isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String field = SqlGuard.identifier(part, "去重字段").toLowerCase(Locale.ROOT);
|
||||||
|
if (!targetColumns.contains(field)) {
|
||||||
|
throw new BusinessException("去重字段不在目标表中:" + field);
|
||||||
|
}
|
||||||
|
fields.add(field);
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Integer> columnIndex(ResultSetMetaData meta) throws SQLException {
|
||||||
|
Map<String, Integer> labels = new LinkedHashMap<>();
|
||||||
|
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||||
|
labels.put(meta.getColumnLabel(i).toLowerCase(Locale.ROOT), i);
|
||||||
|
}
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object readRaw(ResultSet rs, Map<String, Integer> labels, String sourceField) throws SQLException {
|
||||||
|
Integer index = labels.get(sourceField.toLowerCase(Locale.ROOT));
|
||||||
|
if (index == null) {
|
||||||
|
throw new IllegalArgumentException("查询结果没有列 " + sourceField);
|
||||||
|
}
|
||||||
|
return rs.getObject(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String readWatermark(ResultSet rs, Map<String, Integer> labels, String column) throws SQLException {
|
||||||
|
if (column == null || column.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Integer index = labels.get(column.trim().toLowerCase(Locale.ROOT));
|
||||||
|
if (index == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Object value = rs.getObject(index);
|
||||||
|
return value == null ? null : String.valueOf(value).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String applyWatermark(String sql, String watermark, String mode) {
|
||||||
|
if (!sql.contains("${watermark}")) {
|
||||||
|
return sql;
|
||||||
|
}
|
||||||
|
String value = "INCREMENT".equalsIgnoreCase(mode) && watermark != null ? watermark : "";
|
||||||
|
return sql.replace("${watermark}", "'" + value.replace("'", "''") + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String maxWatermark(String current, String next) {
|
||||||
|
if (next == null || next.isBlank()) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
if (current == null || current.isBlank()) {
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
if (current.chars().allMatch(Character::isDigit) && next.chars().allMatch(Character::isDigit)) {
|
||||||
|
return new BigDecimal(next).compareTo(new BigDecimal(current)) > 0 ? next : current;
|
||||||
|
}
|
||||||
|
return next.compareTo(current) > 0 ? next : current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String keyOf(Map<String, Object> row, List<String> fields) {
|
||||||
|
StringBuilder key = new StringBuilder();
|
||||||
|
for (String field : fields) {
|
||||||
|
Object value = row.get(field);
|
||||||
|
if (value == null || String.valueOf(value).isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
key.append('\u0001').append(value);
|
||||||
|
}
|
||||||
|
return key.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finish(SyncLog syncLog, SyncTask task, int success, int failed, int skipped,
|
||||||
|
String watermark, String error, String detail) {
|
||||||
|
syncLog.setSuccessCount(success);
|
||||||
|
syncLog.setFailCount(failed);
|
||||||
|
syncLog.setSkipCount(skipped);
|
||||||
|
syncLog.setEndTime(LocalDateTime.now());
|
||||||
|
syncLog.setErrorMessage(JdbcSources.clip(error, 2000));
|
||||||
|
syncLog.setDetail(JdbcSources.clip(detail, 4000));
|
||||||
|
if (error != null && success == 0) {
|
||||||
|
syncLog.setStatus("FAILED");
|
||||||
|
} else if (failed > 0 || error != null) {
|
||||||
|
syncLog.setStatus("PARTIAL");
|
||||||
|
} else {
|
||||||
|
syncLog.setStatus("SUCCESS");
|
||||||
|
}
|
||||||
|
logMapper.updateById(syncLog);
|
||||||
|
if (error == null && watermark != null && !watermark.equals(task.getIncrementValue())) {
|
||||||
|
task.setIncrementValue(watermark);
|
||||||
|
taskMapper.updateById(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendDetail(StringBuilder detail, int sequence, String message) {
|
||||||
|
if (detail.length() > 3500) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (sequence > 0) {
|
||||||
|
detail.append("第").append(sequence).append("行:");
|
||||||
|
}
|
||||||
|
detail.append(message).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sleep(int attempt) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000L * attempt);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Extracted {
|
||||||
|
private int success;
|
||||||
|
private int failed;
|
||||||
|
private int skipped;
|
||||||
|
private String watermark;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class InsertPlan {
|
||||||
|
private String table;
|
||||||
|
private String sql;
|
||||||
|
private List<String> columns;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.banben.modules.synchub;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||||
|
import com.banben.modules.synchub.mapper.SyncHubRecordMapper;
|
||||||
|
import com.banben.modules.synchub.service.SyncHubService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把还没超过次数的失败记录再送一次。调度开关沿用现有的定时任务配置。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncHubRetryScheduler {
|
||||||
|
|
||||||
|
private final SyncHubRecordMapper recordMapper;
|
||||||
|
private final SyncHubService syncHubService;
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 60000, initialDelay = 45000)
|
||||||
|
public void retryFailed() {
|
||||||
|
List<SyncHubRecord> failed = recordMapper.selectList(new LambdaQueryWrapper<SyncHubRecord>()
|
||||||
|
.eq(SyncHubRecord::getStatus, "FAILED")
|
||||||
|
.apply("retry_count < max_retry")
|
||||||
|
.orderByAsc(SyncHubRecord::getId)
|
||||||
|
.last("LIMIT 5"));
|
||||||
|
for (SyncHubRecord record : failed) {
|
||||||
|
syncHubService.retryQuiet(record.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package com.banben.modules.synchub;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.service.BookCleaner;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动时补齐汇聚用的两张表。已有数据不动,也不改 version_resource。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncHubTableInitializer {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final BookCleaner cleaner;
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void init() {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_hub_record ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "task_no VARCHAR(64) NOT NULL, "
|
||||||
|
+ "direction VARCHAR(8) NOT NULL, "
|
||||||
|
+ "source_node VARCHAR(32), "
|
||||||
|
+ "target_node VARCHAR(32), "
|
||||||
|
+ "source_db VARCHAR(32), "
|
||||||
|
+ "book_count INTEGER DEFAULT 0, "
|
||||||
|
+ "skip_count INTEGER DEFAULT 0, "
|
||||||
|
+ "status VARCHAR(16) NOT NULL, "
|
||||||
|
+ "error_message VARCHAR(1000), "
|
||||||
|
+ "retry_count INTEGER DEFAULT 0, "
|
||||||
|
+ "max_retry INTEGER DEFAULT 3, "
|
||||||
|
+ "start_time TIMESTAMP, "
|
||||||
|
+ "end_time TIMESTAMP, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_sync_hub_record_status ON sync_hub_record (status, create_time)");
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_hub_book ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "holder VARCHAR(32) NOT NULL, "
|
||||||
|
+ "doc_id VARCHAR(320) NOT NULL, "
|
||||||
|
+ "match_key VARCHAR(320), "
|
||||||
|
+ "node_code VARCHAR(32), "
|
||||||
|
+ "source_db VARCHAR(32), "
|
||||||
|
+ "process_no VARCHAR(128), "
|
||||||
|
+ "title VARCHAR(512), "
|
||||||
|
+ "media_type VARCHAR(32), "
|
||||||
|
+ "payload TEXT NOT NULL, "
|
||||||
|
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book ON sync_hub_book (holder, doc_id)");
|
||||||
|
jdbcTemplate.execute("ALTER TABLE sync_hub_record ADD COLUMN IF NOT EXISTS skip_count INTEGER DEFAULT 0");
|
||||||
|
jdbcTemplate.execute("ALTER TABLE sync_hub_book ADD COLUMN IF NOT EXISTS match_key VARCHAR(320)");
|
||||||
|
jdbcTemplate.execute("ALTER TABLE sync_hub_book ALTER COLUMN doc_id TYPE VARCHAR(320)");
|
||||||
|
backfillMatchKeys();
|
||||||
|
jdbcTemplate.execute("CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book_match ON sync_hub_book (holder, match_key)");
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sync_hub_cursor ("
|
||||||
|
+ "node_code VARCHAR(32) NOT NULL PRIMARY KEY, "
|
||||||
|
+ "last_resource_id BIGINT DEFAULT 0, "
|
||||||
|
+ "update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
log.info("图书汇聚表已就绪");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 给早先写入的书补上比对键。同一本书只留最早的一条。 */
|
||||||
|
private void backfillMatchKeys() {
|
||||||
|
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, holder, payload FROM sync_hub_book WHERE match_key IS NULL OR match_key = '' ORDER BY id");
|
||||||
|
for (Map<String, Object> row : rows) {
|
||||||
|
long id = ((Number) row.get("id")).longValue();
|
||||||
|
String holder = String.valueOf(row.get("holder"));
|
||||||
|
BookDocument book;
|
||||||
|
try {
|
||||||
|
book = objectMapper.readValue(String.valueOf(row.get("payload")), BookDocument.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String key = cleaner.matchKey(book);
|
||||||
|
List<Long> others = jdbcTemplate.query(
|
||||||
|
"SELECT id FROM sync_hub_book WHERE holder = ? AND (doc_id = ? OR match_key = ?) AND id <> ?",
|
||||||
|
(rs, rowNum) -> rs.getLong(1), holder, key, key, id);
|
||||||
|
if (!others.isEmpty()) {
|
||||||
|
jdbcTemplate.update("DELETE FROM sync_hub_book WHERE id = ?", id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
jdbcTemplate.update("UPDATE sync_hub_book SET doc_id = ?, match_key = ? WHERE id = ?", key, key, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.banben.modules.synchub.config;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验同步口令。/api/hub 下的接口不使用登录令牌,必须带请求头 X-Hub-Token。
|
||||||
|
* 值要和 application-dev.yml 里的 sync-hub.token 完全一致,开发环境是 local-mock-hub。
|
||||||
|
* 没带这个头、或者值不一致,直接返回 401。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class HubTokenInterceptor implements HandlerInterceptor {
|
||||||
|
|
||||||
|
public static final String HEADER = "X-Hub-Token";
|
||||||
|
|
||||||
|
private final SyncHubProperties properties;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||||
|
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
String configured = properties.getToken() == null ? "" : properties.getToken();
|
||||||
|
String given = request.getHeader(HEADER);
|
||||||
|
if (configured.isBlank() || given == null || !MessageDigest.isEqual(configured.getBytes(StandardCharsets.UTF_8), given.getBytes(StandardCharsets.UTF_8))) {
|
||||||
|
response.setStatus(401);
|
||||||
|
response.setContentType("application/json;charset=UTF-8");
|
||||||
|
response.getWriter().write("{\"code\":401,\"message\":\"同步口令不正确,请在请求头 X-Hub-Token 中填写与 sync-hub.token 相同的值\"}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.banben.modules.synchub.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 节点与南昌总库的同步配置。地址和口令都从这里读,不写死真实库账号。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "sync-hub")
|
||||||
|
public class SyncHubProperties {
|
||||||
|
|
||||||
|
/** 两台电脑互相调用时放在请求头 X-Hub-Token */
|
||||||
|
private String token = "";
|
||||||
|
|
||||||
|
/** es:写入 Elasticsearch;jdbc:写入 sync_hub_book,供本机没有 ES 时联调 */
|
||||||
|
private String store = "es";
|
||||||
|
|
||||||
|
private String esUris = "http://127.0.0.1:9200";
|
||||||
|
|
||||||
|
private String esIndex = "book_metadata";
|
||||||
|
|
||||||
|
/** 节点把数据推到这个总库地址 */
|
||||||
|
private String centerUrl = "http://127.0.0.1:8080";
|
||||||
|
|
||||||
|
/** 总库入库成功后是否立刻回传给各节点 */
|
||||||
|
private boolean autoDispatch = true;
|
||||||
|
|
||||||
|
private int retryMax = 3;
|
||||||
|
|
||||||
|
/** 一次读取、接收或回传的条数。数据量大时按这个数分批,不一次全量传输。 */
|
||||||
|
private int batchSize = 200;
|
||||||
|
|
||||||
|
/** 和 batchSize 同义,保留给旧配置。 */
|
||||||
|
private int dispatchLimit = 200;
|
||||||
|
|
||||||
|
public int pageSize() {
|
||||||
|
int size = batchSize > 0 ? batchSize : dispatchLimit;
|
||||||
|
if (size < 1) {
|
||||||
|
size = 200;
|
||||||
|
}
|
||||||
|
return Math.min(size, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Node> nodes = new ArrayList<>();
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class Node {
|
||||||
|
private String code;
|
||||||
|
private String name;
|
||||||
|
/** MYSQL、SQLSERVER、MOCK,多个用逗号 */
|
||||||
|
private String kinds = "MOCK";
|
||||||
|
private String callbackUrl = "http://127.0.0.1:8080";
|
||||||
|
private String mysqlUrl = "";
|
||||||
|
private String mysqlUser = "";
|
||||||
|
private String mysqlPassword = "";
|
||||||
|
private String mysqlQuery = "";
|
||||||
|
/** 纸质书写入这张表,陆工大测试库是 book_attr */
|
||||||
|
private String paperTable = "book_attr";
|
||||||
|
/** 电子书写入这张表,陆工大测试库是 e_book */
|
||||||
|
private String ebookTable = "e_book";
|
||||||
|
private String sqlserverUrl = "";
|
||||||
|
private String sqlserverUser = "";
|
||||||
|
private String sqlserverPassword = "";
|
||||||
|
private String sqlserverQuery = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node find(String code) {
|
||||||
|
if (code == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return nodes.stream().filter(node -> code.equalsIgnoreCase(node.getCode())).findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package com.banben.modules.synchub.controller;
|
||||||
|
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.service.SyncHubService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.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.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 节点与南昌总库的图书同步接口。
|
||||||
|
*
|
||||||
|
* <p>不使用登录令牌。每个请求都要加请求头 {@code X-Hub-Token},
|
||||||
|
* 值与 {@code application-dev.yml} 的 {@code sync-hub.token} 相同。
|
||||||
|
* 开发环境填 {@code local-mock-hub}。不带或填错返回 401。</p>
|
||||||
|
*
|
||||||
|
* <p>手工测试时优先调 {@code POST /api/hub/node/push}。
|
||||||
|
* 总库收书、节点收书这两个地址是两台电脑互相调用时用的。</p>
|
||||||
|
*/
|
||||||
|
@Tag(name = "图书汇聚", description = "请求头 X-Hub-Token 必填。节点上推、总库接收入库、缺书回补")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/hub")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncHubController {
|
||||||
|
|
||||||
|
private final SyncHubService syncHubService;
|
||||||
|
private final SyncHubProperties properties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 节点读一页本地图书并推到总库。
|
||||||
|
* 总库按 ISBN(没有 ISBN 则按题名+作者+出版年)比对,重复的不入库。
|
||||||
|
* 返回的 nextOffset 有值时,原样作为下一次的 offset 再调,直到它为空。
|
||||||
|
*/
|
||||||
|
@Operation(summary = "节点读取一页本地图书并推送到总库")
|
||||||
|
@PostMapping("/node/push")
|
||||||
|
public Result<SyncHubRecord> push(
|
||||||
|
@Parameter(description = "节点编码。NJ_LZ 南京陆指,NJ_LGD 南京陆工大,BHF 边海防", required = true)
|
||||||
|
@RequestParam String node,
|
||||||
|
@Parameter(description = "从哪里读。MOCK 模拟数据;MYSQL 读该节点配置的 MySQL;SQLSERVER 读 SQL Server。不传默认 MOCK")
|
||||||
|
@RequestParam(defaultValue = "MOCK") String source,
|
||||||
|
@Parameter(description = "只推这一类书。纸质 或 电子。不传表示这一页里的书都推")
|
||||||
|
@RequestParam(required = false) String media,
|
||||||
|
@Parameter(description = "从第几条开始读,从 0 起。下一页把上次返回的 nextOffset 填到这里")
|
||||||
|
@RequestParam(defaultValue = "0") int offset,
|
||||||
|
@Parameter(description = "这一页最多几条。不传用 sync-hub.batch-size,默认 200,最大 1000")
|
||||||
|
@RequestParam(required = false) Integer limit) {
|
||||||
|
return Result.success(syncHubService.pushFromNode(node, source, media, offset, limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 总库接收入库。节点上推时会自己调用它,两台电脑联调时由对方机器调用。
|
||||||
|
* 请求体字段:nodeCode 节点编码,sourceDb 来源库类型,books 图书数组。
|
||||||
|
*/
|
||||||
|
@Operation(summary = "总库接收节点推来的图书。重复的不入库,新的才入库")
|
||||||
|
@PostMapping("/center/receive")
|
||||||
|
public Result<SyncHubRecord> receive(@RequestBody SyncHubService.ReceiveBody body) {
|
||||||
|
return Result.success(syncHubService.receiveAtCenter(body.nodeCode(), body.sourceDb(), body.books()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 总库往下推。
|
||||||
|
* 陆工大已配置 MySQL 时,从 version_resource 按批读取:纸质写入 book_attr,电子写入 e_book,已有 ISBN 的跳过。
|
||||||
|
* 一次最多新增 batch-size 条,没有推完时返回里会提示再调一次。不会一次写完总库全部图书。
|
||||||
|
*/
|
||||||
|
@Operation(summary = "总库按测试库表结构把 version_resource 分批回写到节点")
|
||||||
|
@PostMapping("/center/dispatch")
|
||||||
|
public Result<List<SyncHubRecord>> dispatch() {
|
||||||
|
return Result.success(syncHubService.dispatchAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 节点收下总库补来的书。节点里已经有的不再写,也不会再推回总库。
|
||||||
|
* 请求体字段:nodeCode 收下的节点,books 要补进该节点的书。
|
||||||
|
*/
|
||||||
|
@Operation(summary = "节点接收总库补来的图书")
|
||||||
|
@PostMapping("/node/receive")
|
||||||
|
public Result<SyncHubRecord> receiveBack(@RequestBody SyncHubService.DeliverBody body) {
|
||||||
|
return Result.success(syncHubService.receiveAtNode(body.nodeCode(), body.books()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查看同步记录。bookCount 是新写入条数,skipCount 是重复跳过条数。 */
|
||||||
|
@Operation(summary = "同步记录")
|
||||||
|
@GetMapping("/record")
|
||||||
|
public Result<List<SyncHubRecord>> records(
|
||||||
|
@Parameter(description = "返回最近多少条,默认 50,最大 200")
|
||||||
|
@RequestParam(defaultValue = "50") int limit) {
|
||||||
|
return Result.success(syncHubService.listRecords(limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 对一条失败记录再执行一次。已经成功或超过 maxRetry 的不能再试。 */
|
||||||
|
@Operation(summary = "重试一条失败记录")
|
||||||
|
@PostMapping("/record/{id}/retry")
|
||||||
|
public Result<SyncHubRecord> retry(
|
||||||
|
@Parameter(description = "同步记录的 id,从 /api/hub/record 的返回里取", required = true)
|
||||||
|
@PathVariable Long id) {
|
||||||
|
return Result.success(syncHubService.retry(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查看总库或某个节点已经收下的书,用来核对去重和回补结果。 */
|
||||||
|
@Operation(summary = "查看总库或某个节点已经收下的图书")
|
||||||
|
@GetMapping("/books")
|
||||||
|
public Result<List<BookDocument>> books(
|
||||||
|
@Parameter(description = "CENTER 总库;或节点编码 NJ_LZ、NJ_LGD、BHF。默认 CENTER")
|
||||||
|
@RequestParam(defaultValue = "CENTER") String holder,
|
||||||
|
@Parameter(description = "最多返回多少条,默认 20,最大 100")
|
||||||
|
@RequestParam(defaultValue = "20") int limit) {
|
||||||
|
return Result.success(syncHubService.listBooks(holder, limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只查看模拟图书,不推送、不入库。用来确认节点编码和模拟数据。 */
|
||||||
|
@Operation(summary = "查看某个节点的模拟图书,不入库")
|
||||||
|
@GetMapping("/mock/books")
|
||||||
|
public Result<List<BookDocument>> mockBooks(
|
||||||
|
@Parameter(description = "节点编码。NJ_LZ、NJ_LGD、BHF", required = true)
|
||||||
|
@RequestParam String node,
|
||||||
|
@Parameter(description = "只看这一类。纸质 或 电子。不传返回该节点的全部模拟书")
|
||||||
|
@RequestParam(required = false) String media) {
|
||||||
|
return Result.success(syncHubService.mockBooks(node, media));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 节点清单。只返回编码、名称、库类型和回传地址,不含数据库账号。 */
|
||||||
|
@Operation(summary = "节点清单,不含数据库口令")
|
||||||
|
@GetMapping("/nodes")
|
||||||
|
public Result<List<NodeView>> nodes() {
|
||||||
|
List<NodeView> views = new ArrayList<>();
|
||||||
|
for (SyncHubProperties.Node node : properties.getNodes()) {
|
||||||
|
NodeView view = new NodeView();
|
||||||
|
view.setCode(node.getCode());
|
||||||
|
view.setName(node.getName());
|
||||||
|
view.setKinds(node.getKinds());
|
||||||
|
view.setCallbackUrl(node.getCallbackUrl());
|
||||||
|
views.add(view);
|
||||||
|
}
|
||||||
|
return Result.success(views);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 节点清单里的一项,不含数据库地址和口令。 */
|
||||||
|
@Data
|
||||||
|
public static class NodeView {
|
||||||
|
/** 节点编码,调用 push 时传给 node */
|
||||||
|
private String code;
|
||||||
|
/** 节点名称,如南京陆工大 */
|
||||||
|
private String name;
|
||||||
|
/** 这个节点能读的库类型,多个用逗号分隔,如 MYSQL,SQLSERVER */
|
||||||
|
private String kinds;
|
||||||
|
/** 总库把缺书补回这个地址 */
|
||||||
|
private String callbackUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.banben.modules.synchub.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 一次同步的记录:谁发给谁、什么时候、成功还是失败。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sync_hub_record")
|
||||||
|
public class SyncHubRecord {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** 本次同步编号,排查日志时用 */
|
||||||
|
private String taskNo;
|
||||||
|
|
||||||
|
/** UP:节点推总库。DOWN:总库把缺的书补回节点 */
|
||||||
|
private String direction;
|
||||||
|
|
||||||
|
/** 数据从哪个节点发出。总库回传时是 NC_CENTER */
|
||||||
|
private String sourceNode;
|
||||||
|
|
||||||
|
/** 数据送到哪里。上推时是 NC_CENTER,回传时是节点编码 */
|
||||||
|
private String targetNode;
|
||||||
|
|
||||||
|
/** 读取来源:MOCK、MYSQL、SQLSERVER,回传时为 CENTER */
|
||||||
|
private String sourceDb;
|
||||||
|
|
||||||
|
/** 这次新写入的条数 */
|
||||||
|
private Integer bookCount;
|
||||||
|
|
||||||
|
/** 比对后已存在、没有写入的条数 */
|
||||||
|
private Integer skipCount;
|
||||||
|
|
||||||
|
/** RUNNING 进行中,SUCCESS 成功,FAILED 失败 */
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
/** 失败原因。成功且还有下一批回传时,这里会提示再调一次回传接口 */
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
/** 已经重试过几次 */
|
||||||
|
private Integer retryCount;
|
||||||
|
|
||||||
|
/** 最多还能重试几次,默认 3 */
|
||||||
|
private Integer maxRetry;
|
||||||
|
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
/** 源库还有下一批时返回,调用方用它继续取。不入库。 */
|
||||||
|
@TableField(exist = false)
|
||||||
|
private Integer nextOffset;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.banben.modules.synchub.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||||
|
|
||||||
|
public interface SyncHubRecordMapper extends BaseMapper<SyncHubRecord> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.banben.modules.synchub.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在节点和总库之间传递的一条图书元数据。字段与 version_resource 的书目项对应,不直接改那张表。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class BookDocument {
|
||||||
|
|
||||||
|
private String nodeCode;
|
||||||
|
|
||||||
|
/** MYSQL / SQLSERVER / MOCK */
|
||||||
|
private String sourceDb;
|
||||||
|
|
||||||
|
private String processNo;
|
||||||
|
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
/** 其他题名,下推到 book_attr.TITLE_S */
|
||||||
|
private String otherTitle;
|
||||||
|
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
private String isbn;
|
||||||
|
|
||||||
|
private String publisher;
|
||||||
|
|
||||||
|
private String publishYear;
|
||||||
|
|
||||||
|
/** 出版日期,下推到 PUB_DATE */
|
||||||
|
private String publishDate;
|
||||||
|
|
||||||
|
/** 版次,下推到 book_attr.VERSION */
|
||||||
|
private String edition;
|
||||||
|
|
||||||
|
private String keywords;
|
||||||
|
|
||||||
|
private String summary;
|
||||||
|
|
||||||
|
private String clcCode;
|
||||||
|
|
||||||
|
private String mediaType;
|
||||||
|
|
||||||
|
private String language;
|
||||||
|
|
||||||
|
private String contentForm;
|
||||||
|
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
|
private String fulltextUrl;
|
||||||
|
|
||||||
|
/** version_resource.id,只在总库下推时用来记住读到哪一条。 */
|
||||||
|
@JsonIgnore
|
||||||
|
private Long resourceId;
|
||||||
|
|
||||||
|
@JsonIgnore
|
||||||
|
public String docId() {
|
||||||
|
String node = nodeCode == null ? "NODE" : nodeCode.trim();
|
||||||
|
String no = processNo == null || processNo.isBlank() ? title : processNo.trim();
|
||||||
|
return node + ":" + no;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.banben.modules.synchub.reader;
|
||||||
|
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从分支节点的本地库读取图书。MOCK、MYSQL、SQLSERVER 各有一个实现。
|
||||||
|
*/
|
||||||
|
public interface BookReader {
|
||||||
|
|
||||||
|
boolean supports(String source);
|
||||||
|
|
||||||
|
List<BookDocument> read(SyncHubProperties.Node node, String mediaType);
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package com.banben.modules.synchub.reader;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按节点配置读取 MySQL 或 SQL Server。地址没配时直接拒绝,不会去连测试机。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class JdbcRemoteBookReader implements BookReader {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supports(String source) {
|
||||||
|
return "MYSQL".equalsIgnoreCase(source) || "SQLSERVER".equalsIgnoreCase(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> read(SyncHubProperties.Node node, String mediaType) {
|
||||||
|
throw new BusinessException("请指定 MYSQL 或 SQLSERVER");
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookDocument> read(SyncHubProperties.Node node, String source, String mediaType) {
|
||||||
|
return readPage(node, source, mediaType, 0, 200).books();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按 offset 取一页。more 为 true 表示后面还有,调用方继续传下一个 offset。 */
|
||||||
|
public Page readPage(SyncHubProperties.Node node, String source, String mediaType, int offset, int limit) {
|
||||||
|
boolean mysql = "MYSQL".equalsIgnoreCase(source);
|
||||||
|
String url = mysql ? node.getMysqlUrl() : node.getSqlserverUrl();
|
||||||
|
String user = mysql ? node.getMysqlUser() : node.getSqlserverUser();
|
||||||
|
String password = mysql ? node.getMysqlPassword() : node.getSqlserverPassword();
|
||||||
|
String query = mysql ? node.getMysqlQuery() : node.getSqlserverQuery();
|
||||||
|
if (url == null || url.isBlank() || query == null || query.isBlank()) {
|
||||||
|
throw new BusinessException(node.getName() + " 还没配置 " + source + " 的地址和查询。本地联调请传 source=MOCK");
|
||||||
|
}
|
||||||
|
String sql = query.trim();
|
||||||
|
if (sql.endsWith(";")) {
|
||||||
|
sql = sql.substring(0, sql.length() - 1).trim();
|
||||||
|
}
|
||||||
|
String head = sql.toLowerCase(Locale.ROOT);
|
||||||
|
if ((!head.startsWith("select") && !head.startsWith("with")) || sql.indexOf(';') >= 0) {
|
||||||
|
throw new BusinessException("节点查询只能是一条 SELECT");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Class.forName(mysql ? "com.mysql.cj.jdbc.Driver" : "com.microsoft.sqlserver.jdbc.SQLServerDriver");
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
throw new BusinessException("缺少 " + source + " 驱动");
|
||||||
|
}
|
||||||
|
int size = limit < 1 ? 200 : Math.min(limit, 1000);
|
||||||
|
int start = Math.max(offset, 0);
|
||||||
|
String pageSql = pageSql(sql, mysql, start, size);
|
||||||
|
List<BookDocument> books = new ArrayList<>();
|
||||||
|
int raw = 0;
|
||||||
|
try (Connection connection = DriverManager.getConnection(url, user, password);
|
||||||
|
Statement statement = connection.createStatement()) {
|
||||||
|
statement.setQueryTimeout(20);
|
||||||
|
try (ResultSet rs = statement.executeQuery(pageSql)) {
|
||||||
|
Map<String, Integer> labels = labels(rs.getMetaData());
|
||||||
|
while (rs.next()) {
|
||||||
|
raw++;
|
||||||
|
BookDocument book = mapRow(node, source, rs, labels);
|
||||||
|
if (mediaType != null && !mediaType.isBlank() && !"ALL".equalsIgnoreCase(mediaType)
|
||||||
|
&& book.getMediaType() != null && !mediaType.equals(book.getMediaType())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
books.add(book);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
String message = e.getMessage() == null ? "读取失败" : e.getMessage();
|
||||||
|
if (password != null && !password.isBlank()) {
|
||||||
|
message = message.replace(password, "******");
|
||||||
|
}
|
||||||
|
throw new BusinessException("读取 " + node.getName() + " 失败:" + message);
|
||||||
|
}
|
||||||
|
return new Page(books, raw >= size && !alreadyPaged(sql));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String pageSql(String sql, boolean mysql, int offset, int limit) {
|
||||||
|
if (alreadyPaged(sql)) {
|
||||||
|
return offset > 0 ? "SELECT * FROM (" + sql + ") hub_src WHERE 1 = 0" : sql;
|
||||||
|
}
|
||||||
|
if (mysql) {
|
||||||
|
return "SELECT * FROM (" + sql + ") hub_src LIMIT " + limit + " OFFSET " + offset;
|
||||||
|
}
|
||||||
|
return "SELECT * FROM (" + sql + ") hub_src ORDER BY (SELECT 1) OFFSET " + offset
|
||||||
|
+ " ROWS FETCH NEXT " + limit + " ROWS ONLY";
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean alreadyPaged(String sql) {
|
||||||
|
String text = sql.toLowerCase(Locale.ROOT);
|
||||||
|
return text.contains(" limit ") || text.contains(" offset ") || text.contains(" fetch ") || text.contains(" top ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一页读取结果。more 表示这一页被取满,源库后面可能还有。 */
|
||||||
|
public record Page(List<BookDocument> books, boolean more) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Integer> labels(ResultSetMetaData meta) throws SQLException {
|
||||||
|
Map<String, Integer> labels = new LinkedHashMap<>();
|
||||||
|
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||||
|
labels.put(meta.getColumnLabel(i).toLowerCase(Locale.ROOT), i);
|
||||||
|
}
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookDocument mapRow(SyncHubProperties.Node node, String source, ResultSet rs, Map<String, Integer> labels) throws SQLException {
|
||||||
|
BookDocument book = new BookDocument();
|
||||||
|
book.setNodeCode(node.getCode());
|
||||||
|
book.setSourceDb(source.toUpperCase(Locale.ROOT));
|
||||||
|
book.setProcessNo(text(rs, labels, "process_no", "processno", "record_id", "recordid"));
|
||||||
|
book.setTitle(text(rs, labels, "title", "book_name", "name"));
|
||||||
|
book.setAuthor(text(rs, labels, "author"));
|
||||||
|
book.setIsbn(text(rs, labels, "isbn", "isbn13", "isbn_13", "e_isbn", "eisbn"));
|
||||||
|
book.setPublisher(text(rs, labels, "publisher"));
|
||||||
|
book.setPublishYear(text(rs, labels, "publish_year", "publishyear", "pub_year"));
|
||||||
|
book.setKeywords(text(rs, labels, "keywords", "subject"));
|
||||||
|
book.setSummary(text(rs, labels, "summary", "description"));
|
||||||
|
book.setClcCode(text(rs, labels, "clc_code", "clc", "call_no"));
|
||||||
|
book.setMediaType(text(rs, labels, "media_type", "mediatype"));
|
||||||
|
book.setLanguage(text(rs, labels, "language"));
|
||||||
|
book.setContentForm(text(rs, labels, "content_form"));
|
||||||
|
book.setSourceLibrary(firstNonBlank(text(rs, labels, "source_library"), node.getName()));
|
||||||
|
book.setFulltextUrl(text(rs, labels, "fulltext_url", "find_jump_url"));
|
||||||
|
if (book.getProcessNo() == null || book.getProcessNo().isBlank()) {
|
||||||
|
book.setProcessNo(node.getCode() + "-" + (book.getIsbn() == null ? book.getTitle() : book.getIsbn()));
|
||||||
|
}
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String text(ResultSet rs, Map<String, Integer> labels, String... names) throws SQLException {
|
||||||
|
for (String name : names) {
|
||||||
|
Integer index = labels.get(name.toLowerCase(Locale.ROOT));
|
||||||
|
if (index != null) {
|
||||||
|
String value = rs.getString(index);
|
||||||
|
if (value != null && !value.isBlank()) {
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String firstNonBlank(String value, String fallback) {
|
||||||
|
return value == null || value.isBlank() ? fallback : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.banben.modules.synchub.reader;
|
||||||
|
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本地联调用的模拟图书。不连接陆工大、陆指或边海防的真实库。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class MockBookReader implements BookReader {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supports(String source) {
|
||||||
|
return "MOCK".equalsIgnoreCase(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> read(SyncHubProperties.Node node, String mediaType) {
|
||||||
|
List<BookDocument> all = samples(node);
|
||||||
|
if (mediaType == null || mediaType.isBlank() || "ALL".equalsIgnoreCase(mediaType)) {
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
return all.stream().filter(book -> mediaType.equals(book.getMediaType())).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BookDocument> samples(SyncHubProperties.Node node) {
|
||||||
|
String code = node.getCode() == null ? "" : node.getCode().toUpperCase();
|
||||||
|
List<BookDocument> books = new ArrayList<>();
|
||||||
|
if ("NJ_LGD".equals(code)) {
|
||||||
|
books.add(book(node, "MYSQL", "LGD-P-001", "陆军工程概要", "纸质", "9787300000001"));
|
||||||
|
books.add(book(node, "SQLSERVER", "LGD-E-001", "工程力学电子版", "电子", "9787300000002"));
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
if ("NJ_LZ".equals(code)) {
|
||||||
|
books.add(book(node, "MYSQL", "LZ-P-001", "指挥学基础", "纸质", "9787300000011"));
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
books.add(book(node, "MOCK", code + "-P-001", node.getName() + "样例图书", "纸质", "9787300000099"));
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookDocument book(SyncHubProperties.Node node, String sourceDb, String processNo, String title, String media, String isbn) {
|
||||||
|
BookDocument book = new BookDocument();
|
||||||
|
book.setNodeCode(node.getCode());
|
||||||
|
book.setSourceDb(sourceDb);
|
||||||
|
book.setProcessNo(processNo);
|
||||||
|
book.setTitle(title);
|
||||||
|
book.setAuthor("模拟作者");
|
||||||
|
book.setIsbn(isbn);
|
||||||
|
book.setPublisher("模拟出版社");
|
||||||
|
book.setPublishYear("2024");
|
||||||
|
book.setMediaType(media);
|
||||||
|
book.setLanguage("chi");
|
||||||
|
book.setSourceLibrary(node.getName());
|
||||||
|
book.setKeywords("联调");
|
||||||
|
book.setSummary("本地模拟数据,不是现场馆藏。");
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
package com.banben.modules.synchub.reader;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.service.BookCleaner;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把总库图书按陆工大测试库的表结构写回去。
|
||||||
|
* 纸质写入 book_attr,电子写入 e_book。ISBN 或题名已经存在的不再插入。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MysqlNodeWriter {
|
||||||
|
|
||||||
|
private final BookCleaner cleaner;
|
||||||
|
|
||||||
|
public WriteResult write(SyncHubProperties.Node node, List<BookDocument> books) {
|
||||||
|
if (node.getMysqlUrl() == null || node.getMysqlUrl().isBlank()) {
|
||||||
|
throw new BusinessException(node.getName() + " 还没配置 MySQL 地址");
|
||||||
|
}
|
||||||
|
String paper = table(node.getPaperTable(), "book_attr");
|
||||||
|
String ebook = table(node.getEbookTable(), "e_book");
|
||||||
|
int inserted = 0;
|
||||||
|
int skipped = 0;
|
||||||
|
try {
|
||||||
|
Class.forName("com.mysql.cj.jdbc.Driver");
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
throw new BusinessException("缺少 MySQL 驱动");
|
||||||
|
}
|
||||||
|
try (Connection connection = DriverManager.getConnection(node.getMysqlUrl(), node.getMysqlUser(), node.getMysqlPassword())) {
|
||||||
|
// 测试库的 book_attr.RECORD_ID 指向 bibliography,但 bibliography 和字典表是空的,
|
||||||
|
// 现有两条书也没有父记录。这里按现有数据的方式只写书目表。
|
||||||
|
try (Statement statement = connection.createStatement()) {
|
||||||
|
statement.execute("SET FOREIGN_KEY_CHECKS = 0");
|
||||||
|
}
|
||||||
|
long paperId = maxId(connection, paper);
|
||||||
|
long ebookId = maxId(connection, ebook);
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (BookDocument book : books) {
|
||||||
|
if (book.getTitle() == null || book.getTitle().isBlank()) {
|
||||||
|
skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!seen.add(cleaner.matchKey(book))) {
|
||||||
|
skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
boolean electronic = book.getMediaType() != null && book.getMediaType().contains("电子");
|
||||||
|
String target = electronic ? ebook : paper;
|
||||||
|
if (electronic ? existsEbook(connection, ebook, book) : existsPaper(connection, paper, book)) {
|
||||||
|
skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (electronic) {
|
||||||
|
ebookId++;
|
||||||
|
insertEbook(connection, ebook, ebookId, book);
|
||||||
|
} else {
|
||||||
|
paperId++;
|
||||||
|
insertPaper(connection, paper, paperId, book);
|
||||||
|
}
|
||||||
|
inserted++;
|
||||||
|
}
|
||||||
|
try (Statement statement = connection.createStatement()) {
|
||||||
|
statement.execute("SET FOREIGN_KEY_CHECKS = 1");
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new BusinessException("写入" + node.getName() + "失败:" + safe(e.getMessage(), node.getMysqlPassword()));
|
||||||
|
}
|
||||||
|
return new WriteResult(inserted, skipped);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertPaper(Connection connection, String table, long id, BookDocument book) throws SQLException {
|
||||||
|
String isbn13 = isbn13(book.getIsbn());
|
||||||
|
String isbn10 = isbn13.length() == 10 ? isbn13 : "";
|
||||||
|
String sql = "INSERT INTO `" + table + "` (RECORD_ID, CALL_NO, TITLE, TITLE_S, ISBN13, ISBN10, ISBN, AUTHOR, PUBLISHER, PUB_DATE, PUB_YEAR, VERSION) "
|
||||||
|
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(sql)) {
|
||||||
|
ps.setLong(1, id);
|
||||||
|
ps.setString(2, cut(book.getClcCode(), 255));
|
||||||
|
ps.setString(3, cut(book.getTitle(), 1000));
|
||||||
|
ps.setString(4, cut(first(book.getOtherTitle(), book.getTitle()), 1000));
|
||||||
|
ps.setString(5, cut(isbn13, 32));
|
||||||
|
ps.setString(6, cut(isbn10, 32));
|
||||||
|
ps.setString(7, cut(book.getIsbn(), 64));
|
||||||
|
ps.setString(8, cut(book.getAuthor(), 500));
|
||||||
|
ps.setString(9, cut(book.getPublisher(), 500));
|
||||||
|
ps.setString(10, cut(book.getPublishDate(), 32));
|
||||||
|
ps.setString(11, cut(book.getPublishYear(), 16));
|
||||||
|
ps.setString(12, cut(book.getEdition(), 100));
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertEbook(Connection connection, String table, long id, BookDocument book) throws SQLException {
|
||||||
|
String isbn13 = isbn13(book.getIsbn());
|
||||||
|
String sql = "INSERT INTO `" + table + "` (RECORD_ID, TITLE, AUTHOR, ISBN13, ISBN10, PUBLISHER, PUB_DATE, PUB_YEAR, DOC_ABSTRACT, KEYWORDS, FULLTEXT_LINK) "
|
||||||
|
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(sql)) {
|
||||||
|
ps.setLong(1, id);
|
||||||
|
ps.setString(2, cut(book.getTitle(), 1000));
|
||||||
|
ps.setString(3, cut(book.getAuthor(), 500));
|
||||||
|
ps.setString(4, cut(isbn13, 32));
|
||||||
|
ps.setString(5, isbn13.length() == 10 ? isbn13 : null);
|
||||||
|
ps.setString(6, cut(book.getPublisher(), 500));
|
||||||
|
ps.setString(7, cut(book.getPublishDate(), 32));
|
||||||
|
if (year(book.getPublishYear()) == null) {
|
||||||
|
ps.setObject(8, null);
|
||||||
|
} else {
|
||||||
|
ps.setInt(8, year(book.getPublishYear()));
|
||||||
|
}
|
||||||
|
ps.setString(9, cut(book.getSummary(), 500));
|
||||||
|
ps.setString(10, cut(book.getKeywords(), 255));
|
||||||
|
ps.setString(11, cut(book.getFulltextUrl(), 500));
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean existsPaper(Connection connection, String table, BookDocument book) throws SQLException {
|
||||||
|
String isbn = isbn13(book.getIsbn());
|
||||||
|
if (!isbn.isEmpty()) {
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(
|
||||||
|
"SELECT 1 FROM `" + table + "` WHERE ISBN13 = ? OR ISBN = ? OR ISBN10 = ? LIMIT 1")) {
|
||||||
|
ps.setString(1, isbn);
|
||||||
|
ps.setString(2, book.getIsbn());
|
||||||
|
ps.setString(3, isbn);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return existsByTitle(connection, table, book);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean existsEbook(Connection connection, String table, BookDocument book) throws SQLException {
|
||||||
|
String isbn = isbn13(book.getIsbn());
|
||||||
|
if (!isbn.isEmpty()) {
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(
|
||||||
|
"SELECT 1 FROM `" + table + "` WHERE ISBN13 = ? OR ISBN10 = ? OR EISBN = ? LIMIT 1")) {
|
||||||
|
ps.setString(1, isbn);
|
||||||
|
ps.setString(2, isbn);
|
||||||
|
ps.setString(3, isbn);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return existsByTitle(connection, table, book);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean existsByTitle(Connection connection, String table, BookDocument book) throws SQLException {
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(
|
||||||
|
"SELECT 1 FROM `" + table + "` WHERE TITLE = ? AND IFNULL(AUTHOR,'') = ? LIMIT 1")) {
|
||||||
|
ps.setString(1, book.getTitle());
|
||||||
|
ps.setString(2, book.getAuthor() == null ? "" : book.getAuthor());
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
return rs.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long maxId(Connection connection, String table) throws SQLException {
|
||||||
|
try (Statement statement = connection.createStatement();
|
||||||
|
ResultSet rs = statement.executeQuery("SELECT IFNULL(MAX(RECORD_ID), 0) FROM `" + table + "`")) {
|
||||||
|
rs.next();
|
||||||
|
return rs.getLong(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String table(String name, String fallback) {
|
||||||
|
String table = name == null || name.isBlank() ? fallback : name.trim();
|
||||||
|
if (!table.matches("[A-Za-z0-9_]+")) {
|
||||||
|
throw new BusinessException("图书表名不正确");
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String isbn13(String isbn) {
|
||||||
|
if (isbn == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
for (int i = 0; i < isbn.length(); i++) {
|
||||||
|
char c = isbn.charAt(i);
|
||||||
|
if (c >= '0' && c <= '9') {
|
||||||
|
out.append(c);
|
||||||
|
} else if (c == 'X' || c == 'x') {
|
||||||
|
out.append('x');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer year(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
StringBuilder digits = new StringBuilder();
|
||||||
|
for (int i = 0; i < value.length() && digits.length() < 4; i++) {
|
||||||
|
char c = value.charAt(i);
|
||||||
|
if (c >= '0' && c <= '9') {
|
||||||
|
digits.append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (digits.length() != 4) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Integer.parseInt(digits.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String first(String value, String fallback) {
|
||||||
|
return value == null || value.isBlank() ? fallback : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String cut(String value, int max) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String text = value.trim();
|
||||||
|
return text.length() <= max ? text : text.substring(0, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String safe(String message, String password) {
|
||||||
|
if (message == null) {
|
||||||
|
return "写入失败";
|
||||||
|
}
|
||||||
|
if (password != null && !password.isBlank()) {
|
||||||
|
return message.replace(password, "******");
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** inserted 是新写入条数,skipped 是测试库里已经有、跳过的条数。 */
|
||||||
|
public record WriteResult(int inserted, int skipped) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package com.banben.modules.synchub.service;
|
||||||
|
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图书比对。节点推上来的书和总库比,推送库再和总库比,重复的留下,没有的才入库。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BookCleaner {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从待入库列表里去掉已经有的书。
|
||||||
|
* 有 ISBN 时按 ISBN 判断;没有 ISBN 时按题名、作者、出版年一起判断。
|
||||||
|
* 同一批里相同的书也只留第一条。
|
||||||
|
*/
|
||||||
|
public List<BookDocument> clean(List<BookDocument> incoming, Collection<String> heldKeys) {
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
if (heldKeys != null) {
|
||||||
|
seen.addAll(heldKeys);
|
||||||
|
}
|
||||||
|
List<BookDocument> fresh = new ArrayList<>();
|
||||||
|
if (incoming == null) {
|
||||||
|
return fresh;
|
||||||
|
}
|
||||||
|
for (BookDocument book : incoming) {
|
||||||
|
tidy(book);
|
||||||
|
if (seen.add(matchKey(book))) {
|
||||||
|
fresh.add(book);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fresh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 同一本书用同一个比对键,不看它来自哪个节点。 */
|
||||||
|
public String matchKey(BookDocument book) {
|
||||||
|
String isbn = digits(book == null ? null : book.getIsbn());
|
||||||
|
if (!isbn.isEmpty()) {
|
||||||
|
return cut("isbn:" + isbn);
|
||||||
|
}
|
||||||
|
String title = norm(book == null ? null : book.getTitle());
|
||||||
|
String author = norm(book == null ? null : book.getAuthor());
|
||||||
|
String year = norm(book == null ? null : book.getPublishYear());
|
||||||
|
return cut("meta:" + title + "|" + author + "|" + year);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> keysOf(List<BookDocument> books) {
|
||||||
|
Set<String> keys = new HashSet<>();
|
||||||
|
if (books == null) {
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
for (BookDocument book : books) {
|
||||||
|
keys.add(matchKey(book));
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void tidy(BookDocument book) {
|
||||||
|
if (book == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (book.getTitle() != null) {
|
||||||
|
book.setTitle(book.getTitle().trim());
|
||||||
|
}
|
||||||
|
if (book.getIsbn() != null) {
|
||||||
|
book.setIsbn(book.getIsbn().trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String digits(String isbn) {
|
||||||
|
if (isbn == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
for (int i = 0; i < isbn.length(); i++) {
|
||||||
|
char c = isbn.charAt(i);
|
||||||
|
if (c >= '0' && c <= '9') {
|
||||||
|
out.append(c);
|
||||||
|
} else if (c == 'X' || c == 'x') {
|
||||||
|
out.append('x');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String norm(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return value.trim().replaceAll("\\s+", "").toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String cut(String key) {
|
||||||
|
return key.length() <= 300 ? key : key.substring(0, 300);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
package com.banben.modules.synchub.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.synchub.config.HubTokenInterceptor;
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.entity.SyncHubRecord;
|
||||||
|
import com.banben.modules.synchub.mapper.SyncHubRecordMapper;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.reader.JdbcRemoteBookReader;
|
||||||
|
import com.banben.modules.synchub.reader.MockBookReader;
|
||||||
|
import com.banben.modules.synchub.reader.MysqlNodeWriter;
|
||||||
|
import com.banben.modules.synchub.store.BookStore;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分支节点把图书推到南昌总库。总库只收新书,再把总库里该节点还没有的书补回去。
|
||||||
|
* 数据量大时按 batch-size 分批,不一次传输全库。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SyncHubService {
|
||||||
|
|
||||||
|
public static final String CENTER = "CENTER";
|
||||||
|
public static final String UP = "UP";
|
||||||
|
public static final String DOWN = "DOWN";
|
||||||
|
|
||||||
|
private final SyncHubProperties properties;
|
||||||
|
private final BookCleaner cleaner;
|
||||||
|
private final BookStore bookStore;
|
||||||
|
private final MockBookReader mockBookReader;
|
||||||
|
private final JdbcRemoteBookReader remoteBookReader;
|
||||||
|
private final MysqlNodeWriter mysqlNodeWriter;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final SyncHubRecordMapper recordMapper;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
|
||||||
|
|
||||||
|
/** 节点读取一页本地图书,推到总库。返回的 nextOffset 有值时,用它继续取下一页。 */
|
||||||
|
public SyncHubRecord pushFromNode(String nodeCode, String source, String mediaType, int offset, Integer limit) {
|
||||||
|
SyncHubProperties.Node node = requireNode(nodeCode);
|
||||||
|
int size = limit == null || limit < 1 ? properties.pageSize() : Math.min(limit, 1000);
|
||||||
|
int start = Math.max(offset, 0);
|
||||||
|
SyncHubRecord record = open(UP, node.getCode(), "NC_CENTER", source);
|
||||||
|
try {
|
||||||
|
JdbcRemoteBookReader.Page page = readPage(node, source, mediaType, start, size);
|
||||||
|
if (page.books().isEmpty()) {
|
||||||
|
if (start == 0) {
|
||||||
|
throw new BusinessException("没有图书数据");
|
||||||
|
}
|
||||||
|
record.setBookCount(0);
|
||||||
|
record.setSkipCount(0);
|
||||||
|
succeed(record);
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
List<BookDocument> books = prepare(page.books(), node.getCode(), source);
|
||||||
|
JsonNode data = post(join(properties.getCenterUrl(), "/api/hub/center/receive"), new ReceiveBody(node.getCode(), source, books));
|
||||||
|
record.setBookCount(data.path("bookCount").asInt(0));
|
||||||
|
record.setSkipCount(data.path("skipCount").asInt(0));
|
||||||
|
if (page.more()) {
|
||||||
|
record.setNextOffset(start + size);
|
||||||
|
}
|
||||||
|
succeed(record);
|
||||||
|
return record;
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(record, e);
|
||||||
|
throw new BusinessException(record.getErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 总库收到节点推来的图书。和总库已有书比对,重复的不入库,新的才入库,然后给还缺书的节点补回。 */
|
||||||
|
public SyncHubRecord receiveAtCenter(String nodeCode, String sourceDb, List<BookDocument> books) {
|
||||||
|
SyncHubRecord record = open(UP, nodeCode, "NC_CENTER", sourceDb);
|
||||||
|
try {
|
||||||
|
List<BookDocument> prepared = prepare(books, nodeCode, sourceDb);
|
||||||
|
guardSize(prepared);
|
||||||
|
List<BookDocument> fresh = cleaner.clean(prepared, bookStore.existingKeys(CENTER, cleaner.keysOf(prepared)));
|
||||||
|
int inserted = fresh.isEmpty() ? 0 : bookStore.saveNew(CENTER, fresh);
|
||||||
|
record.setBookCount(inserted);
|
||||||
|
record.setSkipCount(prepared.size() - inserted);
|
||||||
|
succeed(record);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(record, e);
|
||||||
|
throw new BusinessException(record.getErrorMessage());
|
||||||
|
}
|
||||||
|
if (properties.isAutoDispatch()) {
|
||||||
|
dispatchAll();
|
||||||
|
}
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 总库把各节点还没有的书补过去。一次最多回传 20 批,没传完就再调一次。 */
|
||||||
|
public List<SyncHubRecord> dispatchAll() {
|
||||||
|
List<SyncHubRecord> records = new ArrayList<>();
|
||||||
|
for (SyncHubProperties.Node node : properties.getNodes()) {
|
||||||
|
SyncHubRecord record = dispatchMissing(node);
|
||||||
|
if (record != null) {
|
||||||
|
records.add(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 节点收下总库补来的书。节点里已经有的不再写入,也不再往总库推。 */
|
||||||
|
public SyncHubRecord receiveAtNode(String nodeCode, List<BookDocument> books) {
|
||||||
|
SyncHubProperties.Node node = requireNode(nodeCode);
|
||||||
|
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "CENTER");
|
||||||
|
try {
|
||||||
|
List<BookDocument> prepared = prepare(books, null, null);
|
||||||
|
guardSize(prepared);
|
||||||
|
List<BookDocument> fresh = cleaner.clean(prepared, bookStore.existingKeys(node.getCode(), cleaner.keysOf(prepared)));
|
||||||
|
int inserted = fresh.isEmpty() ? 0 : bookStore.saveNew(node.getCode(), fresh);
|
||||||
|
record.setBookCount(inserted);
|
||||||
|
record.setSkipCount(prepared.size() - inserted);
|
||||||
|
succeed(record);
|
||||||
|
return record;
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(record, e);
|
||||||
|
throw new BusinessException(record.getErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookDocument> mockBooks(String nodeCode, String mediaType) {
|
||||||
|
return mockBookReader.read(requireNode(nodeCode), mediaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookDocument> listBooks(String holder, int limit) {
|
||||||
|
String code = holder == null || holder.isBlank() ? CENTER : holder.trim();
|
||||||
|
if (!CENTER.equalsIgnoreCase(code) && properties.find(code) == null) {
|
||||||
|
throw new BusinessException("未知节点:" + code);
|
||||||
|
}
|
||||||
|
int size = limit <= 0 ? 20 : Math.min(limit, 100);
|
||||||
|
return bookStore.findAll(code, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<SyncHubRecord> listRecords(int limit) {
|
||||||
|
int size = limit <= 0 ? 50 : Math.min(limit, 200);
|
||||||
|
return recordMapper.selectList(new LambdaQueryWrapper<SyncHubRecord>()
|
||||||
|
.orderByDesc(SyncHubRecord::getId)
|
||||||
|
.last("LIMIT " + size));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 失败记录再跑一次。上推会重新读取,回传会重新读取总库已保存的数据。 */
|
||||||
|
public SyncHubRecord retry(Long id) {
|
||||||
|
SyncHubRecord record = recordMapper.selectById(id);
|
||||||
|
if (record == null) {
|
||||||
|
throw new BusinessException("同步记录不存在");
|
||||||
|
}
|
||||||
|
if ("SUCCESS".equals(record.getStatus())) {
|
||||||
|
throw new BusinessException("这条记录已经成功");
|
||||||
|
}
|
||||||
|
int used = record.getRetryCount() == null ? 0 : record.getRetryCount();
|
||||||
|
int max = record.getMaxRetry() == null ? properties.getRetryMax() : record.getMaxRetry();
|
||||||
|
if (used >= max) {
|
||||||
|
throw new BusinessException("已达到重试次数");
|
||||||
|
}
|
||||||
|
record.setRetryCount(used + 1);
|
||||||
|
record.setStatus("RUNNING");
|
||||||
|
record.setErrorMessage(null);
|
||||||
|
record.setStartTime(LocalDateTime.now());
|
||||||
|
recordMapper.updateById(record);
|
||||||
|
try {
|
||||||
|
if (UP.equals(record.getDirection())) {
|
||||||
|
SyncHubProperties.Node node = requireNode(record.getSourceNode());
|
||||||
|
JdbcRemoteBookReader.Page page = readPage(node, record.getSourceDb(), null, 0, properties.pageSize());
|
||||||
|
if (page.books().isEmpty()) {
|
||||||
|
throw new BusinessException("没有图书数据");
|
||||||
|
}
|
||||||
|
List<BookDocument> books = prepare(page.books(), node.getCode(), record.getSourceDb());
|
||||||
|
JsonNode data = post(join(properties.getCenterUrl(), "/api/hub/center/receive"), new ReceiveBody(node.getCode(), record.getSourceDb(), books));
|
||||||
|
record.setBookCount(data.path("bookCount").asInt(0));
|
||||||
|
record.setSkipCount(data.path("skipCount").asInt(0));
|
||||||
|
} else {
|
||||||
|
SyncHubProperties.Node node = requireNode(record.getTargetNode());
|
||||||
|
if (node.getMysqlUrl() != null && !node.getMysqlUrl().isBlank()) {
|
||||||
|
List<BookDocument> page = readVersionResource(loadCursor(node.getCode()), properties.pageSize());
|
||||||
|
if (!page.isEmpty()) {
|
||||||
|
MysqlNodeWriter.WriteResult result = mysqlNodeWriter.write(node, page);
|
||||||
|
saveCursor(node.getCode(), page.get(page.size() - 1).getResourceId());
|
||||||
|
record.setBookCount(result.inserted());
|
||||||
|
record.setSkipCount(result.skipped());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
List<BookDocument> books = bookStore.findMissing(CENTER, node.getCode(), properties.pageSize());
|
||||||
|
if (!books.isEmpty()) {
|
||||||
|
post(join(node.getCallbackUrl(), "/api/hub/node/receive"), new DeliverBody(node.getCode(), books));
|
||||||
|
}
|
||||||
|
record.setBookCount(books.size());
|
||||||
|
record.setSkipCount(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
succeed(record);
|
||||||
|
return record;
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(record, e);
|
||||||
|
throw new BusinessException(record.getErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void retryQuiet(Long id) {
|
||||||
|
try {
|
||||||
|
retry(id);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("同步重试未成功:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配了 MySQL 的节点,从 version_resource 按批写成对方的书目表。
|
||||||
|
* 没配 MySQL 的节点,仍把缺的书送到对方的接收接口。
|
||||||
|
*/
|
||||||
|
private SyncHubRecord dispatchMissing(SyncHubProperties.Node node) {
|
||||||
|
if (node.getMysqlUrl() != null && !node.getMysqlUrl().isBlank()) {
|
||||||
|
return dispatchToMysql(node);
|
||||||
|
}
|
||||||
|
int size = properties.pageSize();
|
||||||
|
List<BookDocument> missing = bookStore.findMissing(CENTER, node.getCode(), size);
|
||||||
|
if (missing.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "CENTER");
|
||||||
|
int sent = 0;
|
||||||
|
int pages = 0;
|
||||||
|
boolean more = false;
|
||||||
|
try {
|
||||||
|
while (!missing.isEmpty()) {
|
||||||
|
post(join(node.getCallbackUrl(), "/api/hub/node/receive"), new DeliverBody(node.getCode(), missing));
|
||||||
|
sent += missing.size();
|
||||||
|
pages++;
|
||||||
|
if (missing.size() < size) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (pages >= 20) {
|
||||||
|
more = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
missing = bookStore.findMissing(CENTER, node.getCode(), size);
|
||||||
|
}
|
||||||
|
record.setBookCount(sent);
|
||||||
|
record.setSkipCount(0);
|
||||||
|
if (more) {
|
||||||
|
record.setErrorMessage("还有未回传的数据,请再调用一次回传接口");
|
||||||
|
}
|
||||||
|
succeed(record);
|
||||||
|
} catch (Exception e) {
|
||||||
|
record.setBookCount(sent);
|
||||||
|
fail(record, e);
|
||||||
|
}
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SyncHubRecord dispatchToMysql(SyncHubProperties.Node node) {
|
||||||
|
long cursor = loadCursor(node.getCode());
|
||||||
|
int size = properties.pageSize();
|
||||||
|
int inserted = 0;
|
||||||
|
int skipped = 0;
|
||||||
|
boolean more = false;
|
||||||
|
try {
|
||||||
|
int pages = 0;
|
||||||
|
while (pages < 20 && inserted < size) {
|
||||||
|
List<BookDocument> page = readVersionResource(cursor, size);
|
||||||
|
if (page.isEmpty()) {
|
||||||
|
more = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
MysqlNodeWriter.WriteResult result = mysqlNodeWriter.write(node, page);
|
||||||
|
inserted += result.inserted();
|
||||||
|
skipped += result.skipped();
|
||||||
|
cursor = page.get(page.size() - 1).getResourceId();
|
||||||
|
saveCursor(node.getCode(), cursor);
|
||||||
|
pages++;
|
||||||
|
more = page.size() == size;
|
||||||
|
if (!more) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inserted == 0 && skipped == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "VERSION_RESOURCE");
|
||||||
|
record.setBookCount(inserted);
|
||||||
|
record.setSkipCount(skipped);
|
||||||
|
if (more) {
|
||||||
|
record.setErrorMessage("version_resource 后面还有,请再调用一次回传");
|
||||||
|
}
|
||||||
|
succeed(record);
|
||||||
|
return record;
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
SyncHubRecord record = open(DOWN, "NC_CENTER", node.getCode(), "VERSION_RESOURCE");
|
||||||
|
record.setBookCount(inserted);
|
||||||
|
record.setSkipCount(skipped);
|
||||||
|
fail(record, e);
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从总库 version_resource 取 id 大于 afterId 的一页,不改这张表。 */
|
||||||
|
private List<BookDocument> readVersionResource(long afterId, int limit) {
|
||||||
|
return jdbcTemplate.query(
|
||||||
|
"SELECT id, process_no, title, other_title, author, isbn, publisher, publish_year, publish_date, "
|
||||||
|
+ "clc_code, edition, keywords, summary, media_type, fulltext_url "
|
||||||
|
+ "FROM version_resource WHERE deleted = 0 AND id > ? AND title IS NOT NULL AND title <> '' "
|
||||||
|
+ "ORDER BY id LIMIT ?",
|
||||||
|
(rs, rowNum) -> {
|
||||||
|
BookDocument book = new BookDocument();
|
||||||
|
book.setResourceId(rs.getLong("id"));
|
||||||
|
book.setProcessNo(rs.getString("process_no"));
|
||||||
|
book.setTitle(rs.getString("title"));
|
||||||
|
book.setOtherTitle(rs.getString("other_title"));
|
||||||
|
book.setAuthor(rs.getString("author"));
|
||||||
|
book.setIsbn(rs.getString("isbn"));
|
||||||
|
book.setPublisher(rs.getString("publisher"));
|
||||||
|
book.setPublishYear(rs.getString("publish_year"));
|
||||||
|
book.setPublishDate(rs.getString("publish_date"));
|
||||||
|
book.setClcCode(rs.getString("clc_code"));
|
||||||
|
book.setEdition(rs.getString("edition"));
|
||||||
|
book.setKeywords(rs.getString("keywords"));
|
||||||
|
book.setSummary(rs.getString("summary"));
|
||||||
|
book.setMediaType(rs.getString("media_type"));
|
||||||
|
book.setFulltextUrl(rs.getString("fulltext_url"));
|
||||||
|
book.setSourceDb("VERSION_RESOURCE");
|
||||||
|
book.setNodeCode("NC_CENTER");
|
||||||
|
return book;
|
||||||
|
},
|
||||||
|
afterId, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long loadCursor(String nodeCode) {
|
||||||
|
List<Long> ids = jdbcTemplate.query(
|
||||||
|
"SELECT last_resource_id FROM sync_hub_cursor WHERE node_code = ?",
|
||||||
|
(rs, rowNum) -> rs.getLong(1), nodeCode);
|
||||||
|
return ids.isEmpty() ? 0L : ids.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveCursor(String nodeCode, long resourceId) {
|
||||||
|
jdbcTemplate.update(
|
||||||
|
"INSERT INTO sync_hub_cursor (node_code, last_resource_id, update_time) VALUES (?,?, CURRENT_TIMESTAMP) "
|
||||||
|
+ "ON CONFLICT (node_code) DO UPDATE SET last_resource_id = EXCLUDED.last_resource_id, update_time = CURRENT_TIMESTAMP",
|
||||||
|
nodeCode, resourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JdbcRemoteBookReader.Page readPage(SyncHubProperties.Node node, String source, String mediaType, int offset, int limit) {
|
||||||
|
if (source == null || source.isBlank() || "MOCK".equalsIgnoreCase(source)) {
|
||||||
|
List<BookDocument> all = new ArrayList<>(mockBookReader.read(node, mediaType));
|
||||||
|
if (offset >= all.size()) {
|
||||||
|
return new JdbcRemoteBookReader.Page(List.of(), false);
|
||||||
|
}
|
||||||
|
int end = Math.min(offset + limit, all.size());
|
||||||
|
return new JdbcRemoteBookReader.Page(new ArrayList<>(all.subList(offset, end)), end < all.size());
|
||||||
|
}
|
||||||
|
if (remoteBookReader.supports(source)) {
|
||||||
|
return remoteBookReader.readPage(node, source, mediaType, offset, limit);
|
||||||
|
}
|
||||||
|
throw new BusinessException("不支持的来源:" + source);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BookDocument> prepare(List<BookDocument> books, String nodeCode, String sourceDb) {
|
||||||
|
if (books == null || books.isEmpty()) {
|
||||||
|
throw new BusinessException("没有图书数据");
|
||||||
|
}
|
||||||
|
for (BookDocument book : books) {
|
||||||
|
if (nodeCode != null && (book.getNodeCode() == null || book.getNodeCode().isBlank())) {
|
||||||
|
book.setNodeCode(nodeCode);
|
||||||
|
}
|
||||||
|
if (sourceDb != null && (book.getSourceDb() == null || book.getSourceDb().isBlank())) {
|
||||||
|
book.setSourceDb(sourceDb);
|
||||||
|
}
|
||||||
|
if (book.getTitle() == null || book.getTitle().isBlank()) {
|
||||||
|
throw new BusinessException("图书缺少题名");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void guardSize(List<BookDocument> books) {
|
||||||
|
if (books.size() > 1000) {
|
||||||
|
throw new BusinessException("单次最多接收 1000 条。数据量大时请按 offset 分批推送,每批不超过 " + properties.pageSize() + " 条");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode post(String url, Object body) throws Exception {
|
||||||
|
String json = objectMapper.writeValueAsString(body);
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
|
.timeout(Duration.ofSeconds(30))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header(HubTokenInterceptor.HEADER, properties.getToken() == null ? "" : properties.getToken())
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
if (response.statusCode() != 200) {
|
||||||
|
throw new BusinessException("对方返回 " + response.statusCode());
|
||||||
|
}
|
||||||
|
JsonNode root = objectMapper.readTree(response.body());
|
||||||
|
if (root.path("code").asInt() != 200) {
|
||||||
|
String message = root.path("message").asText("同步失败");
|
||||||
|
throw new BusinessException(message);
|
||||||
|
}
|
||||||
|
return root.path("data");
|
||||||
|
}
|
||||||
|
|
||||||
|
private SyncHubProperties.Node requireNode(String code) {
|
||||||
|
SyncHubProperties.Node node = properties.find(code);
|
||||||
|
if (node == null) {
|
||||||
|
throw new BusinessException("未知节点:" + code);
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SyncHubRecord open(String direction, String sourceNode, String targetNode, String sourceDb) {
|
||||||
|
SyncHubRecord record = new SyncHubRecord();
|
||||||
|
record.setTaskNo(UUID.randomUUID().toString().replace("-", ""));
|
||||||
|
record.setDirection(direction);
|
||||||
|
record.setSourceNode(sourceNode);
|
||||||
|
record.setTargetNode(targetNode);
|
||||||
|
record.setSourceDb(sourceDb);
|
||||||
|
record.setBookCount(0);
|
||||||
|
record.setSkipCount(0);
|
||||||
|
record.setStatus("RUNNING");
|
||||||
|
record.setRetryCount(0);
|
||||||
|
record.setMaxRetry(properties.getRetryMax());
|
||||||
|
record.setStartTime(LocalDateTime.now());
|
||||||
|
record.setCreateTime(LocalDateTime.now());
|
||||||
|
recordMapper.insert(record);
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void succeed(SyncHubRecord record) {
|
||||||
|
record.setStatus("SUCCESS");
|
||||||
|
if (record.getErrorMessage() == null || record.getErrorMessage().isBlank()) {
|
||||||
|
record.setErrorMessage("");
|
||||||
|
}
|
||||||
|
record.setEndTime(LocalDateTime.now());
|
||||||
|
recordMapper.updateById(record);
|
||||||
|
log.info("图书同步成功 {} {} -> {} 共 {} 条", record.getTaskNo(), record.getSourceNode(), record.getTargetNode(), record.getBookCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(SyncHubRecord record, Exception e) {
|
||||||
|
String message = e.getMessage() == null ? "同步失败" : e.getMessage();
|
||||||
|
if (message.length() > 1000) {
|
||||||
|
message = message.substring(0, 1000);
|
||||||
|
}
|
||||||
|
record.setStatus("FAILED");
|
||||||
|
record.setErrorMessage(message);
|
||||||
|
record.setEndTime(LocalDateTime.now());
|
||||||
|
recordMapper.updateById(record);
|
||||||
|
log.warn("图书同步失败 {}:{}", record.getTaskNo(), message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String join(String base, String path) {
|
||||||
|
String root = base == null ? "" : base.trim();
|
||||||
|
if (root.endsWith("/")) {
|
||||||
|
root = root.substring(0, root.length() - 1);
|
||||||
|
}
|
||||||
|
return root + path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 节点推给总库的报文,对应 POST /api/hub/center/receive。
|
||||||
|
*
|
||||||
|
* @param nodeCode 发出数据的节点编码,如 NJ_LGD
|
||||||
|
* @param sourceDb 这批书从哪类库读出:MOCK、MYSQL、SQLSERVER
|
||||||
|
* @param books 这一页图书。单次最多 1000 条
|
||||||
|
*/
|
||||||
|
public record ReceiveBody(String nodeCode, String sourceDb, List<BookDocument> books) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 总库补回给节点的报文,对应 POST /api/hub/node/receive。
|
||||||
|
*
|
||||||
|
* @param nodeCode 收下这批书的节点编码
|
||||||
|
* @param books 总库有、该节点还没有的书
|
||||||
|
*/
|
||||||
|
public record DeliverBody(String nodeCode, List<BookDocument> books) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.banben.modules.synchub.store;
|
||||||
|
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图书汇总的存放位置。总库用 holder=CENTER,节点收到回传后用自己的节点编码。
|
||||||
|
*/
|
||||||
|
public interface BookStore {
|
||||||
|
|
||||||
|
/** 只插入还没有的书,返回真正新增的条数。已有的不覆盖。 */
|
||||||
|
int saveNew(String holder, List<BookDocument> books);
|
||||||
|
|
||||||
|
/** 这批比对键里,库中已经存在的那些。 */
|
||||||
|
Set<String> existingKeys(String holder, Collection<String> keys);
|
||||||
|
|
||||||
|
/** 源库有、目标库没有的书,一次最多返回 limit 条。 */
|
||||||
|
List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit);
|
||||||
|
|
||||||
|
List<BookDocument> findAll(String holder, int limit);
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
package com.banben.modules.synchub.store;
|
||||||
|
|
||||||
|
import co.elastic.clients.elasticsearch.ElasticsearchClient;
|
||||||
|
import co.elastic.clients.elasticsearch._types.FieldValue;
|
||||||
|
import co.elastic.clients.elasticsearch._types.SortOrder;
|
||||||
|
import co.elastic.clients.elasticsearch.core.BulkResponse;
|
||||||
|
import co.elastic.clients.elasticsearch.core.MgetResponse;
|
||||||
|
import co.elastic.clients.elasticsearch.core.SearchResponse;
|
||||||
|
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
|
||||||
|
import co.elastic.clients.elasticsearch.core.mget.MultiGetResponseItem;
|
||||||
|
import co.elastic.clients.elasticsearch.core.search.Hit;
|
||||||
|
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
|
||||||
|
import co.elastic.clients.transport.rest_client.RestClientTransport;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.synchub.config.SyncHubProperties;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.service.BookCleaner;
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
import org.apache.http.HttpHost;
|
||||||
|
import org.elasticsearch.client.RestClient;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 南昌总库的 Elasticsearch 写入和读取。文档编号用比对键,已存在的不覆盖。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "sync-hub.store", havingValue = "es")
|
||||||
|
public class EsBookStore implements BookStore {
|
||||||
|
|
||||||
|
private final SyncHubProperties properties;
|
||||||
|
private final BookCleaner cleaner;
|
||||||
|
private final RestClient restClient;
|
||||||
|
private final ElasticsearchClient client;
|
||||||
|
|
||||||
|
public EsBookStore(SyncHubProperties properties, BookCleaner cleaner) {
|
||||||
|
this.properties = properties;
|
||||||
|
this.cleaner = cleaner;
|
||||||
|
this.restClient = RestClient.builder(HttpHost.create(properties.getEsUris())).build();
|
||||||
|
this.client = new ElasticsearchClient(new RestClientTransport(restClient, new JacksonJsonpMapper()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int saveNew(String holder, List<BookDocument> books) {
|
||||||
|
if (books == null || books.isEmpty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
ensureIndex(holder);
|
||||||
|
List<BulkOperation> operations = new ArrayList<>();
|
||||||
|
for (BookDocument book : books) {
|
||||||
|
String key = cleaner.matchKey(book);
|
||||||
|
operations.add(BulkOperation.of(op -> op.create(c -> c.index(index(holder)).id(key).document(book))));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
BulkResponse response = client.bulk(b -> b.operations(operations));
|
||||||
|
int inserted = 0;
|
||||||
|
for (var item : response.items()) {
|
||||||
|
if (item.error() == null) {
|
||||||
|
inserted++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inserted;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("写入 Elasticsearch 失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<String> existingKeys(String holder, Collection<String> keys) {
|
||||||
|
Set<String> found = new HashSet<>();
|
||||||
|
if (keys == null || keys.isEmpty()) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
ensureIndex(holder);
|
||||||
|
try {
|
||||||
|
MgetResponse<BookDocument> response = client.mget(m -> m.index(index(holder)).ids(new ArrayList<>(keys)), BookDocument.class);
|
||||||
|
for (MultiGetResponseItem<BookDocument> item : response.docs()) {
|
||||||
|
if (item.isResult() && item.result().found()) {
|
||||||
|
found.add(item.result().id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit) {
|
||||||
|
ensureIndex(sourceHolder);
|
||||||
|
ensureIndex(targetHolder);
|
||||||
|
List<BookDocument> missing = new ArrayList<>();
|
||||||
|
List<FieldValue> searchAfter = null;
|
||||||
|
try {
|
||||||
|
while (missing.size() < limit) {
|
||||||
|
List<FieldValue> after = searchAfter;
|
||||||
|
SearchResponse<BookDocument> response = client.search(s -> {
|
||||||
|
s.index(index(sourceHolder)).size(limit).sort(o -> o.field(f -> f.field("_doc").order(SortOrder.Asc)));
|
||||||
|
if (after != null) {
|
||||||
|
s.searchAfter(after);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}, BookDocument.class);
|
||||||
|
List<Hit<BookDocument>> hits = response.hits().hits();
|
||||||
|
if (hits.isEmpty()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
List<String> ids = new ArrayList<>();
|
||||||
|
for (Hit<BookDocument> hit : hits) {
|
||||||
|
ids.add(hit.id());
|
||||||
|
}
|
||||||
|
Set<String> held = existingKeys(targetHolder, ids);
|
||||||
|
for (Hit<BookDocument> hit : hits) {
|
||||||
|
if (hit.source() != null && !held.contains(hit.id()) && missing.size() < limit) {
|
||||||
|
missing.add(hit.source());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
searchAfter = hits.get(hits.size() - 1).sort();
|
||||||
|
if (hits.size() < limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return missing;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> findAll(String holder, int limit) {
|
||||||
|
ensureIndex(holder);
|
||||||
|
try {
|
||||||
|
SearchResponse<BookDocument> response = client.search(s -> s.index(index(holder)).size(limit), BookDocument.class);
|
||||||
|
List<BookDocument> books = new ArrayList<>();
|
||||||
|
for (Hit<BookDocument> hit : response.hits().hits()) {
|
||||||
|
if (hit.source() != null) {
|
||||||
|
books.add(hit.source());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return books;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("读取 Elasticsearch 失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureIndex(String holder) {
|
||||||
|
String name = index(holder);
|
||||||
|
try {
|
||||||
|
boolean exists = client.indices().exists(e -> e.index(name)).value();
|
||||||
|
if (!exists) {
|
||||||
|
client.indices().create(c -> c.index(name));
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("Elasticsearch 索引不可用:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 总库和各节点回传箱用不同索引后缀,避免汇总数据和节点收件混在一起。 */
|
||||||
|
private String index(String holder) {
|
||||||
|
String base = properties.getEsIndex();
|
||||||
|
if (holder == null || "CENTER".equalsIgnoreCase(holder)) {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
return base + "_" + holder.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void close() throws IOException {
|
||||||
|
restClient.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package com.banben.modules.synchub.store;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.synchub.model.BookDocument;
|
||||||
|
import com.banben.modules.synchub.service.BookCleaner;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本机没有 Elasticsearch 时,用业务库里的独立表暂存。不写入 version_resource。
|
||||||
|
* 重复图书按比对键跳过,不覆盖已有记录。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@ConditionalOnProperty(name = "sync-hub.store", havingValue = "jdbc")
|
||||||
|
public class JdbcBookStore implements BookStore {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final BookCleaner cleaner;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int saveNew(String holder, List<BookDocument> books) {
|
||||||
|
String sql = "INSERT INTO sync_hub_book (holder, doc_id, match_key, node_code, source_db, process_no, title, media_type, payload, update_time) "
|
||||||
|
+ "VALUES (?,?,?,?,?,?,?,?,?, CURRENT_TIMESTAMP) "
|
||||||
|
+ "ON CONFLICT (holder, doc_id) DO NOTHING";
|
||||||
|
int inserted = 0;
|
||||||
|
for (BookDocument book : books) {
|
||||||
|
String key = cleaner.matchKey(book);
|
||||||
|
inserted += jdbcTemplate.update(sql, holder, key, key, book.getNodeCode(), book.getSourceDb(),
|
||||||
|
book.getProcessNo(), book.getTitle(), book.getMediaType(), toJson(book));
|
||||||
|
}
|
||||||
|
return inserted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<String> existingKeys(String holder, Collection<String> keys) {
|
||||||
|
Set<String> found = new HashSet<>();
|
||||||
|
if (keys == null || keys.isEmpty()) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
List<String> list = new ArrayList<>(new LinkedHashSet<>(keys));
|
||||||
|
for (int from = 0; from < list.size(); from += 200) {
|
||||||
|
List<String> part = list.subList(from, Math.min(from + 200, list.size()));
|
||||||
|
StringBuilder marks = new StringBuilder();
|
||||||
|
Object[] args = new Object[part.size() + 1];
|
||||||
|
args[0] = holder;
|
||||||
|
for (int i = 0; i < part.size(); i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
marks.append(',');
|
||||||
|
}
|
||||||
|
marks.append('?');
|
||||||
|
args[i + 1] = part.get(i);
|
||||||
|
}
|
||||||
|
found.addAll(jdbcTemplate.query(
|
||||||
|
"SELECT match_key FROM sync_hub_book WHERE holder = ? AND match_key IN (" + marks + ")",
|
||||||
|
(rs, rowNum) -> rs.getString(1),
|
||||||
|
args));
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> findMissing(String sourceHolder, String targetHolder, int limit) {
|
||||||
|
return jdbcTemplate.query(
|
||||||
|
"SELECT c.payload FROM sync_hub_book c "
|
||||||
|
+ "WHERE c.holder = ? AND c.match_key IS NOT NULL AND NOT EXISTS ("
|
||||||
|
+ "SELECT 1 FROM sync_hub_book n WHERE n.holder = ? AND n.match_key = c.match_key) "
|
||||||
|
+ "ORDER BY c.id LIMIT ?",
|
||||||
|
(rs, rowNum) -> fromJson(rs.getString(1)),
|
||||||
|
sourceHolder, targetHolder, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<BookDocument> findAll(String holder, int limit) {
|
||||||
|
return jdbcTemplate.query(
|
||||||
|
"SELECT payload FROM sync_hub_book WHERE holder = ? ORDER BY id LIMIT ?",
|
||||||
|
(rs, rowNum) -> fromJson(rs.getString(1)),
|
||||||
|
holder, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String toJson(BookDocument book) {
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(book);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new BusinessException("图书数据无法序列化");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookDocument fromJson(String json) {
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, BookDocument.class);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new BusinessException("暂存的图书数据无法读取");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,3 +27,35 @@ spring:
|
|||||||
logging:
|
logging:
|
||||||
level:
|
level:
|
||||||
com.banben: debug
|
com.banben: debug
|
||||||
|
|
||||||
|
# 节点与南昌总库的图书同步。
|
||||||
|
# 陆工大暂用 10.1.1.243 的 ljgc_db。下推时从 version_resource 按批读出,
|
||||||
|
# 纸质写入 book_attr,电子写入 e_book。不把总库两百万条一次写完。
|
||||||
|
sync-hub:
|
||||||
|
token: local-mock-hub
|
||||||
|
store: jdbc
|
||||||
|
es-uris: http://127.0.0.1:9200
|
||||||
|
center-url: http://127.0.0.1:8080
|
||||||
|
auto-dispatch: true
|
||||||
|
retry-max: 3
|
||||||
|
batch-size: 200
|
||||||
|
dispatch-limit: 200
|
||||||
|
nodes:
|
||||||
|
- code: NJ_LZ
|
||||||
|
name: 南京陆指
|
||||||
|
kinds: MYSQL
|
||||||
|
callback-url: http://127.0.0.1:8080
|
||||||
|
- code: NJ_LGD
|
||||||
|
name: 南京陆工大
|
||||||
|
kinds: MYSQL,SQLSERVER
|
||||||
|
callback-url: http://127.0.0.1:8080
|
||||||
|
mysql-url: jdbc:mysql://10.1.1.243:3306/ljgc_db?useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=8000&characterEncoding=utf8
|
||||||
|
mysql-user: root
|
||||||
|
mysql-password: 123456
|
||||||
|
mysql-query: SELECT RECORD_ID AS process_no, TITLE AS title, AUTHOR AS author, ISBN13 AS isbn, PUBLISHER AS publisher, PUB_YEAR AS publish_year, CALL_NO AS clc_code FROM book_attr
|
||||||
|
paper-table: book_attr
|
||||||
|
ebook-table: e_book
|
||||||
|
- code: BHF
|
||||||
|
name: 边海防
|
||||||
|
kinds: MOCK
|
||||||
|
callback-url: http://127.0.0.1:8080
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- 版本资源元数据:补齐 32 个著录要素字段
|
||||||
|
-- 适用数据库:PostgreSQL / 瀚高(HighGo)
|
||||||
|
-- 说明:
|
||||||
|
-- 1. 本脚本【幂等】,可重复执行;仅当列不存在时才添加,不会对已建好
|
||||||
|
-- 完整表的库报错。
|
||||||
|
-- 2. 用于「实际运行库」是用更早版本表结构创建、尚缺这些列时的补列。
|
||||||
|
-- 3. schema.sql 已包含全部字段,新库直接执行 schema.sql 即可,无需本脚本。
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
-- ==================== 必备字段 ====================
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='process_no') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN process_no VARCHAR(128);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='title') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN title VARCHAR(512) NOT NULL DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='clc_code') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN clc_code VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='keywords') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN keywords VARCHAR(512);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='summary') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN summary TEXT;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_year') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN publish_year VARCHAR(8);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='process_date') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN process_date VARCHAR(16);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='content_form') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN content_form VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='media_type') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN media_type VARCHAR(32);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='format') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN format VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='page_count') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN page_count VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='language') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN language VARCHAR(16);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='submit_org') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN submit_org VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='task_year') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN task_year VARCHAR(8);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='source_library') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN source_library VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='source_library_addr') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN source_library_addr VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='fulltext_url') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN fulltext_url VARCHAR(1024);
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
-- ==================== 有则必备字段 ====================
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='other_title') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN other_title VARCHAR(512);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='author') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN author VARCHAR(512);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='responsibility') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN responsibility VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='note') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN note TEXT;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publisher') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN publisher VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_place') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN publish_place VARCHAR(128);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_date') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN publish_date VARCHAR(32);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='relation') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN relation VARCHAR(512);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='time_range') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN time_range VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='space_range') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN space_range VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='edition') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN edition VARCHAR(128);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='isbn') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN isbn VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='unified_book_no') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN unified_book_no VARCHAR(64);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='cdoi') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN cdoi VARCHAR(256);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='version_resource' AND column_name='publish_url') THEN
|
||||||
|
ALTER TABLE version_resource ADD COLUMN publish_url VARCHAR(1024);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 列注释(幂等,可重复执行)
|
||||||
|
COMMENT ON COLUMN version_resource.process_no IS '加工编号(必备)';
|
||||||
|
COMMENT ON COLUMN version_resource.title IS '正题名(必备)';
|
||||||
|
COMMENT ON COLUMN version_resource.clc_code IS '中图分类(必备)';
|
||||||
|
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 '内容形式(必备,GB/T 3469-2013)';
|
||||||
|
COMMENT ON COLUMN version_resource.media_type IS '媒体类型(必备:纸质/电子)';
|
||||||
|
COMMENT ON COLUMN version_resource.format IS '格式(必备,英文大写,如 TIF、PDF)';
|
||||||
|
COMMENT ON COLUMN version_resource.page_count IS '页码(必备)';
|
||||||
|
COMMENT ON COLUMN version_resource.language IS '语种(必备,3位语种代码)';
|
||||||
|
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 '来源馆地址(必备,IP:端口或域名)';
|
||||||
|
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 '发布地址(有则必备)';
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- 角色可见的顶部导航。已有角色默认拥有全部栏目,之后可在角色管理里取消勾选。
|
||||||
|
-- menu_inited=1 后再次执行不会把已清空的栏目补回来。
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_role_menu
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
role_id BIGINT NOT NULL,
|
||||||
|
menu_code VARCHAR(32) NOT NULL
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_role_menu ON sys_role_menu (role_id, menu_code);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sys_role_menu IS '角色可访问的顶部导航编码';
|
||||||
|
COMMENT ON COLUMN sys_role_menu.menu_code IS '导航编码,如 dashboard、search';
|
||||||
|
|
||||||
|
ALTER TABLE sys_role ADD COLUMN IF NOT EXISTS menu_inited SMALLINT DEFAULT 0;
|
||||||
|
COMMENT ON COLUMN sys_role.menu_inited IS '1表示顶部导航已按角色保存过,重复执行不再补全';
|
||||||
|
|
||||||
|
INSERT INTO sys_role_menu (role_id, menu_code)
|
||||||
|
SELECT r.id, m.code
|
||||||
|
FROM sys_role r
|
||||||
|
CROSS JOIN (
|
||||||
|
VALUES ('dashboard'), ('search'), ('hotwords'), ('special'),
|
||||||
|
('deposit'), ('analysis'), ('resource'), ('collect'), ('governance')
|
||||||
|
) AS m(code)
|
||||||
|
WHERE r.deleted = 0
|
||||||
|
AND COALESCE(r.menu_inited, 0) = 0
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id);
|
||||||
|
|
||||||
|
UPDATE sys_role
|
||||||
|
SET menu_inited = 1
|
||||||
|
WHERE deleted = 0
|
||||||
|
AND COALESCE(menu_inited, 0) = 0;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- 后台管理成为顶部导航的一项。已有的系统管理员默认拥有该栏目,其它角色需在角色管理里勾选。
|
||||||
|
|
||||||
|
INSERT INTO sys_role_menu (role_id, menu_code)
|
||||||
|
SELECT r.id, 'admin'
|
||||||
|
FROM sys_role r
|
||||||
|
WHERE r.deleted = 0
|
||||||
|
AND upper(r.code) = 'ADMIN'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id AND x.menu_code = 'admin'
|
||||||
|
);
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
-- 系统管理员补齐全部顶部栏目。可重复执行,已有的不会重复插入。
|
||||||
|
|
||||||
|
INSERT INTO sys_role_menu (role_id, menu_code)
|
||||||
|
SELECT r.id, m.code
|
||||||
|
FROM sys_role r
|
||||||
|
CROSS JOIN (
|
||||||
|
VALUES ('dashboard'), ('search'), ('hotwords'), ('special'),
|
||||||
|
('deposit'), ('analysis'), ('resource'), ('collect'),
|
||||||
|
('governance'), ('admin')
|
||||||
|
) AS m(code)
|
||||||
|
WHERE r.deleted = 0
|
||||||
|
AND upper(r.code) = 'ADMIN'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_role_menu x WHERE x.role_id = r.id AND x.menu_code = m.code
|
||||||
|
);
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- 版本资源多来源表
|
||||||
|
-- 支持「一条文献可有多个来源,概览页按来源图标+名称展示并可分别下载」
|
||||||
|
-- 兼容 PostgreSQL / 瀚高(HighGo)
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS resource_source
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
resource_id BIGINT NOT NULL,
|
||||||
|
source_repo VARCHAR(256),
|
||||||
|
source_library VARCHAR(256),
|
||||||
|
source_library_addr VARCHAR(256),
|
||||||
|
fulltext_url VARCHAR(1024),
|
||||||
|
process_no VARCHAR(128),
|
||||||
|
media_type VARCHAR(32),
|
||||||
|
sort_no INT DEFAULT 0,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
deleted SMALLINT DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_rs_resource_id ON resource_source (resource_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_rs_deleted ON resource_source (deleted);
|
||||||
|
|
||||||
|
COMMENT ON TABLE resource_source IS '版本资源多来源表(一条文献可来自多个资源库/来源馆)';
|
||||||
|
COMMENT ON COLUMN resource_source.resource_id IS '关联版本资源主记录ID';
|
||||||
|
COMMENT ON COLUMN resource_source.source_repo IS '来源资源库名';
|
||||||
|
COMMENT ON COLUMN resource_source.fulltext_url IS '全文下载地址';
|
||||||
|
|
||||||
|
-- 仅在无来源数据时为样例文献补全多来源(演示用,可重复执行)
|
||||||
|
INSERT INTO resource_source (resource_id, source_repo, source_library, source_library_addr, fulltext_url, process_no, media_type, sort_no)
|
||||||
|
SELECT v.id, '版本资源总库', v.source_library, v.source_library_addr, v.fulltext_url, v.process_no, v.media_type, 1
|
||||||
|
FROM version_resource v
|
||||||
|
WHERE v.id IN (1, 2)
|
||||||
|
AND v.deleted = 0
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM resource_source s WHERE s.resource_id = v.id AND s.deleted = 0);
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- 用户登录日志(会话维度)
|
||||||
|
-- 一次成功登录产生一条会话记录(online=1, logout_time=null);
|
||||||
|
-- 用户主动退出时回填 logout_time 并置 online=0。在线状态以 logout_time 为空为准。
|
||||||
|
-- 兼容 PostgreSQL / 瀚高(HighGo)
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS login_log
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT,
|
||||||
|
username VARCHAR(128),
|
||||||
|
real_name VARCHAR(128),
|
||||||
|
org_name VARCHAR(256),
|
||||||
|
ip VARCHAR(64),
|
||||||
|
user_agent VARCHAR(512),
|
||||||
|
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
logout_time TIMESTAMP,
|
||||||
|
online SMALLINT DEFAULT 1,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
|
||||||
|
|
||||||
|
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
|
||||||
|
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
|
||||||
|
COMMENT ON COLUMN login_log.username IS '登录账号';
|
||||||
|
COMMENT ON COLUMN login_log.real_name IS '姓名';
|
||||||
|
COMMENT ON COLUMN login_log.org_name IS '所属单位';
|
||||||
|
COMMENT ON COLUMN login_log.ip IS '登录IP';
|
||||||
|
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
|
||||||
|
COMMENT ON COLUMN login_log.login_time IS '登录时间';
|
||||||
|
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
|
||||||
|
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- 异构数据源同步
|
||||||
|
-- 连接信息、查询 SQL、字段映射全部落库,现场改配置即可,不在代码里写死外部库。
|
||||||
|
-- 兼容 PostgreSQL / 瀚高(HighGo)
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_datasource
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
name VARCHAR(128) NOT NULL,
|
||||||
|
db_type VARCHAR(32) NOT NULL,
|
||||||
|
host VARCHAR(256) NOT NULL,
|
||||||
|
port INTEGER NOT NULL,
|
||||||
|
db_name VARCHAR(128) NOT NULL,
|
||||||
|
username VARCHAR(128) NOT NULL,
|
||||||
|
password VARCHAR(256),
|
||||||
|
jdbc_params VARCHAR(1000),
|
||||||
|
enabled SMALLINT DEFAULT 1,
|
||||||
|
remark VARCHAR(500),
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
deleted SMALLINT DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_datasource IS '外部数据源连接配置';
|
||||||
|
COMMENT ON COLUMN sync_datasource.db_type IS 'MYSQL / ORACLE / SQLSERVER / POSTGRESQL / HIGHGO';
|
||||||
|
COMMENT ON COLUMN sync_datasource.db_name IS '库名。Oracle 填服务名';
|
||||||
|
COMMENT ON COLUMN sync_datasource.jdbc_params IS '附加连接参数,如 useSSL=false。空则使用该类型的默认参数';
|
||||||
|
COMMENT ON COLUMN sync_datasource.password IS '连接密码,接口不回传';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_task
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
name VARCHAR(128) NOT NULL,
|
||||||
|
datasource_id BIGINT NOT NULL,
|
||||||
|
query_sql TEXT NOT NULL,
|
||||||
|
target_table VARCHAR(64) NOT NULL DEFAULT 'version_resource',
|
||||||
|
batch_size INTEGER DEFAULT 200,
|
||||||
|
retry_times INTEGER DEFAULT 1,
|
||||||
|
cron_expr VARCHAR(64),
|
||||||
|
schedule_enabled SMALLINT DEFAULT 0,
|
||||||
|
sync_mode VARCHAR(16) DEFAULT 'FULL',
|
||||||
|
increment_column VARCHAR(64),
|
||||||
|
increment_value VARCHAR(128),
|
||||||
|
unique_fields VARCHAR(256),
|
||||||
|
enabled SMALLINT DEFAULT 1,
|
||||||
|
last_schedule_time TIMESTAMP,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
deleted SMALLINT DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_task IS '同步任务:查询 SQL、目标表、批次、重试、定时与增量水位';
|
||||||
|
COMMENT ON COLUMN sync_task.query_sql IS '外部库查询语句,只允许单条 SELECT。增量可写占位符 ${watermark}';
|
||||||
|
COMMENT ON COLUMN sync_task.sync_mode IS 'FULL 全量 / INCREMENT 增量(增量需在 SQL 中使用 ${watermark})';
|
||||||
|
COMMENT ON COLUMN sync_task.increment_column IS '增量水位来源列,成功后取本批最大值写回 increment_value';
|
||||||
|
COMMENT ON COLUMN sync_task.increment_value IS '上次成功同步的水位,增量预留';
|
||||||
|
COMMENT ON COLUMN sync_task.unique_fields IS '去重字段,目标表列名,多个用英文逗号分隔';
|
||||||
|
COMMENT ON COLUMN sync_task.cron_expr IS 'Spring 6 位 cron:秒 分 时 日 月 周';
|
||||||
|
COMMENT ON COLUMN sync_task.last_schedule_time IS '上次定时触发时间,用于计算下一次 cron';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_field_map
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
task_id BIGINT NOT NULL,
|
||||||
|
source_field VARCHAR(128) NOT NULL,
|
||||||
|
target_field VARCHAR(64) NOT NULL,
|
||||||
|
data_type VARCHAR(16) DEFAULT 'STRING',
|
||||||
|
clean_rule VARCHAR(32) DEFAULT 'TRIM',
|
||||||
|
required_flag SMALLINT DEFAULT 0,
|
||||||
|
default_value VARCHAR(256),
|
||||||
|
sort_no INTEGER DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sync_field_task ON sync_field_map (task_id);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_field_map IS '外部字段到目标表字段的映射,随任务保存,不写死在代码中';
|
||||||
|
COMMENT ON COLUMN sync_field_map.data_type IS 'STRING / INTEGER / LONG / DECIMAL / DATE / DATETIME';
|
||||||
|
COMMENT ON COLUMN sync_field_map.clean_rule IS 'NONE / TRIM / UPPER / LOWER / DIGITS / COMPACT_DATE';
|
||||||
|
COMMENT ON COLUMN sync_field_map.default_value IS '源值为空时使用。可用 ${uuid} ${today} ${year} ${seq} ${task}';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_log
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
task_id BIGINT,
|
||||||
|
datasource_id BIGINT,
|
||||||
|
task_name VARCHAR(128),
|
||||||
|
datasource_name VARCHAR(128),
|
||||||
|
trigger_type VARCHAR(16),
|
||||||
|
status VARCHAR(16),
|
||||||
|
start_time TIMESTAMP,
|
||||||
|
end_time TIMESTAMP,
|
||||||
|
success_count INTEGER DEFAULT 0,
|
||||||
|
fail_count INTEGER DEFAULT 0,
|
||||||
|
skip_count INTEGER DEFAULT 0,
|
||||||
|
error_message TEXT,
|
||||||
|
detail TEXT,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sync_log_task ON sync_log (task_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sync_log_start ON sync_log (start_time);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_log IS '每一次同步的执行记录';
|
||||||
|
COMMENT ON COLUMN sync_log.trigger_type IS 'MANUAL 手动 / SCHEDULE 定时';
|
||||||
|
COMMENT ON COLUMN sync_log.status IS 'RUNNING / SUCCESS / PARTIAL / FAILED';
|
||||||
|
COMMENT ON COLUMN sync_log.skip_count IS '因去重跳过的条数';
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
-- 节点与南昌总库的图书同步记录。不改 version_resource。
|
||||||
|
-- 兼容 PostgreSQL / 瀚高
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_hub_record
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
task_no VARCHAR(64) NOT NULL,
|
||||||
|
direction VARCHAR(8) NOT NULL,
|
||||||
|
source_node VARCHAR(32),
|
||||||
|
target_node VARCHAR(32),
|
||||||
|
source_db VARCHAR(32),
|
||||||
|
book_count INTEGER DEFAULT 0,
|
||||||
|
skip_count INTEGER DEFAULT 0,
|
||||||
|
status VARCHAR(16) NOT NULL,
|
||||||
|
error_message VARCHAR(1000),
|
||||||
|
retry_count INTEGER DEFAULT 0,
|
||||||
|
max_retry INTEGER DEFAULT 3,
|
||||||
|
start_time TIMESTAMP,
|
||||||
|
end_time TIMESTAMP,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sync_hub_record_status ON sync_hub_record (status, create_time);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_hub_record IS '图书同步记录:上推 UP、回传 DOWN';
|
||||||
|
COMMENT ON COLUMN sync_hub_record.direction IS 'UP 节点推总库 / DOWN 总库回传节点';
|
||||||
|
COMMENT ON COLUMN sync_hub_record.status IS 'RUNNING / SUCCESS / FAILED';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sync_hub_book
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
holder VARCHAR(32) NOT NULL,
|
||||||
|
doc_id VARCHAR(320) NOT NULL,
|
||||||
|
match_key VARCHAR(320),
|
||||||
|
node_code VARCHAR(32),
|
||||||
|
source_db VARCHAR(32),
|
||||||
|
process_no VARCHAR(128),
|
||||||
|
title VARCHAR(512),
|
||||||
|
media_type VARCHAR(32),
|
||||||
|
payload TEXT NOT NULL,
|
||||||
|
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book ON sync_hub_book (holder, doc_id);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uk_sync_hub_book_match ON sync_hub_book (holder, match_key);
|
||||||
|
|
||||||
|
COMMENT ON TABLE sync_hub_book IS '总库或节点暂存的图书元数据。store=es 时总库改写入 Elasticsearch';
|
||||||
|
COMMENT ON COLUMN sync_hub_book.holder IS 'CENTER 表示总库,节点编码表示该节点收到的回传';
|
||||||
|
COMMENT ON COLUMN sync_hub_book.match_key IS '比对键。有 ISBN 用 ISBN,否则用题名、作者、出版年';
|
||||||
|
COMMENT ON COLUMN sync_hub_record.skip_count IS '比对后已存在、未写入的条数';
|
||||||
|
COMMENT ON COLUMN sync_hub_record.book_count IS '本次新写入的条数';
|
||||||
@@ -110,6 +110,31 @@ CREATE TABLE IF NOT EXISTS list_field_config
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_lfc_scene ON list_field_config (scene, sort_no);
|
CREATE INDEX IF NOT EXISTS idx_lfc_scene ON list_field_config (scene, sort_no);
|
||||||
|
|
||||||
|
-- 版本资源多来源表(一条文献可来自多个资源库/来源馆,概览页按来源展示并可分别下载)
|
||||||
|
CREATE TABLE IF NOT EXISTS resource_source
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
resource_id BIGINT NOT NULL, -- 关联 version_resource.id
|
||||||
|
source_repo VARCHAR(256), -- 来源资源库名
|
||||||
|
source_library VARCHAR(256), -- 来源馆
|
||||||
|
source_library_addr VARCHAR(256), -- 来源馆地址 IP:端口/域名
|
||||||
|
fulltext_url VARCHAR(1024), -- 全文地址(下载地址)
|
||||||
|
process_no VARCHAR(128), -- 加工编号(来源库内编号)
|
||||||
|
media_type VARCHAR(32), -- 媒体类型:纸质/电子
|
||||||
|
sort_no INT DEFAULT 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_rs_resource_id ON resource_source (resource_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_rs_deleted ON resource_source (deleted);
|
||||||
|
|
||||||
|
COMMENT ON TABLE resource_source IS '版本资源多来源表(一条文献可来自多个资源库/来源馆)';
|
||||||
|
COMMENT ON COLUMN resource_source.resource_id IS '关联版本资源主记录ID';
|
||||||
|
COMMENT ON COLUMN resource_source.source_repo IS '来源资源库名';
|
||||||
|
COMMENT ON COLUMN resource_source.fulltext_url IS '全文下载地址';
|
||||||
|
|
||||||
-- 样例数据
|
-- 样例数据
|
||||||
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,
|
||||||
@@ -132,3 +157,46 @@ ON CONFLICT (id) DO NOTHING;
|
|||||||
-- 同步自增序列起点,避免与样例数据主键冲突
|
-- 同步自增序列起点,避免与样例数据主键冲突
|
||||||
SELECT setval('version_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM version_resource), 0), 1), true);
|
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);
|
SELECT setval('special_resource_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM special_resource), 0), 1), true);
|
||||||
|
|
||||||
|
-- 多来源演示数据:每条文献可归属多个资源库,概览页按来源图标+名称展示并可分别下载
|
||||||
|
INSERT INTO resource_source (resource_id, source_repo, source_library, source_library_addr, fulltext_url, process_no, media_type, sort_no)
|
||||||
|
VALUES
|
||||||
|
(1, '版本资源总库', '陆军步兵学院图书馆', '10.0.0.11:8080', 'http://cdio.example.org/fulltext/BB-2026-0001', 'BB-2026-0001', '纸质', 1),
|
||||||
|
(1, '军事理论特色库', '国防大学图书馆', '10.0.0.31:8080', 'http://cdio.example.org/fulltext/BB-2026-0001-dx', 'BB-2026-0001-DX', '电子', 2),
|
||||||
|
(2, '版本资源总库', '南京某院校图书馆', '10.0.0.21:8080', 'http://cdio.example.org/fulltext/BB-2026-0002', 'BB-2026-0002', '电子', 1),
|
||||||
|
(2, '电子图书镜像库', '西安某院校图书馆', '10.0.0.41:8080', 'http://cdio.example.org/fulltext/BB-2026-0002-mirror', 'BB-2026-0002-MIRROR', '电子', 2);
|
||||||
|
|
||||||
|
SELECT setval('resource_source_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM resource_source), 0), 1), true);
|
||||||
|
|
||||||
|
-- =====================================================================
|
||||||
|
-- 用户登录日志(会话维度):一次成功登录一条记录,登出写入 logout_time 并置 online=0
|
||||||
|
-- =====================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS login_log
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT,
|
||||||
|
username VARCHAR(128),
|
||||||
|
real_name VARCHAR(128),
|
||||||
|
org_name VARCHAR(256),
|
||||||
|
ip VARCHAR(64),
|
||||||
|
user_agent VARCHAR(512),
|
||||||
|
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
logout_time TIMESTAMP,
|
||||||
|
online SMALLINT DEFAULT 1,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
|
||||||
|
|
||||||
|
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
|
||||||
|
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
|
||||||
|
COMMENT ON COLUMN login_log.username IS '登录账号';
|
||||||
|
COMMENT ON COLUMN login_log.real_name IS '姓名';
|
||||||
|
COMMENT ON COLUMN login_log.org_name IS '所属单位';
|
||||||
|
COMMENT ON COLUMN login_log.ip IS '登录IP';
|
||||||
|
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
|
||||||
|
COMMENT ON COLUMN login_log.login_time IS '登录时间';
|
||||||
|
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
|
||||||
|
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';
|
||||||
|
|||||||
@@ -146,3 +146,109 @@ export function saveListFields(scene: string, items: ListFieldConfig[]) {
|
|||||||
export function resetListFields(scene: string) {
|
export function resetListFields(scene: string) {
|
||||||
return request.post<never, ListFieldConfig[]>(`/admin/list-fields/${scene}/reset`)
|
return request.post<never, ListFieldConfig[]>(`/admin/list-fields/${scene}/reset`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 登录日志 ====================
|
||||||
|
|
||||||
|
export interface LoginLog {
|
||||||
|
id?: number
|
||||||
|
userId?: number
|
||||||
|
/** 登录账号 */
|
||||||
|
username?: string
|
||||||
|
/** 姓名 */
|
||||||
|
realName?: string
|
||||||
|
/** 所属单位 */
|
||||||
|
orgName?: string
|
||||||
|
/** 登录IP */
|
||||||
|
ip?: string
|
||||||
|
/** 浏览器/客户端标识 */
|
||||||
|
userAgent?: string
|
||||||
|
/** 登录时间 */
|
||||||
|
loginTime?: string
|
||||||
|
/** 退出时间,未退出为 null */
|
||||||
|
logoutTime?: string | null
|
||||||
|
/** 是否在线:1在线 0离线 */
|
||||||
|
online?: number
|
||||||
|
createTime?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLogQuery {
|
||||||
|
current: number
|
||||||
|
size: number
|
||||||
|
keyword?: string
|
||||||
|
/** ONLINE 在线 / OFFLINE 离线 / 不传 全部 */
|
||||||
|
status?: string
|
||||||
|
/** 登录时间起(yyyy-MM-dd) */
|
||||||
|
loginStart?: string
|
||||||
|
/** 登录时间止(yyyy-MM-dd) */
|
||||||
|
loginEnd?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLogSummary {
|
||||||
|
/** 会话总数 */
|
||||||
|
total: number
|
||||||
|
/** 当前在线人数 */
|
||||||
|
online: number
|
||||||
|
/** 今日登录次数 */
|
||||||
|
today: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录日志分页 */
|
||||||
|
export function pageLoginLogs(params: LoginLogQuery) {
|
||||||
|
return request.get<never, PageResult<LoginLog>>('/admin/login-logs/page', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录日志概览统计 */
|
||||||
|
export function loginLogSummary() {
|
||||||
|
return request.get<never, LoginLogSummary>('/admin/login-logs/summary')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 网络访问统计 ====================
|
||||||
|
|
||||||
|
export interface AccessOverview {
|
||||||
|
/** 历史访问人次 */
|
||||||
|
historyCount: number
|
||||||
|
/** 历史访问人数(去重) */
|
||||||
|
historyUsers: number
|
||||||
|
/** 本月访问人次 */
|
||||||
|
monthCount: number
|
||||||
|
monthUsers: number
|
||||||
|
/** 本周访问人次 */
|
||||||
|
weekCount: number
|
||||||
|
weekUsers: number
|
||||||
|
/** 今日访问人次 */
|
||||||
|
todayCount: number
|
||||||
|
todayUsers: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccessTrendPoint {
|
||||||
|
/** 时间桶,如 2026-11-04 08 / 2026-11 / 2026 */
|
||||||
|
bucket: string
|
||||||
|
/** 访问人次 */
|
||||||
|
count: number
|
||||||
|
/** 访问人数(去重) */
|
||||||
|
users: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccessDimensionItem {
|
||||||
|
/** 维度值(IP / 单位 / 账号 / 在线状态) */
|
||||||
|
name: string
|
||||||
|
/** 访问人次 */
|
||||||
|
count: number
|
||||||
|
/** 访问人数(去重) */
|
||||||
|
users: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 网络访问概览:历史 / 本月 / 本周 / 今日 */
|
||||||
|
export function accessOverview() {
|
||||||
|
return request.get<never, AccessOverview>('/admin/login-logs/access-overview')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 网络访问趋势:granularity = hour|day|week|month|year,可指定 start/end(yyyy-MM-dd) */
|
||||||
|
export function accessTrend(params: { granularity: string; start?: string; end?: string }) {
|
||||||
|
return request.get<never, AccessTrendPoint[]>('/admin/login-logs/access-trend', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 网络访问维度统计:dimension = ip|org|account|type */
|
||||||
|
export function accessDimension(params: { dimension: string; start?: string; end?: string; limit?: number }) {
|
||||||
|
return request.get<never, AccessDimensionItem[]>('/admin/login-logs/access-dimension', { params })
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,6 +20,11 @@ export function getCurrentUser() {
|
|||||||
return request.get<never, UserInfo>('/auth/me')
|
return request.get<never, UserInfo>('/auth/me')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 当前用户可见的顶部导航编码 */
|
||||||
|
export function myMenus() {
|
||||||
|
return request.get<never, string[]>('/auth/menus')
|
||||||
|
}
|
||||||
|
|
||||||
/** 登出 */
|
/** 登出 */
|
||||||
export function logout() {
|
export function logout() {
|
||||||
return request.post<never, void>('/auth/logout')
|
return request.post<never, void>('/auth/logout')
|
||||||
|
|||||||
@@ -32,18 +32,6 @@ export interface VersionResource {
|
|||||||
publishDate?: string
|
publishDate?: string
|
||||||
edition?: string
|
edition?: string
|
||||||
isbn?: string
|
isbn?: string
|
||||||
/** 统一书号 */
|
|
||||||
unifiedBookNo?: string
|
|
||||||
/** CDOI */
|
|
||||||
cdoi?: string
|
|
||||||
/** 发布地址 */
|
|
||||||
publishUrl?: string
|
|
||||||
/** 关联 */
|
|
||||||
relation?: string
|
|
||||||
/** 时间范围 */
|
|
||||||
timeRange?: string
|
|
||||||
/** 空间范围 */
|
|
||||||
spaceRange?: string
|
|
||||||
governStatus?: string
|
governStatus?: string
|
||||||
mergedToId?: number
|
mergedToId?: number
|
||||||
abnormalFlag?: number
|
abnormalFlag?: number
|
||||||
@@ -52,6 +40,28 @@ export interface VersionResource {
|
|||||||
isSpecial?: number
|
isSpecial?: number
|
||||||
/** 附注 */
|
/** 附注 */
|
||||||
note?: string
|
note?: string
|
||||||
|
/** 多来源列表:一条文献可来自多个资源库,概览页按来源图标+名称展示并可分别下载 */
|
||||||
|
sources?: ResourceSource[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 版本资源多来源(一条文献可来自多个资源库/来源馆) */
|
||||||
|
export interface ResourceSource {
|
||||||
|
id?: number
|
||||||
|
resourceId?: number
|
||||||
|
/** 来源资源库名 */
|
||||||
|
sourceRepo?: string
|
||||||
|
/** 来源馆 */
|
||||||
|
sourceLibrary?: string
|
||||||
|
/** 来源馆地址(IP:端口或域名) */
|
||||||
|
sourceLibraryAddr?: string
|
||||||
|
/** 全文下载地址 */
|
||||||
|
fulltextUrl?: string
|
||||||
|
/** 加工编号(来源库内编号) */
|
||||||
|
processNo?: string
|
||||||
|
/** 媒体类型:纸质/电子 */
|
||||||
|
mediaType?: string
|
||||||
|
/** 展示顺序,数值小的靠前 */
|
||||||
|
sortNo?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ResourceQuery {
|
export interface ResourceQuery {
|
||||||
|
|||||||
@@ -26,6 +26,12 @@ export interface SearchQuery extends ResourceQuery {
|
|||||||
sourceLibraries?: string[]
|
sourceLibraries?: string[]
|
||||||
/** 来源馆(单选,左侧「来源院校」分面点选用) */
|
/** 来源馆(单选,左侧「来源院校」分面点选用) */
|
||||||
sourceLibrary?: string
|
sourceLibrary?: string
|
||||||
|
/** 来源资源库名(多选,in) */
|
||||||
|
sourceRepos?: string[]
|
||||||
|
/** 媒体类型(多选,in):纸质/电子 */
|
||||||
|
mediaTypes?: string[]
|
||||||
|
/** 在结果中搜索:附加关键词必须同时命中(AND 收窄) */
|
||||||
|
withinKeyword?: string
|
||||||
publishYearStart?: string
|
publishYearStart?: string
|
||||||
publishYearEnd?: string
|
publishYearEnd?: string
|
||||||
matchType?: 'EQ' | 'LEFT' | 'RIGHT' | 'LIKE'
|
matchType?: 'EQ' | 'LEFT' | 'RIGHT' | 'LIKE'
|
||||||
@@ -50,6 +56,7 @@ export interface SearchResultVO {
|
|||||||
page: PageResult<VersionResource>
|
page: PageResult<VersionResource>
|
||||||
mediaTypeFacets: FacetItem[]
|
mediaTypeFacets: FacetItem[]
|
||||||
sourceLibraryFacets: FacetItem[]
|
sourceLibraryFacets: FacetItem[]
|
||||||
|
sourceRepoFacets?: FacetItem[]
|
||||||
clcFacets: FacetItem[]
|
clcFacets: FacetItem[]
|
||||||
yearStats: YearStat[]
|
yearStats: YearStat[]
|
||||||
costMs: number
|
costMs: number
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export interface SyncDatasource {
|
||||||
|
id?: number
|
||||||
|
name: string
|
||||||
|
dbType: string
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
dbName: string
|
||||||
|
username: string
|
||||||
|
dbPassword?: string
|
||||||
|
password?: string
|
||||||
|
jdbcParams?: string
|
||||||
|
enabled?: number
|
||||||
|
remark?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncFieldMap {
|
||||||
|
sourceField: string
|
||||||
|
targetField: string
|
||||||
|
dataType?: string
|
||||||
|
cleanRule?: string
|
||||||
|
requiredFlag?: number
|
||||||
|
defaultValue?: string
|
||||||
|
sortNo?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncTask {
|
||||||
|
id?: number
|
||||||
|
name: string
|
||||||
|
datasourceId?: number
|
||||||
|
datasourceName?: string
|
||||||
|
querySql: string
|
||||||
|
targetTable: string
|
||||||
|
batchSize?: number
|
||||||
|
retryTimes?: number
|
||||||
|
cronExpr?: string
|
||||||
|
scheduleEnabled?: number
|
||||||
|
syncMode?: string
|
||||||
|
incrementColumn?: string
|
||||||
|
incrementValue?: string
|
||||||
|
uniqueFields?: string
|
||||||
|
enabled?: number
|
||||||
|
mappings: SyncFieldMap[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TargetColumn {
|
||||||
|
name: string
|
||||||
|
comment?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncLog {
|
||||||
|
id: number
|
||||||
|
taskId?: number
|
||||||
|
taskName?: string
|
||||||
|
datasourceName?: string
|
||||||
|
triggerType?: string
|
||||||
|
status?: string
|
||||||
|
startTime?: string
|
||||||
|
endTime?: string
|
||||||
|
successCount?: number
|
||||||
|
failCount?: number
|
||||||
|
skipCount?: number
|
||||||
|
errorMessage?: string
|
||||||
|
detail?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PageResult<T> {
|
||||||
|
records: T[]
|
||||||
|
total: number
|
||||||
|
current: number
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listSyncDatasources() {
|
||||||
|
return request.get<never, SyncDatasource[]>('/sync/datasource')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSyncDatasource(data: SyncDatasource) {
|
||||||
|
if (data.id) return request.put<never, void>(`/sync/datasource/${data.id}`, data)
|
||||||
|
return request.post<never, number>('/sync/datasource', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeSyncDatasource(id: number) {
|
||||||
|
return request.delete<never, void>(`/sync/datasource/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function testSyncDatasource(data: SyncDatasource) {
|
||||||
|
return request.post<never, string>('/sync/datasource/test', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function previewSyncColumns(datasource: SyncDatasource, querySql: string) {
|
||||||
|
return request.post<never, string[]>('/sync/preview', { datasource, querySql })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listTargetTables() {
|
||||||
|
return request.get<never, string[]>('/sync/target/tables')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listTargetColumns(table: string) {
|
||||||
|
return request.get<never, TargetColumn[]>('/sync/target/columns', { params: { table } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listSyncTasks() {
|
||||||
|
return request.get<never, SyncTask[]>('/sync/task')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSyncTask(data: SyncTask) {
|
||||||
|
if (data.id) return request.put<never, void>(`/sync/task/${data.id}`, data)
|
||||||
|
return request.post<never, number>('/sync/task', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeSyncTask(id: number) {
|
||||||
|
return request.delete<never, void>(`/sync/task/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runSyncTask(id: number) {
|
||||||
|
return request.post<never, number>(`/sync/task/${id}/run`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pageSyncLogs(params: { taskId?: number; current: number; size: number }) {
|
||||||
|
return request.get<never, PageResult<SyncLog>>('/sync/log', { params })
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ export interface RoleItem {
|
|||||||
remark?: string
|
remark?: string
|
||||||
status?: number
|
status?: number
|
||||||
builtin?: number
|
builtin?: number
|
||||||
|
menuCodes?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RoleSave {
|
export interface RoleSave {
|
||||||
@@ -36,6 +37,7 @@ export interface RoleSave {
|
|||||||
name: string
|
name: string
|
||||||
remark?: string
|
remark?: string
|
||||||
status?: number
|
status?: number
|
||||||
|
menuCodes?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserItem {
|
export interface UserItem {
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/** 顶部导航。编码与后端 NavMenus、路由 meta.menu 一致。 */
|
||||||
|
export const NAV_MENUS = [
|
||||||
|
{ code: 'dashboard', title: '首页', path: '/dashboard' },
|
||||||
|
{ code: 'search', title: '资源检索', path: '/search' },
|
||||||
|
{ code: 'hotwords', title: '热词检索', path: '/hotwords' },
|
||||||
|
{ code: 'special', title: '特藏推荐', path: '/special' },
|
||||||
|
{ code: 'deposit', title: '资源呈缴', path: '/deposit' },
|
||||||
|
{ code: 'analysis', title: '数据统计', path: '/analysis' },
|
||||||
|
{ code: 'resource', title: '资源管理', path: '/resource' },
|
||||||
|
{ code: 'collect', title: '数据采集', path: '/collect' },
|
||||||
|
{ code: 'sync', title: '数据同步', path: '/sync' },
|
||||||
|
{ code: 'governance', title: '数据治理', path: '/governance' },
|
||||||
|
{ code: 'admin', title: '后台管理', path: '/admin' }
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type NavCode = (typeof NAV_MENUS)[number]['code']
|
||||||
|
|
||||||
|
export function firstAllowedPath(menus: string[]): string | null {
|
||||||
|
const item = NAV_MENUS.find((menu) => menus.includes(menu.code))
|
||||||
|
return item ? item.path : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function navTitle(code: string): string {
|
||||||
|
return NAV_MENUS.find((menu) => menu.code === code)?.title || code
|
||||||
|
}
|
||||||
@@ -1,37 +1,49 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue'
|
import { computed, onMounted, ref } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { clearAuth, getUser } from '@/utils/auth'
|
import { myMenus } from '@/api/auth'
|
||||||
|
import { NAV_MENUS, firstAllowedPath } from '@/constants/nav'
|
||||||
|
import { clearAuth, getUser, setUser } from '@/utils/auth'
|
||||||
import logoUrl from '@/assets/logo-green.png'
|
import logoUrl from '@/assets/logo-green.png'
|
||||||
import noticeUrl from '@/assets/icon-notice.png'
|
import noticeUrl from '@/assets/icon-notice.png'
|
||||||
import settingUrl from '@/assets/icon-setting.png'
|
|
||||||
import avatarUrl from '@/assets/avatar.png'
|
import avatarUrl from '@/assets/avatar.png'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const user = computed(() => getUser())
|
const user = computed(() => getUser())
|
||||||
|
const allowed = ref<string[] | null>(getUser()?.menus ?? null)
|
||||||
|
|
||||||
const menus = [
|
const menus = computed(() => {
|
||||||
{ path: '/dashboard', title: '首页' },
|
if (allowed.value == null) return NAV_MENUS
|
||||||
{ path: '/search', title: '资源检索' },
|
return NAV_MENUS.filter((menu) => allowed.value!.includes(menu.code))
|
||||||
{ path: '/hotwords', title: '热词检索' },
|
})
|
||||||
{ path: '/special', title: '特藏推荐' },
|
|
||||||
{ path: '/deposit', title: '资源呈缴' },
|
const canSeeCurrent = computed(() => {
|
||||||
{ path: '/analysis', title: '数据统计' },
|
const code = route.meta.menu as string | undefined
|
||||||
{ path: '/resource', title: '资源管理' },
|
if (!code || allowed.value == null) return true
|
||||||
{ path: '/collect', title: '数据采集' },
|
return allowed.value.includes(code)
|
||||||
{ path: '/governance', title: '数据治理' }
|
})
|
||||||
]
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const list = await myMenus()
|
||||||
|
allowed.value = list
|
||||||
|
const current = getUser()
|
||||||
|
if (current) setUser({ ...current, menus: list })
|
||||||
|
const code = route.meta.menu as string | undefined
|
||||||
|
if (code && !list.includes(code)) {
|
||||||
|
const next = firstAllowedPath(list)
|
||||||
|
if (next) router.replace(next)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 权限接口暂时不可用时,沿用登录时记下的栏目
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
function logout() {
|
function logout() {
|
||||||
clearAuth()
|
clearAuth()
|
||||||
router.push('/login')
|
router.push('/login')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 齿轮按钮:新标签页打开后台管理 */
|
|
||||||
function openAdmin() {
|
|
||||||
window.open(router.resolve('/admin').href, '_blank')
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -47,7 +59,7 @@ function openAdmin() {
|
|||||||
<a
|
<a
|
||||||
v-for="m in menus"
|
v-for="m in menus"
|
||||||
:key="m.path"
|
:key="m.path"
|
||||||
:class="{ active: route.path === m.path }"
|
:class="{ active: route.path === m.path || route.path.startsWith(m.path + '/') }"
|
||||||
@click="router.push(m.path)"
|
@click="router.push(m.path)"
|
||||||
>
|
>
|
||||||
{{ m.title }}
|
{{ m.title }}
|
||||||
@@ -55,7 +67,6 @@ function openAdmin() {
|
|||||||
</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" 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>
|
||||||
@@ -63,7 +74,8 @@ function openAdmin() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main class="site-main">
|
<main class="site-main">
|
||||||
<router-view />
|
<router-view v-if="canSeeCurrent" />
|
||||||
|
<el-empty v-else description="当前角色没有此栏目的访问权限" />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -177,16 +189,23 @@ function openAdmin() {
|
|||||||
.nav {
|
.nav {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
scrollbar-width: none;
|
||||||
|
|
||||||
|
&::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
padding: 0 11px;
|
padding: 0 8px;
|
||||||
color: rgba(255, 255, 255, 0.78);
|
color: rgba(255, 255, 255, 0.78);
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
letter-spacing: 0.5px;
|
letter-spacing: 0.5px;
|
||||||
@@ -198,8 +217,8 @@ function openAdmin() {
|
|||||||
&::after {
|
&::after {
|
||||||
content: '';
|
content: '';
|
||||||
position: absolute;
|
position: absolute;
|
||||||
left: 11px;
|
left: 8px;
|
||||||
right: 11px;
|
right: 8px;
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
height: 2px;
|
height: 2px;
|
||||||
background: var(--brand-gold);
|
background: var(--brand-gold);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
||||||
import BasicLayout from '@/layouts/BasicLayout.vue'
|
import BasicLayout from '@/layouts/BasicLayout.vue'
|
||||||
import { getToken } from '@/utils/auth'
|
import { firstAllowedPath } from '@/constants/nav'
|
||||||
|
import { getToken, getUser } from '@/utils/auth'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 路由表:与招标文件功能模块对应。
|
* 路由表:与招标文件功能模块对应。
|
||||||
@@ -16,67 +17,73 @@ const routes: RouteRecordRaw[] = [
|
|||||||
path: 'dashboard',
|
path: 'dashboard',
|
||||||
name: 'Dashboard',
|
name: 'Dashboard',
|
||||||
component: () => import('@/views/Dashboard.vue'),
|
component: () => import('@/views/Dashboard.vue'),
|
||||||
meta: { title: '首页概览', icon: 'HomeFilled' }
|
meta: { title: '首页概览', icon: 'HomeFilled', menu: 'dashboard' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'search',
|
path: 'search',
|
||||||
name: 'Search',
|
name: 'Search',
|
||||||
component: () => import('@/views/search/SearchView.vue'),
|
component: () => import('@/views/search/SearchView.vue'),
|
||||||
meta: { title: '检索发现', icon: 'Search' }
|
meta: { title: '检索发现', icon: 'Search', menu: 'search' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'hotwords',
|
path: 'hotwords',
|
||||||
name: 'HotWords',
|
name: 'HotWords',
|
||||||
component: () => import('@/views/search/HotWords.vue'),
|
component: () => import('@/views/search/HotWords.vue'),
|
||||||
meta: { title: '热词检索', icon: 'Cloudy' }
|
meta: { title: '热词检索', icon: 'Cloudy', menu: 'hotwords' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'advanced',
|
path: 'advanced',
|
||||||
name: 'Advanced',
|
name: 'Advanced',
|
||||||
component: () => import('@/views/search/AdvancedView.vue'),
|
component: () => import('@/views/search/AdvancedView.vue'),
|
||||||
meta: { title: '高级检索' }
|
meta: { title: '高级检索', menu: 'search' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'resource',
|
path: 'resource',
|
||||||
name: 'Resource',
|
name: 'Resource',
|
||||||
component: () => import('@/views/resource/ResourceList.vue'),
|
component: () => import('@/views/resource/ResourceList.vue'),
|
||||||
meta: { title: '版本资源库', icon: 'Collection' }
|
meta: { title: '版本资源库', icon: 'Collection', menu: 'resource' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'collect',
|
path: 'collect',
|
||||||
name: 'Collect',
|
name: 'Collect',
|
||||||
component: () => import('@/views/collect/CollectView.vue'),
|
component: () => import('@/views/collect/CollectView.vue'),
|
||||||
meta: { title: '数据采集', icon: 'Download' }
|
meta: { title: '数据采集', icon: 'Download', menu: 'collect' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sync',
|
||||||
|
name: 'Sync',
|
||||||
|
component: () => import('@/views/sync/SyncView.vue'),
|
||||||
|
meta: { title: '数据同步', icon: 'Connection', menu: 'sync' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'governance',
|
path: 'governance',
|
||||||
name: 'Governance',
|
name: 'Governance',
|
||||||
component: () => import('@/views/governance/GovernanceView.vue'),
|
component: () => import('@/views/governance/GovernanceView.vue'),
|
||||||
meta: { title: '数据治理', icon: 'MagicStick' }
|
meta: { title: '数据治理', icon: 'MagicStick', menu: 'governance' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'special',
|
path: 'special',
|
||||||
name: 'Special',
|
name: 'Special',
|
||||||
component: () => import('@/views/special/SpecialView.vue'),
|
component: () => import('@/views/special/SpecialView.vue'),
|
||||||
meta: { title: '特藏推荐', icon: 'Star' }
|
meta: { title: '特藏推荐', icon: 'Star', menu: 'special' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'deposit',
|
path: 'deposit',
|
||||||
name: 'Deposit',
|
name: 'Deposit',
|
||||||
component: () => import('@/views/deposit/DepositView.vue'),
|
component: () => import('@/views/deposit/DepositView.vue'),
|
||||||
meta: { title: '资源呈缴', icon: 'Upload' }
|
meta: { title: '资源呈缴', icon: 'Upload', menu: 'deposit' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'analysis',
|
path: 'analysis',
|
||||||
name: 'Analysis',
|
name: 'Analysis',
|
||||||
component: () => import('@/views/analysis/AnalysisView.vue'),
|
component: () => import('@/views/analysis/AnalysisView.vue'),
|
||||||
meta: { title: '统计分析', icon: 'DataAnalysis' }
|
meta: { title: '统计分析', icon: 'DataAnalysis', menu: 'analysis' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'admin',
|
path: 'admin',
|
||||||
name: 'Admin',
|
name: 'Admin',
|
||||||
component: () => import('@/views/admin/AdminView.vue'),
|
component: () => import('@/views/admin/AdminView.vue'),
|
||||||
meta: { title: '后台管理' }
|
meta: { title: '后台管理', menu: 'admin' }
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -107,6 +114,12 @@ router.beforeEach((to) => {
|
|||||||
if (to.path === '/login' && token) {
|
if (to.path === '/login' && token) {
|
||||||
return '/'
|
return '/'
|
||||||
}
|
}
|
||||||
|
const menu = to.meta?.menu as string | undefined
|
||||||
|
const menus = getUser()?.menus
|
||||||
|
if (menu && menus && !menus.includes(menu)) {
|
||||||
|
const next = firstAllowedPath(menus)
|
||||||
|
if (next && next !== to.path) return next
|
||||||
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ a {
|
|||||||
.el-dialog {
|
.el-dialog {
|
||||||
border: 1px solid var(--card-gold-border);
|
border: 1px solid var(--card-gold-border);
|
||||||
border-radius: var(--radius-sm);
|
border-radius: var(--radius-sm);
|
||||||
overflow: hidden;
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
|
||||||
.el-dialog__header,
|
.el-dialog__header,
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export interface UserInfo {
|
|||||||
realName: string
|
realName: string
|
||||||
role: string
|
role: string
|
||||||
orgName: string
|
orgName: string
|
||||||
|
/** 可见的顶部导航编码。未下发时表示尚未刷新,先按全部栏目显示。 */
|
||||||
|
menus?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getToken(): string {
|
export function getToken(): string {
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ async function handleLogin() {
|
|||||||
username: res.username,
|
username: res.username,
|
||||||
realName: res.realName,
|
realName: res.realName,
|
||||||
role: res.role,
|
role: res.role,
|
||||||
orgName: res.orgName
|
orgName: res.orgName,
|
||||||
|
menus: res.menus
|
||||||
})
|
})
|
||||||
ElMessage.success('登录成功')
|
ElMessage.success('登录成功')
|
||||||
const redirect = (route.query.redirect as string) || '/'
|
const redirect = (route.query.redirect as string) || '/'
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
|
import * as echarts from 'echarts'
|
||||||
|
import {
|
||||||
|
accessDimension,
|
||||||
|
accessOverview,
|
||||||
|
accessTrend,
|
||||||
|
type AccessDimensionItem,
|
||||||
|
type AccessOverview,
|
||||||
|
type AccessTrendPoint
|
||||||
|
} from '@/api/admin'
|
||||||
|
|
||||||
|
const overview = ref<AccessOverview | null>(null)
|
||||||
|
const granularity = ref<'hour' | 'day' | 'week' | 'month' | 'year'>('hour')
|
||||||
|
const dateRange = ref<string[]>([])
|
||||||
|
const dimension = ref<'ip' | 'org' | 'account' | 'type'>('ip')
|
||||||
|
const trendData = ref<AccessTrendPoint[]>([])
|
||||||
|
const dimData = ref<AccessDimensionItem[]>([])
|
||||||
|
|
||||||
|
const trendRef = ref<HTMLElement>()
|
||||||
|
const dimRef = ref<HTMLElement>()
|
||||||
|
const charts: echarts.ECharts[] = []
|
||||||
|
|
||||||
|
function todayStr(): string {
|
||||||
|
const d = new Date()
|
||||||
|
const p = (n: number) => String(n).padStart(2, '0')
|
||||||
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function rangeParams() {
|
||||||
|
return {
|
||||||
|
start: dateRange.value?.[0] || undefined,
|
||||||
|
end: dateRange.value?.[1] || undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const overviewCards = computed(() =>
|
||||||
|
overview.value
|
||||||
|
? [
|
||||||
|
{ label: '历史访问', count: overview.value.historyCount, users: overview.value.historyUsers },
|
||||||
|
{ label: '本月访问', count: overview.value.monthCount, users: overview.value.monthUsers },
|
||||||
|
{ label: '本周访问', count: overview.value.weekCount, users: overview.value.weekUsers },
|
||||||
|
{ label: '今日访问', count: overview.value.todayCount, users: overview.value.todayUsers }
|
||||||
|
]
|
||||||
|
: []
|
||||||
|
)
|
||||||
|
|
||||||
|
async function loadOverview() {
|
||||||
|
overview.value = await accessOverview()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTrend() {
|
||||||
|
const data = await accessTrend({ granularity: granularity.value, ...rangeParams() })
|
||||||
|
// 小时粒度补全 0-23,保证「今日各小时」视图完整
|
||||||
|
let list = data
|
||||||
|
if (granularity.value === 'hour') {
|
||||||
|
const byKey = new Map<string, AccessTrendPoint>()
|
||||||
|
data.forEach((d) => byKey.set(d.bucket.slice(-2), d))
|
||||||
|
list = []
|
||||||
|
for (let h = 0; h < 24; h++) {
|
||||||
|
const key = String(h).padStart(2, '0')
|
||||||
|
list.push(byKey.get(key) ?? { bucket: key, count: 0, users: 0 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trendData.value = list
|
||||||
|
renderTrend(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDimension() {
|
||||||
|
dimData.value = await accessDimension({ dimension: dimension.value, limit: 20, ...rangeParams() })
|
||||||
|
renderDim(dimData.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function searchAll() {
|
||||||
|
await Promise.all([loadTrend(), loadDimension()])
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
granularity.value = 'hour'
|
||||||
|
dateRange.value = [todayStr(), todayStr()]
|
||||||
|
dimension.value = 'ip'
|
||||||
|
searchAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTrend(list: AccessTrendPoint[]) {
|
||||||
|
const el = trendRef.value
|
||||||
|
if (!el) return
|
||||||
|
let chart = charts[0]
|
||||||
|
if (!chart) {
|
||||||
|
chart = echarts.init(el)
|
||||||
|
charts[0] = chart
|
||||||
|
}
|
||||||
|
const labels = list.map((d) => (granularity.value === 'hour' ? d.bucket.slice(-2) + '时' : d.bucket))
|
||||||
|
chart.setOption({
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { data: ['访问人次', '访问人数'], bottom: 0 },
|
||||||
|
grid: { left: 50, right: 20, top: 30, bottom: 40 },
|
||||||
|
xAxis: { type: 'category', data: labels, axisLabel: { color: '#23362c' } },
|
||||||
|
yAxis: { type: 'value', axisLabel: { color: '#23362c' } },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: '访问人次',
|
||||||
|
type: 'bar',
|
||||||
|
data: list.map((d) => d.count),
|
||||||
|
itemStyle: { color: '#b8862d' },
|
||||||
|
barMaxWidth: 28
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '访问人数',
|
||||||
|
type: 'line',
|
||||||
|
smooth: true,
|
||||||
|
data: list.map((d) => d.users),
|
||||||
|
itemStyle: { color: '#2f5d47' },
|
||||||
|
lineStyle: { width: 2 }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
chart.resize()
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDim(list: AccessDimensionItem[]) {
|
||||||
|
const el = dimRef.value
|
||||||
|
if (!el) return
|
||||||
|
let chart = charts[1]
|
||||||
|
if (!chart) {
|
||||||
|
chart = echarts.init(el)
|
||||||
|
charts[1] = chart
|
||||||
|
}
|
||||||
|
const top = list.slice(0, 10).reverse()
|
||||||
|
chart.setOption({
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
grid: { left: 10, right: 24, top: 10, bottom: 10, containLabel: true },
|
||||||
|
xAxis: { type: 'value', axisLabel: { color: '#23362c' } },
|
||||||
|
yAxis: { type: 'category', inverse: true, data: top.map((d) => d.name), axisLabel: { color: '#23362c' } },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: '访问人次',
|
||||||
|
type: 'bar',
|
||||||
|
data: top.map((d) => d.count),
|
||||||
|
itemStyle: { color: '#5b9a78' },
|
||||||
|
barMaxWidth: 22
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
chart.resize()
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleResize() {
|
||||||
|
charts.forEach((c) => c.resize())
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
dateRange.value = [todayStr(), todayStr()]
|
||||||
|
await Promise.all([loadOverview(), loadTrend(), loadDimension()])
|
||||||
|
window.addEventListener('resize', handleResize)
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('resize', handleResize)
|
||||||
|
charts.forEach((c) => c.dispose())
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="access-stats">
|
||||||
|
<!-- 概览卡片 -->
|
||||||
|
<el-row :gutter="16" class="mb-16">
|
||||||
|
<el-col v-for="c in overviewCards" :key="c.label" :xs="12" :sm="6">
|
||||||
|
<div class="ov-card">
|
||||||
|
<div class="ov-label">{{ c.label }}</div>
|
||||||
|
<div class="ov-count">{{ c.count.toLocaleString() }}</div>
|
||||||
|
<div class="ov-users">访问人数 {{ c.users.toLocaleString() }}</div>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- 控制条 -->
|
||||||
|
<div class="toolbar">
|
||||||
|
<span class="tb-label">时间粒度</span>
|
||||||
|
<el-radio-group v-model="granularity" size="small" @change="loadTrend">
|
||||||
|
<el-radio-button value="hour">小时</el-radio-button>
|
||||||
|
<el-radio-button value="day">日</el-radio-button>
|
||||||
|
<el-radio-button value="week">周</el-radio-button>
|
||||||
|
<el-radio-button value="month">月</el-radio-button>
|
||||||
|
<el-radio-button value="year">年</el-radio-button>
|
||||||
|
</el-radio-group>
|
||||||
|
<el-date-picker
|
||||||
|
v-model="dateRange"
|
||||||
|
type="daterange"
|
||||||
|
:editable="false"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="开始日期"
|
||||||
|
end-placeholder="结束日期"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 260px"
|
||||||
|
@change="searchAll"
|
||||||
|
/>
|
||||||
|
<el-button type="primary" @click="searchAll">查询</el-button>
|
||||||
|
<el-button @click="reset">重置</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 访问趋势 -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<span class="panel-title">访问趋势</span>
|
||||||
|
<span class="panel-sub">人次 = 登录会话数,人数 = 去重用户数</span>
|
||||||
|
</div>
|
||||||
|
<div ref="trendRef" class="chart-lg"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 维度统计 -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<span class="panel-title">维度统计</span>
|
||||||
|
<el-radio-group v-model="dimension" size="small" @change="loadDimension">
|
||||||
|
<el-radio-button value="ip">按 IP</el-radio-button>
|
||||||
|
<el-radio-button value="org">按单位</el-radio-button>
|
||||||
|
<el-radio-button value="account">按账号</el-radio-button>
|
||||||
|
<el-radio-button value="type">按类型</el-radio-button>
|
||||||
|
</el-radio-group>
|
||||||
|
</div>
|
||||||
|
<el-row :gutter="16">
|
||||||
|
<el-col :md="14" :xs="24">
|
||||||
|
<div ref="dimRef" class="chart-md"></div>
|
||||||
|
</el-col>
|
||||||
|
<el-col :md="10" :xs="24">
|
||||||
|
<el-table :data="dimData" border stripe max-height="360" size="small">
|
||||||
|
<el-table-column type="index" label="#" width="50" />
|
||||||
|
<el-table-column prop="name" label="维度值" min-width="120" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="count" label="人次" width="90" align="right" />
|
||||||
|
<el-table-column prop="users" label="人数" width="90" align="right" />
|
||||||
|
</el-table>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped lang="scss">
|
||||||
|
.ov-card {
|
||||||
|
position: relative;
|
||||||
|
text-align: center;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 18px 12px;
|
||||||
|
background: var(--bg-card, #fff);
|
||||||
|
border: 1px solid var(--border-soft, #e7eee9);
|
||||||
|
border-radius: 10px;
|
||||||
|
|
||||||
|
&::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 3px;
|
||||||
|
background: linear-gradient(180deg, var(--brand-gold-light, #e9c878), var(--brand-gold-deep, #8a6420));
|
||||||
|
}
|
||||||
|
|
||||||
|
.ov-label {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted, #7a8a80);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ov-count {
|
||||||
|
font-family: var(--font-serif, serif);
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--brand-primary-deep, #2f5d47);
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ov-users {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted, #7a8a80);
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
|
||||||
|
.tb-label {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted, #7a8a80);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--bg-card, #fff);
|
||||||
|
border: 1px solid var(--border-soft, #e7eee9);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
|
||||||
|
.panel-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-title {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-main, #23362c);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-sub {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted, #7a8a80);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-lg {
|
||||||
|
width: 100%;
|
||||||
|
height: 340px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-md {
|
||||||
|
width: 100%;
|
||||||
|
height: 360px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -12,7 +12,9 @@ const menuTitle: Record<string, string> = {
|
|||||||
hits: '敏感词命中处置',
|
hits: '敏感词命中处置',
|
||||||
library: '院校资源库',
|
library: '院校资源库',
|
||||||
fields: '列表字段配置',
|
fields: '列表字段配置',
|
||||||
deposit: '呈缴管理'
|
deposit: '呈缴管理',
|
||||||
|
log: '日志管理',
|
||||||
|
access: '网络访问统计'
|
||||||
}
|
}
|
||||||
const pageTitle = computed(() => menuTitle[activeMenu.value] || '后台管理')
|
const pageTitle = computed(() => menuTitle[activeMenu.value] || '后台管理')
|
||||||
|
|
||||||
@@ -43,6 +45,7 @@ import {
|
|||||||
type SensitiveWord,
|
type SensitiveWord,
|
||||||
} from '@/api/admin'
|
} from '@/api/admin'
|
||||||
import OrgUserPanel from './OrgUserPanel.vue'
|
import OrgUserPanel from './OrgUserPanel.vue'
|
||||||
|
import AccessStatsPanel from './AccessStatsPanel.vue'
|
||||||
import {
|
import {
|
||||||
acceptDeposit,
|
acceptDeposit,
|
||||||
pageDeposit,
|
pageDeposit,
|
||||||
@@ -50,6 +53,13 @@ import {
|
|||||||
type DepositQuery,
|
type DepositQuery,
|
||||||
type DepositRecord
|
type DepositRecord
|
||||||
} from '@/api/deposit'
|
} from '@/api/deposit'
|
||||||
|
import {
|
||||||
|
loginLogSummary,
|
||||||
|
pageLoginLogs,
|
||||||
|
type LoginLog,
|
||||||
|
type LoginLogQuery,
|
||||||
|
type LoginLogSummary
|
||||||
|
} from '@/api/admin'
|
||||||
|
|
||||||
// ==================== 敏感词库 ====================
|
// ==================== 敏感词库 ====================
|
||||||
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
|
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
|
||||||
@@ -438,6 +448,74 @@ function depositStatusText(status?: string) {
|
|||||||
return '待审核'
|
return '待审核'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 日志管理 ====================
|
||||||
|
const logQuery = reactive<LoginLogQuery>({ current: 1, size: 20, keyword: '', status: '', loginStart: '', loginEnd: '' })
|
||||||
|
const logList = ref<LoginLog[]>([])
|
||||||
|
const logTotal = ref(0)
|
||||||
|
const logLoading = ref(false)
|
||||||
|
const logDateRange = ref<string[]>([])
|
||||||
|
const logSummary = ref<LoginLogSummary>({ total: 0, online: 0, today: 0 })
|
||||||
|
|
||||||
|
async function fetchLogs() {
|
||||||
|
logLoading.value = true
|
||||||
|
try {
|
||||||
|
const page = await pageLoginLogs({
|
||||||
|
current: logQuery.current,
|
||||||
|
size: logQuery.size,
|
||||||
|
keyword: logQuery.keyword || undefined,
|
||||||
|
status: logQuery.status || undefined,
|
||||||
|
loginStart: logDateRange.value?.[0] || undefined,
|
||||||
|
loginEnd: logDateRange.value?.[1] || undefined,
|
||||||
|
})
|
||||||
|
logList.value = page.records || []
|
||||||
|
logTotal.value = page.total || 0
|
||||||
|
} finally {
|
||||||
|
logLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLogSummary() {
|
||||||
|
try {
|
||||||
|
logSummary.value = await loginLogSummary()
|
||||||
|
} catch {
|
||||||
|
logSummary.value = { total: 0, online: 0, today: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchLogs() {
|
||||||
|
logQuery.current = 1
|
||||||
|
fetchLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetLogFilters() {
|
||||||
|
logQuery.keyword = ''
|
||||||
|
logQuery.status = ''
|
||||||
|
logDateRange.value = []
|
||||||
|
searchLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析时间戳:兼容 "2026-11-04T10:30:00"(ISO)与 "2026-11-04 10:30:00"(空格)两种格式 */
|
||||||
|
function parseTime(s?: string | null): number {
|
||||||
|
if (!s) return 0
|
||||||
|
const d = new Date(s.replace('T', ' ').replace(/-/g, '/'))
|
||||||
|
const t = d.getTime()
|
||||||
|
return Number.isNaN(t) ? 0 : t
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在线时长:未退出按当前时间算,已退出按退出时间算 */
|
||||||
|
function onlineDuration(row: LoginLog): string {
|
||||||
|
const start = parseTime(row.loginTime)
|
||||||
|
if (!start) return '-'
|
||||||
|
const end = parseTime(row.logoutTime) || Date.now()
|
||||||
|
const mins = Math.max(0, Math.floor((end - start) / 60000))
|
||||||
|
if (mins < 60) return `${mins} 分钟`
|
||||||
|
const hours = Math.floor(mins / 60)
|
||||||
|
const rem = mins % 60
|
||||||
|
if (hours < 24) return `${hours} 小时${rem ? ' ' + rem + ' 分' : ''}`
|
||||||
|
const days = Math.floor(hours / 24)
|
||||||
|
return `${days} 天 ${hours % 24} 小时`
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
fetchWords()
|
fetchWords()
|
||||||
fetchHits()
|
fetchHits()
|
||||||
@@ -445,6 +523,8 @@ onMounted(() => {
|
|||||||
fetchStats()
|
fetchStats()
|
||||||
fetchFields()
|
fetchFields()
|
||||||
fetchDeposits()
|
fetchDeposits()
|
||||||
|
fetchLogs()
|
||||||
|
fetchLogSummary()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -468,6 +548,8 @@ onMounted(() => {
|
|||||||
<el-menu-item index="library">院校资源库</el-menu-item>
|
<el-menu-item index="library">院校资源库</el-menu-item>
|
||||||
<el-menu-item index="fields">列表字段配置</el-menu-item>
|
<el-menu-item index="fields">列表字段配置</el-menu-item>
|
||||||
<el-menu-item index="deposit">呈缴管理</el-menu-item>
|
<el-menu-item index="deposit">呈缴管理</el-menu-item>
|
||||||
|
<el-menu-item index="log">日志管理</el-menu-item>
|
||||||
|
<el-menu-item index="access">网络访问统计</el-menu-item>
|
||||||
</el-menu>
|
</el-menu>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
@@ -780,6 +862,90 @@ onMounted(() => {
|
|||||||
@current-change="fetchDeposits"
|
@current-change="fetchDeposits"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- ==================== 日志管理 ==================== -->
|
||||||
|
<div v-show="activeMenu === 'log'">
|
||||||
|
<div class="log-summary">
|
||||||
|
<div class="log-card">
|
||||||
|
<div class="log-card__num">{{ logSummary.total }}</div>
|
||||||
|
<div class="log-card__label">会话总数</div>
|
||||||
|
</div>
|
||||||
|
<div class="log-card log-card--online">
|
||||||
|
<div class="log-card__num">{{ logSummary.online }}</div>
|
||||||
|
<div class="log-card__label">当前在线</div>
|
||||||
|
</div>
|
||||||
|
<div class="log-card log-card--today">
|
||||||
|
<div class="log-card__num">{{ logSummary.today }}</div>
|
||||||
|
<div class="log-card__label">今日登录</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-input
|
||||||
|
v-model="logQuery.keyword"
|
||||||
|
placeholder="账号 / 姓名 / 单位"
|
||||||
|
clearable
|
||||||
|
style="width: 220px"
|
||||||
|
@keyup.enter="searchLogs"
|
||||||
|
@clear="searchLogs"
|
||||||
|
/>
|
||||||
|
<el-select v-model="logQuery.status" placeholder="全部状态" clearable style="width: 130px" @change="searchLogs">
|
||||||
|
<el-option label="在线" value="ONLINE" />
|
||||||
|
<el-option label="离线" value="OFFLINE" />
|
||||||
|
</el-select>
|
||||||
|
<el-date-picker
|
||||||
|
v-model="logDateRange"
|
||||||
|
type="daterange"
|
||||||
|
:editable="false"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="登录起"
|
||||||
|
end-placeholder="登录止"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 260px"
|
||||||
|
@change="searchLogs"
|
||||||
|
/>
|
||||||
|
<el-button type="primary" @click="searchLogs">查询</el-button>
|
||||||
|
<el-button @click="resetLogFilters">重置</el-button>
|
||||||
|
<el-button @click="fetchLogSummary">刷新概览</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-table v-loading="logLoading" :data="logList" border stripe>
|
||||||
|
<el-table-column type="index" label="#" width="50" />
|
||||||
|
<el-table-column prop="username" label="账号" width="140" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="realName" label="姓名" width="120" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="orgName" label="单位" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="ip" label="登录IP" width="140" />
|
||||||
|
<el-table-column prop="loginTime" label="登录时间" width="180" />
|
||||||
|
<el-table-column label="退出时间" width="180">
|
||||||
|
<template #default="{ row }">{{ row.logoutTime || '—' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="在线时长" width="140">
|
||||||
|
<template #default="{ row }">{{ onlineDuration(row) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small" :type="row.logoutTime ? 'info' : 'success'">
|
||||||
|
{{ row.logoutTime ? '离线' : '在线' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<el-pagination
|
||||||
|
class="pager"
|
||||||
|
background
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
:total="logTotal"
|
||||||
|
v-model:current-page="logQuery.current"
|
||||||
|
v-model:page-size="logQuery.size"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
@current-change="fetchLogs"
|
||||||
|
@size-change="fetchLogs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ==================== 网络访问统计 ==================== -->
|
||||||
|
<AccessStatsPanel v-if="activeMenu === 'access'" />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 敏感词 新增/编辑 弹窗 -->
|
<!-- 敏感词 新增/编辑 弹窗 -->
|
||||||
@@ -974,4 +1140,51 @@ onMounted(() => {
|
|||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.log-summary {
|
||||||
|
display: flex;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card {
|
||||||
|
min-width: 150px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border: 1px solid var(--card-gold-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--brand-light);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card__num {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-main);
|
||||||
|
font-family: var(--font-serif);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card__label {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--online {
|
||||||
|
background: #e8f5e9;
|
||||||
|
border-color: #b7dfc1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--online .log-card__num {
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--today {
|
||||||
|
background: #eaf2fb;
|
||||||
|
border-color: #bcd4ef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--today .log-card__num {
|
||||||
|
color: #1565c0;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, reactive, ref } from 'vue'
|
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import {
|
import {
|
||||||
createOrg,
|
createOrg,
|
||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
type UserImportResult,
|
type UserImportResult,
|
||||||
type UserItem
|
type UserItem
|
||||||
} from '@/api/system'
|
} from '@/api/system'
|
||||||
|
import { NAV_MENUS, navTitle } from '@/constants/nav'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
section: 'org' | 'role' | 'user'
|
section: 'org' | 'role' | 'user'
|
||||||
@@ -42,12 +43,26 @@ const orgForm = reactive<OrgSave & { id?: number }>({
|
|||||||
const roles = ref<RoleItem[]>([])
|
const roles = ref<RoleItem[]>([])
|
||||||
const roleDialog = ref(false)
|
const roleDialog = ref(false)
|
||||||
const roleSaving = ref(false)
|
const roleSaving = ref(false)
|
||||||
const roleForm = reactive<{ id?: number; code: string; name: string; remark: string; status: number; builtin?: number }>({
|
const roleForm = reactive<{ id?: number; code: string; name: string; remark: string; status: number; builtin?: number; menuCodes: string[] }>({
|
||||||
code: '',
|
code: '',
|
||||||
name: '',
|
name: '',
|
||||||
remark: '',
|
remark: '',
|
||||||
status: 1
|
status: 1,
|
||||||
|
menuCodes: NAV_MENUS.map((menu) => menu.code)
|
||||||
})
|
})
|
||||||
|
const isAdminRole = computed(() => roleForm.code.trim().toUpperCase() === 'ADMIN')
|
||||||
|
const allMenuCodes = () => NAV_MENUS.map((menu) => menu.code)
|
||||||
|
const roleChoices = computed(() => {
|
||||||
|
return [...roles.value].sort((a, b) => {
|
||||||
|
const rank = (code?: string) => (code || '').toUpperCase() === 'USER' ? 0 : 1
|
||||||
|
return rank(a.code) - rank(b.code)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
function userRoleId() {
|
||||||
|
const role = roles.value.find((item) => (item.code || '').toUpperCase() === 'USER')
|
||||||
|
return role ? Number(role.id) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
const userQuery = reactive<{ current: number; size: number; keyword: string; orgId?: number; roleId?: number }>({
|
const userQuery = reactive<{ current: number; size: number; keyword: string; orgId?: number; roleId?: number }>({
|
||||||
current: 1,
|
current: 1,
|
||||||
@@ -170,6 +185,7 @@ function openRoleCreate() {
|
|||||||
roleForm.remark = ''
|
roleForm.remark = ''
|
||||||
roleForm.status = 1
|
roleForm.status = 1
|
||||||
roleForm.builtin = 0
|
roleForm.builtin = 0
|
||||||
|
roleForm.menuCodes = allMenuCodes()
|
||||||
roleDialog.value = true
|
roleDialog.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,6 +196,9 @@ function openRoleEdit(row: RoleItem) {
|
|||||||
roleForm.remark = row.remark || ''
|
roleForm.remark = row.remark || ''
|
||||||
roleForm.status = row.status ?? 1
|
roleForm.status = row.status ?? 1
|
||||||
roleForm.builtin = row.builtin
|
roleForm.builtin = row.builtin
|
||||||
|
roleForm.menuCodes = row.code === 'ADMIN'
|
||||||
|
? allMenuCodes()
|
||||||
|
: (row.menuCodes ? [...row.menuCodes] : allMenuCodes())
|
||||||
roleDialog.value = true
|
roleDialog.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +213,8 @@ async function saveRole() {
|
|||||||
code: roleForm.code.trim(),
|
code: roleForm.code.trim(),
|
||||||
name: roleForm.name.trim(),
|
name: roleForm.name.trim(),
|
||||||
remark: roleForm.remark.trim() || undefined,
|
remark: roleForm.remark.trim() || undefined,
|
||||||
status: roleForm.status
|
status: roleForm.status,
|
||||||
|
menuCodes: isAdminRole.value ? allMenuCodes() : [...roleForm.menuCodes]
|
||||||
}
|
}
|
||||||
if (roleForm.id) {
|
if (roleForm.id) {
|
||||||
await updateRole(roleForm.id, data)
|
await updateRole(roleForm.id, data)
|
||||||
@@ -216,18 +236,39 @@ async function deleteRole(row: RoleItem) {
|
|||||||
loadRoles()
|
loadRoles()
|
||||||
}
|
}
|
||||||
|
|
||||||
function openUserCreate() {
|
async function openUserCreate() {
|
||||||
|
try {
|
||||||
|
await loadRoles()
|
||||||
|
} catch {
|
||||||
|
// 角色列表失败时仍打开弹窗,下面会提示先去角色管理新增
|
||||||
|
}
|
||||||
userForm.id = undefined
|
userForm.id = undefined
|
||||||
userForm.username = ''
|
userForm.username = ''
|
||||||
userForm.password = ''
|
userForm.password = ''
|
||||||
userForm.realName = ''
|
userForm.realName = ''
|
||||||
userForm.roleId = roles.value.find((role) => role.code === 'USER')?.id
|
|
||||||
userForm.orgId = undefined
|
userForm.orgId = undefined
|
||||||
userForm.status = 1
|
userForm.status = 1
|
||||||
|
userForm.roleId = userRoleId()
|
||||||
userDialog.value = true
|
userDialog.value = true
|
||||||
|
await nextTick()
|
||||||
|
if (!userForm.id) {
|
||||||
|
userForm.roleId = userRoleId()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function openUserEdit(row: UserItem) {
|
function onUserDialogOpened() {
|
||||||
|
if (userForm.id || userForm.roleId) return
|
||||||
|
userForm.roleId = userRoleId()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openUserEdit(row: UserItem) {
|
||||||
|
if (!roles.value.length) {
|
||||||
|
try {
|
||||||
|
await loadRoles()
|
||||||
|
} catch {
|
||||||
|
// 沿用已有列表
|
||||||
|
}
|
||||||
|
}
|
||||||
userForm.id = row.id
|
userForm.id = row.id
|
||||||
userForm.username = row.username
|
userForm.username = row.username
|
||||||
userForm.password = ''
|
userForm.password = ''
|
||||||
@@ -239,6 +280,9 @@ function openUserEdit(row: UserItem) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function saveUser() {
|
async function saveUser() {
|
||||||
|
if (!userForm.id && !userForm.roleId) {
|
||||||
|
userForm.roleId = userRoleId()
|
||||||
|
}
|
||||||
if (!userForm.username.trim() || !userForm.realName.trim() || !userForm.roleId) {
|
if (!userForm.username.trim() || !userForm.realName.trim() || !userForm.roleId) {
|
||||||
ElMessage.warning('请填写账号、姓名并选择角色')
|
ElMessage.warning('请填写账号、姓名并选择角色')
|
||||||
return
|
return
|
||||||
@@ -381,7 +425,12 @@ onMounted(() => {
|
|||||||
</el-tag>
|
</el-tag>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
|
<el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column label="可见栏目" min-width="220" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ (row.menuCodes || []).map((code: string) => navTitle(code)).join('、') || '无' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
<el-table-column label="操作" width="140">
|
<el-table-column label="操作" width="140">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-button link type="primary" size="small" @click="openRoleEdit(row)">编辑</el-button>
|
<el-button link type="primary" size="small" @click="openRoleEdit(row)">编辑</el-button>
|
||||||
@@ -495,7 +544,7 @@ onMounted(() => {
|
|||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
<el-dialog v-model="roleDialog" :title="roleForm.id ? '编辑角色' : '新增角色'" width="480px">
|
<el-dialog v-model="roleDialog" :title="roleForm.id ? '编辑角色' : '新增角色'" width="560px">
|
||||||
<el-form label-width="88px">
|
<el-form label-width="88px">
|
||||||
<el-form-item label="编码" required>
|
<el-form-item label="编码" required>
|
||||||
<el-input v-model="roleForm.code" maxlength="32" :disabled="roleForm.builtin === 1" placeholder="如 EDITOR" />
|
<el-input v-model="roleForm.code" maxlength="32" :disabled="roleForm.builtin === 1" placeholder="如 EDITOR" />
|
||||||
@@ -509,6 +558,16 @@ onMounted(() => {
|
|||||||
<el-radio :value="0">停用</el-radio>
|
<el-radio :value="0">停用</el-radio>
|
||||||
</el-radio-group>
|
</el-radio-group>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
<el-form-item label="可见栏目">
|
||||||
|
<el-checkbox-group v-model="roleForm.menuCodes" class="nav-checks" :disabled="isAdminRole">
|
||||||
|
<el-checkbox v-for="menu in NAV_MENUS" :key="menu.code" :value="menu.code">
|
||||||
|
{{ menu.title }}
|
||||||
|
</el-checkbox>
|
||||||
|
</el-checkbox-group>
|
||||||
|
<div class="form-tip">
|
||||||
|
{{ isAdminRole ? '系统管理员默认可访问全部栏目' : '未勾选的栏目不会出现在该角色用户的顶部导航中,后台管理也在其中' }}
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
<el-form-item label="备注">
|
<el-form-item label="备注">
|
||||||
<el-input v-model="roleForm.remark" type="textarea" maxlength="256" />
|
<el-input v-model="roleForm.remark" type="textarea" maxlength="256" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
@@ -519,7 +578,7 @@ onMounted(() => {
|
|||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
<el-dialog v-model="userDialog" :title="userForm.id ? '编辑用户' : '新增用户'" width="480px">
|
<el-dialog v-model="userDialog" :title="userForm.id ? '编辑用户' : '新增用户'" width="480px" @opened="onUserDialogOpened">
|
||||||
<el-form label-width="88px">
|
<el-form label-width="88px">
|
||||||
<el-form-item label="登录账号" required>
|
<el-form-item label="登录账号" required>
|
||||||
<el-input v-model="userForm.username" maxlength="64" />
|
<el-input v-model="userForm.username" maxlength="64" />
|
||||||
@@ -537,9 +596,11 @@ onMounted(() => {
|
|||||||
/>
|
/>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="角色" required>
|
<el-form-item label="角色" required>
|
||||||
<el-select v-model="userForm.roleId" style="width: 100%">
|
<el-radio-group v-if="roleChoices.length" v-model="userForm.roleId" class="role-picks">
|
||||||
<el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
|
<el-radio v-for="role in roleChoices" :key="role.id" :value="Number(role.id)">{{ role.name }}</el-radio>
|
||||||
</el-select>
|
</el-radio-group>
|
||||||
|
<div v-if="!userForm.id && roleChoices.length" class="form-tip">新增用户默认是普通用户</div>
|
||||||
|
<div v-else-if="!roleChoices.length" class="form-tip">暂无角色,请先在角色管理中新增</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="组织">
|
<el-form-item label="组织">
|
||||||
<el-tree-select
|
<el-tree-select
|
||||||
@@ -581,4 +642,24 @@ onMounted(() => {
|
|||||||
margin-top: 12px;
|
margin-top: 12px;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.nav-checks {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-tip {
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picks {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px 16px;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
import * as echarts from 'echarts'
|
import * as echarts from 'echarts'
|
||||||
import {
|
import {
|
||||||
getHotKeywords,
|
getHotKeywords,
|
||||||
@@ -15,6 +15,10 @@ import type { FacetItem, YearStat } from '@/api/search'
|
|||||||
const overview = ref<AnalysisOverview | null>(null)
|
const overview = ref<AnalysisOverview | null>(null)
|
||||||
const hotKeywords = ref<FacetItem[]>([])
|
const hotKeywords = ref<FacetItem[]>([])
|
||||||
const recent = ref<YearStat[]>([])
|
const recent = ref<YearStat[]>([])
|
||||||
|
const resourceRatio = ref<FacetItem[]>([])
|
||||||
|
const libraryContribution = ref<FacetItem[]>([])
|
||||||
|
const ratioTotal = computed(() => resourceRatio.value.reduce((s, r) => s + r.value, 0))
|
||||||
|
const contribTotal = computed(() => libraryContribution.value.reduce((s, r) => s + r.value, 0))
|
||||||
|
|
||||||
const ratioRef = ref<HTMLElement>()
|
const ratioRef = ref<HTMLElement>()
|
||||||
const yearRef = ref<HTMLElement>()
|
const yearRef = ref<HTMLElement>()
|
||||||
@@ -49,15 +53,17 @@ async function loadAll() {
|
|||||||
const tip = { textStyle: { fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif', color: paper } }
|
const tip = { textStyle: { fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif', color: paper } }
|
||||||
|
|
||||||
const ratio = await getResourceRatio()
|
const ratio = await getResourceRatio()
|
||||||
|
resourceRatio.value = ratio
|
||||||
initChart(ratioRef.value)?.setOption({
|
initChart(ratioRef.value)?.setOption({
|
||||||
color: [ink, gold, leaf, goldDeep, mist, cssVar('--brand-light', '#eaf4ed')],
|
color: [ink, gold, leaf, goldDeep, mist, cssVar('--brand-light', '#eaf4ed')],
|
||||||
tooltip: { trigger: 'item', ...tip },
|
tooltip: { trigger: 'item', formatter: '{b}<br/>数量:{c} ({d}%)', ...tip },
|
||||||
legend: { bottom: 0, textStyle: { color: paper } },
|
legend: { bottom: 0, textStyle: { color: paper } },
|
||||||
series: [
|
series: [
|
||||||
{
|
{
|
||||||
name: '资源比例',
|
name: '资源比例',
|
||||||
type: 'pie',
|
type: 'pie',
|
||||||
radius: ['40%', '65%'],
|
radius: ['40%', '65%'],
|
||||||
|
label: { color: paper, formatter: '{b}\n{c} ({d}%)' },
|
||||||
data: ratio.map((r) => ({ name: r.name, value: r.value }))
|
data: ratio.map((r) => ({ name: r.name, value: r.value }))
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -90,6 +96,7 @@ async function loadAll() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const contrib = await getLibraryContribution()
|
const contrib = await getLibraryContribution()
|
||||||
|
libraryContribution.value = contrib
|
||||||
initChart(contribRef.value)?.setOption({
|
initChart(contribRef.value)?.setOption({
|
||||||
tooltip: { trigger: 'axis', ...tip },
|
tooltip: { trigger: 'axis', ...tip },
|
||||||
grid: { left: 45, right: 20, top: 30, bottom: 60 },
|
grid: { left: 45, right: 20, top: 30, bottom: 60 },
|
||||||
@@ -188,14 +195,34 @@ onBeforeUnmount(() => {
|
|||||||
<el-row :gutter="16" class="mb-16">
|
<el-row :gutter="16" class="mb-16">
|
||||||
<el-col :xs="24" :md="12">
|
<el-col :xs="24" :md="12">
|
||||||
<div class="page-card">
|
<div class="page-card">
|
||||||
<h3 class="page-title">版本资源综合比例</h3>
|
<h3 class="page-title">版本资源综合比例(纸质 / 电子)</h3>
|
||||||
<div ref="ratioRef" class="chart-sm"></div>
|
<div ref="ratioRef" class="chart-sm"></div>
|
||||||
|
<el-table :data="resourceRatio" size="small" class="pct-table" :border="false">
|
||||||
|
<el-table-column prop="name" label="资源类型" />
|
||||||
|
<el-table-column prop="value" label="数量" align="right" />
|
||||||
|
<el-table-column label="所占比例" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ ratioTotal ? ((row.value / ratioTotal) * 100).toFixed(1) : '0.0' }}%
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div class="pct-total">合计:{{ ratioTotal.toLocaleString() }} 条</div>
|
||||||
</div>
|
</div>
|
||||||
</el-col>
|
</el-col>
|
||||||
<el-col :xs="24" :md="12">
|
<el-col :xs="24" :md="12">
|
||||||
<div class="page-card">
|
<div class="page-card">
|
||||||
<h3 class="page-title">来源单位贡献量</h3>
|
<h3 class="page-title">各馆版本资源数量及占比</h3>
|
||||||
<div ref="contribRef" class="chart-sm"></div>
|
<div ref="contribRef" class="chart-sm"></div>
|
||||||
|
<el-table :data="libraryContribution" size="small" class="pct-table" max-height="240" :border="false">
|
||||||
|
<el-table-column prop="name" label="来源馆 / 院校" />
|
||||||
|
<el-table-column prop="value" label="数量(条)" align="right" />
|
||||||
|
<el-table-column label="占比" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ contribTotal ? ((row.value / contribTotal) * 100).toFixed(1) : '0.0' }}%
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div class="pct-total">合计:{{ contribTotal.toLocaleString() }} 条</div>
|
||||||
</div>
|
</div>
|
||||||
</el-col>
|
</el-col>
|
||||||
</el-row>
|
</el-row>
|
||||||
@@ -251,4 +278,21 @@ onBeforeUnmount(() => {
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
height: 280px;
|
height: 280px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.pct-table {
|
||||||
|
margin-top: 8px;
|
||||||
|
|
||||||
|
:deep(.el-table__header th),
|
||||||
|
:deep(.el-table__cell) {
|
||||||
|
background: transparent;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.pct-total {
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -70,13 +70,47 @@ const saving = ref(false)
|
|||||||
const formRef = ref<FormInstance | null>(null)
|
const formRef = ref<FormInstance | null>(null)
|
||||||
const editForm = ref<VersionResource>({ title: '' } as VersionResource)
|
const editForm = ref<VersionResource>({ title: '' } as VersionResource)
|
||||||
|
|
||||||
const rules: FormRules = {
|
// 必备(必填)字段:新增时强制校验完整性
|
||||||
|
const REQUIRED_FIELDS: Array<[keyof VersionResource, string]> = [
|
||||||
|
['processNo', '加工编号'],
|
||||||
|
['title', '正题名'],
|
||||||
|
['clcCode', '中图分类'],
|
||||||
|
['keywords', '主题词或关键词'],
|
||||||
|
['summary', '摘要'],
|
||||||
|
['publishYear', '出版年份'],
|
||||||
|
['processDate', '加工日期'],
|
||||||
|
['contentForm', '内容形式'],
|
||||||
|
['mediaType', '媒体类型'],
|
||||||
|
['format', '格式'],
|
||||||
|
['pageCount', '页码'],
|
||||||
|
['language', '语种'],
|
||||||
|
['submitOrg', '数据提交单位'],
|
||||||
|
['taskYear', '所属任务年份'],
|
||||||
|
['sourceLibrary', '来源馆'],
|
||||||
|
['sourceLibraryAddr', '来源馆地址'],
|
||||||
|
['fulltextUrl', '全文地址']
|
||||||
|
]
|
||||||
|
|
||||||
|
function buildRequiredRules(): FormRules {
|
||||||
|
const r: FormRules = {}
|
||||||
|
for (const [key, label] of REQUIRED_FIELDS) {
|
||||||
|
r[key] = [{ required: true, message: `请填写${label}`, trigger: ['blur', 'change'] }]
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// 编辑时仅校验正题名(避免历史不完整数据无法保存);新增时校验全部必备字段
|
||||||
|
const editRules: FormRules = {
|
||||||
title: [{ required: true, message: '请输入正题名', trigger: 'blur' }]
|
title: [{ required: true, message: '请输入正题名', trigger: 'blur' }]
|
||||||
}
|
}
|
||||||
|
const createRules = buildRequiredRules()
|
||||||
|
const rules = ref<FormRules>(editRules)
|
||||||
|
|
||||||
async function openEdit(row: VersionResource) {
|
async function openEdit(row: VersionResource) {
|
||||||
drawerVisible.value = true
|
drawerVisible.value = true
|
||||||
detailLoading.value = true
|
detailLoading.value = true
|
||||||
|
rules.value = editRules
|
||||||
|
formRef.value?.clearValidate()
|
||||||
editForm.value = { title: row.title } as VersionResource
|
editForm.value = { title: row.title } as VersionResource
|
||||||
try {
|
try {
|
||||||
// 拉取完整元数据,避免表格行缺字段
|
// 拉取完整元数据,避免表格行缺字段
|
||||||
@@ -87,7 +121,7 @@ async function openEdit(row: VersionResource) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 新增:复用编辑抽屉,空表单(不带 id,保存时后端走新增) */
|
/** 新增:复用编辑抽屉,空表单(不带 id,保存时后端走新增),加载必备字段校验规则 */
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
editForm.value = {
|
editForm.value = {
|
||||||
title: '',
|
title: '',
|
||||||
@@ -98,12 +132,18 @@ function openCreate() {
|
|||||||
isSpecial: 0
|
isSpecial: 0
|
||||||
} as VersionResource
|
} as VersionResource
|
||||||
detailLoading.value = false
|
detailLoading.value = false
|
||||||
|
rules.value = createRules
|
||||||
|
formRef.value?.clearValidate()
|
||||||
drawerVisible.value = true
|
drawerVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveEdit() {
|
async function saveEdit() {
|
||||||
if (!formRef.value) return
|
if (!formRef.value) return
|
||||||
|
try {
|
||||||
await formRef.value.validate()
|
await formRef.value.validate()
|
||||||
|
} catch {
|
||||||
|
return // 校验未通过,终止保存
|
||||||
|
}
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
// id 有值 → 后端走更新;isSpecial 随表单一起保存(1是 0否)
|
// id 有值 → 后端走更新;isSpecial 随表单一起保存(1是 0否)
|
||||||
@@ -226,11 +266,9 @@ onMounted(fetchData)
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="table-scroll-x">
|
|
||||||
<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" fixed="left" />
|
<el-table-column type="index" label="#" width="50" />
|
||||||
<el-table-column prop="processNo" label="加工编号*" width="140" show-overflow-tooltip />
|
<el-table-column prop="title" label="正题名" min-width="200" show-overflow-tooltip>
|
||||||
<el-table-column prop="title" label="正题名*" min-width="200" show-overflow-tooltip>
|
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-tag v-if="row.isSpecial === 1" size="small" class="special-tag" effect="dark">
|
<el-tag v-if="row.isSpecial === 1" size="small" class="special-tag" effect="dark">
|
||||||
特藏
|
特藏
|
||||||
@@ -238,36 +276,11 @@ onMounted(fetchData)
|
|||||||
<span>{{ row.title }}</span>
|
<span>{{ row.title }}</span>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="otherTitle" label="其他题名" width="140" show-overflow-tooltip />
|
<el-table-column prop="author" label="责任者" width="140" show-overflow-tooltip />
|
||||||
<el-table-column prop="author" label="责任者名称" width="140" show-overflow-tooltip />
|
<el-table-column prop="clcCode" label="中图分类" width="110" />
|
||||||
<el-table-column prop="responsibility" label="责任方式" width="100" show-overflow-tooltip />
|
<el-table-column prop="mediaType" label="媒体类型" width="90" />
|
||||||
<el-table-column prop="clcCode" label="中图分类*" width="110" />
|
<el-table-column prop="publishYear" label="出版年份" width="100" />
|
||||||
<el-table-column prop="keywords" label="主题词或关键词*" min-width="160" show-overflow-tooltip />
|
<el-table-column prop="sourceLibrary" label="来源馆" width="180" show-overflow-tooltip />
|
||||||
<el-table-column prop="summary" label="摘要*" min-width="220" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="note" label="附注" min-width="180" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="publisher" label="出版者名称" width="160" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="publishPlace" label="出版地" width="110" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="publishDate" label="出版日期" width="120" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="publishYear" label="出版年份*" width="100" />
|
|
||||||
<el-table-column prop="processDate" label="加工日期*" width="120" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="contentForm" label="内容形式*" width="120" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="mediaType" label="媒体类型*" width="90" />
|
|
||||||
<el-table-column prop="format" label="格式*" width="100" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="pageCount" label="页码*" width="110" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="language" label="语种*" width="80" />
|
|
||||||
<el-table-column prop="relation" label="关联" min-width="160" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="timeRange" label="时间范围" width="130" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="spaceRange" label="空间范围" width="130" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="edition" label="版本" width="110" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="isbn" label="ISBN" width="160" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="unifiedBookNo" label="统一书号" width="140" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="cdoi" label="CDOI" min-width="200" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="publishUrl" label="发布地址" min-width="200" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="submitOrg" label="数据提交单位*" width="160" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="taskYear" label="所属任务年份*" width="120" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="sourceLibrary" label="来源馆*" width="180" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="sourceLibraryAddr" label="来源馆地址*" width="160" show-overflow-tooltip />
|
|
||||||
<el-table-column prop="fulltextUrl" label="全文地址*" min-width="220" show-overflow-tooltip />
|
|
||||||
<el-table-column label="治理状态" width="110">
|
<el-table-column label="治理状态" width="110">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-tag size="small" :type="governStatusTagType(row.governStatus)">
|
<el-tag size="small" :type="governStatusTagType(row.governStatus)">
|
||||||
@@ -288,7 +301,6 @@ onMounted(fetchData)
|
|||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
</el-table>
|
</el-table>
|
||||||
</div>
|
|
||||||
|
|
||||||
<el-pagination
|
<el-pagination
|
||||||
class="pager"
|
class="pager"
|
||||||
@@ -317,120 +329,94 @@ onMounted(fetchData)
|
|||||||
label-width="110px"
|
label-width="110px"
|
||||||
label-position="right"
|
label-position="right"
|
||||||
>
|
>
|
||||||
<el-divider content-position="left">著录要素(按采集标准顺序)</el-divider>
|
<el-divider content-position="left">基本信息</el-divider>
|
||||||
<div class="form-grid">
|
<div class="form-grid">
|
||||||
<el-form-item label="加工编号" prop="processNo">
|
|
||||||
<el-input v-model="editForm.processNo" placeholder="著录资源的加工编号" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="正题名" prop="title">
|
<el-form-item label="正题名" prop="title">
|
||||||
<el-input v-model="editForm.title" placeholder="资源主要名称(必备)" />
|
<el-input v-model="editForm.title" placeholder="请输入正题名" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="其他题名">
|
<el-form-item label="加工编号" prop="processNo">
|
||||||
<el-input v-model="editForm.otherTitle" placeholder="其他语种题名或限定/补充题名" />
|
<el-input v-model="editForm.processNo" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="责任者名称">
|
<el-form-item label="责任者">
|
||||||
<el-input v-model="editForm.author" placeholder="主要责任者或贡献者,多人用 ; 分隔" />
|
<el-input v-model="editForm.author" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="责任方式">
|
<el-form-item label="责任方式">
|
||||||
<el-input v-model="editForm.responsibility" placeholder="如 著、编、译、主编" />
|
<el-input v-model="editForm.responsibility" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="中图分类">
|
<el-form-item label="中图分类" prop="clcCode">
|
||||||
<el-input v-model="editForm.clcCode" placeholder="CLC第五版类号,如 G250.7" />
|
<el-input v-model="editForm.clcCode" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="主题词或关键词">
|
<el-form-item label="媒体类型" prop="mediaType">
|
||||||
<el-input v-model="editForm.keywords" placeholder="多个用 ; 分隔,受控词依 CCT 标引" />
|
<el-select v-model="editForm.mediaType" style="width: 100%">
|
||||||
</el-form-item>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<el-form-item label="摘要">
|
|
||||||
<el-input v-model="editForm.summary" type="textarea" :rows="4" placeholder="自由行文概括描述,建议不少于 100 字(必备)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="附注">
|
|
||||||
<el-input v-model="editForm.note" type="textarea" :rows="3" placeholder="其他补充说明,版权信息著录于此,不同类型信息重复本字段" />
|
|
||||||
</el-form-item>
|
|
||||||
|
|
||||||
<el-divider content-position="left">出版与版本</el-divider>
|
|
||||||
<div class="form-grid">
|
|
||||||
<el-form-item label="出版者名称">
|
|
||||||
<el-input v-model="editForm.publisher" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="出版地">
|
|
||||||
<el-input v-model="editForm.publishPlace" placeholder="出版者所在城市,不详可著录省名或国名" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="出版日期">
|
|
||||||
<el-input v-model="editForm.publishDate" placeholder="如 2026-01-01 或 2026" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="出版年份">
|
|
||||||
<el-input v-model="editForm.publishYear" placeholder="yyyy(必备)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="加工日期">
|
|
||||||
<el-input v-model="editForm.processDate" placeholder="yyyyMMdd(必备)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="内容形式">
|
|
||||||
<el-input v-model="editForm.contentForm" placeholder="GB/T 3469-2013,如 文本、图像(测绘型)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="媒体类型">
|
|
||||||
<el-select v-model="editForm.mediaType" style="width: 100%" placeholder="纸质 或 电子(必备)">
|
|
||||||
<el-option label="纸质" value="纸质" />
|
<el-option label="纸质" value="纸质" />
|
||||||
<el-option label="电子" value="电子" />
|
<el-option label="电子" value="电子" />
|
||||||
</el-select>
|
</el-select>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="格式">
|
<el-form-item label="出版年份" prop="publishYear">
|
||||||
<el-input v-model="editForm.format" placeholder="英文大写,如 TIF;PDF(必备)" />
|
<el-input v-model="editForm.publishYear" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="页码">
|
<el-form-item label="出版日期">
|
||||||
<el-input v-model="editForm.pageCount" placeholder="如 2 册(116 页)、132-423 页(必备)" />
|
<el-input v-model="editForm.publishDate" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="语种">
|
<el-form-item label="出版者">
|
||||||
<el-input v-model="editForm.language" placeholder="3 位语种代码,如 chi(必备)" />
|
<el-input v-model="editForm.publisher" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</div>
|
<el-form-item label="出版地">
|
||||||
|
<el-input v-model="editForm.publishPlace" />
|
||||||
<el-divider content-position="left">关联与标识</el-divider>
|
|
||||||
<div class="form-grid">
|
|
||||||
<el-form-item label="关联">
|
|
||||||
<el-input v-model="editForm.relation" placeholder="相关资源名称或标识符,如丛编、合订" />
|
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="时间范围">
|
<el-form-item label="内容形式" prop="contentForm">
|
||||||
<el-input v-model="editForm.timeRange" placeholder="内容涉及的时代/日期/时间段" />
|
<el-input v-model="editForm.contentForm" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="空间范围">
|
<el-form-item label="格式" prop="format">
|
||||||
<el-input v-model="editForm.spaceRange" placeholder="内容涉及的地点/地理坐标" />
|
<el-input v-model="editForm.format" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="版本">
|
<el-form-item label="页码" prop="pageCount">
|
||||||
<el-input v-model="editForm.edition" placeholder="如 修订版、影印本、第3版" />
|
<el-input v-model="editForm.pageCount" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="语种" prop="language">
|
||||||
|
<el-input v-model="editForm.language" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="其他题名">
|
||||||
|
<el-input v-model="editForm.otherTitle" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="版本/版次">
|
||||||
|
<el-input v-model="editForm.edition" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="ISBN">
|
<el-form-item label="ISBN">
|
||||||
<el-input v-model="editForm.isbn" />
|
<el-input v-model="editForm.isbn" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="统一书号">
|
<el-form-item label="主题词" prop="keywords">
|
||||||
<el-input v-model="editForm.unifiedBookNo" />
|
<el-input v-model="editForm.keywords" placeholder="多个主题词用 ; 分隔" />
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="CDOI">
|
|
||||||
<el-input v-model="editForm.cdoi" placeholder="数字对象唯一标识" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="发布地址">
|
|
||||||
<el-input v-model="editForm.publishUrl" placeholder="因特网或局域网发布地址" />
|
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<el-form-item label="摘要" prop="summary">
|
||||||
|
<el-input v-model="editForm.summary" type="textarea" :rows="4" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="附注">
|
||||||
|
<el-input v-model="editForm.note" type="textarea" :rows="3" placeholder="附注内容将展示在特藏推荐模块" />
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
<el-divider content-position="left">来源信息</el-divider>
|
<el-divider content-position="left">来源信息</el-divider>
|
||||||
<div class="form-grid">
|
<div class="form-grid">
|
||||||
<el-form-item label="数据提交单位">
|
<el-form-item label="来源馆" prop="sourceLibrary">
|
||||||
<el-input v-model="editForm.submitOrg" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="所属任务年份">
|
|
||||||
<el-input v-model="editForm.taskYear" placeholder="yyyy(必备)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="来源馆">
|
|
||||||
<el-input v-model="editForm.sourceLibrary" />
|
<el-input v-model="editForm.sourceLibrary" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="来源馆地址">
|
<el-form-item label="来源馆地址" prop="sourceLibraryAddr">
|
||||||
<el-input v-model="editForm.sourceLibraryAddr" placeholder="IP:端口 或 域名(必备)" />
|
<el-input v-model="editForm.sourceLibraryAddr" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="数据提交单位" prop="submitOrg">
|
||||||
|
<el-input v-model="editForm.submitOrg" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="任务年份" prop="taskYear">
|
||||||
|
<el-input v-model="editForm.taskYear" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="加工日期" prop="processDate">
|
||||||
|
<el-input v-model="editForm.processDate" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</div>
|
</div>
|
||||||
<el-form-item label="全文地址">
|
<el-form-item label="全文地址" prop="fulltextUrl">
|
||||||
<el-input v-model="editForm.fulltextUrl" placeholder="根据 CDOI 生成,下载全文地址(必备)" />
|
<el-input v-model="editForm.fulltextUrl" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
<el-divider content-position="left">特藏设置</el-divider>
|
<el-divider content-position="left">特藏设置</el-divider>
|
||||||
@@ -515,16 +501,6 @@ onMounted(fetchData)
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 宽表横向滚动:32 个著录字段总宽超出视口时,可左右滚动完整查看,表头与 # / 操作列冻结 */
|
|
||||||
.table-scroll-x {
|
|
||||||
width: 100%;
|
|
||||||
overflow-x: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.table-scroll-x .el-table {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 导入结果 */
|
/* 导入结果 */
|
||||||
.imp-summary {
|
.imp-summary {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ElMessage } from 'element-plus'
|
|||||||
import * as XLSX from 'xlsx'
|
import * as XLSX from 'xlsx'
|
||||||
import { listFields, type ListFieldConfig } from '@/api/admin'
|
import { listFields, type ListFieldConfig } from '@/api/admin'
|
||||||
import { getSearchDetail, getSimilar, unifiedSearch, searchList, clcTree, type ClcNode, type FacetItem, type SearchQuery } from '@/api/search'
|
import { getSearchDetail, getSimilar, unifiedSearch, searchList, clcTree, type ClcNode, type FacetItem, type SearchQuery } from '@/api/search'
|
||||||
import type { VersionResource } from '@/api/resource'
|
import type { VersionResource, ResourceSource } from '@/api/resource'
|
||||||
import ClcTree from './ClcTree.vue'
|
import ClcTree from './ClcTree.vue'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
@@ -16,6 +16,7 @@ const total = ref(0)
|
|||||||
const costMs = ref(0)
|
const costMs = ref(0)
|
||||||
const mediaFacets = ref<FacetItem[]>([])
|
const mediaFacets = ref<FacetItem[]>([])
|
||||||
const libraryFacets = ref<FacetItem[]>([])
|
const libraryFacets = ref<FacetItem[]>([])
|
||||||
|
const repoFacets = ref<FacetItem[]>([])
|
||||||
const clcFacets = ref<FacetItem[]>([])
|
const clcFacets = ref<FacetItem[]>([])
|
||||||
/** 命中但被屏蔽/下架而不展示的记录数 */
|
/** 命中但被屏蔽/下架而不展示的记录数 */
|
||||||
const maskedCount = ref(0)
|
const maskedCount = ref(0)
|
||||||
@@ -28,12 +29,28 @@ const selectedClc = ref('')
|
|||||||
const query = reactive<SearchQuery>({
|
const query = reactive<SearchQuery>({
|
||||||
current: 1,
|
current: 1,
|
||||||
size: 50,
|
size: 50,
|
||||||
mediaType: ''
|
mediaType: '',
|
||||||
|
mediaTypes: [] as string[],
|
||||||
|
sourceLibraries: [] as string[],
|
||||||
|
sourceRepos: [] as string[],
|
||||||
|
clcCodes: undefined,
|
||||||
|
withinKeyword: ''
|
||||||
})
|
})
|
||||||
|
|
||||||
/** 概览页每页条数选项(默认 50,可切 100/200;20 便于数据量小时演示翻页) */
|
/** 概览页每页条数选项(默认 50,可切 100/200;20 便于数据量小时演示翻页) */
|
||||||
const pageSizes = [20, 50, 100, 200]
|
const pageSizes = [20, 50, 100, 200]
|
||||||
|
|
||||||
|
// ==================== 二次检索(在结果中搜索 / 添加 / 去除) ====================
|
||||||
|
/** 二次检索模式:在结果中搜索(AND 收窄) / 在结果中添加(OR 拓宽) / 在结果中去除(排除) */
|
||||||
|
const secMode = ref<'within' | 'add' | 'remove'>('within')
|
||||||
|
const secInput = ref('')
|
||||||
|
/** 在结果中搜索:必须同时命中的附加关键词 */
|
||||||
|
const withinTerms = ref<string[]>([])
|
||||||
|
/** 在结果中添加:与当前结果集并集的附加关键词(叠加到综合 keyword,OR 生效) */
|
||||||
|
const addedTerms = ref<string[]>([])
|
||||||
|
/** 综合检索词的基础部分(不含 addedTerms),用于「添加」后精确还原 */
|
||||||
|
const baseKeyword = ref('')
|
||||||
|
|
||||||
// ==================== 检索结果展示字段(管理员在后台配置) ====================
|
// ==================== 检索结果展示字段(管理员在后台配置) ====================
|
||||||
|
|
||||||
/** 展示字段配置:取不到配置时用默认的 8 个字段兜底 */
|
/** 展示字段配置:取不到配置时用默认的 8 个字段兜底 */
|
||||||
@@ -59,15 +76,16 @@ function metaValue(row: VersionResource, key: string): string {
|
|||||||
/** 输入框内容(与查询参数分离,避免按途径分发后被清空) */
|
/** 输入框内容(与查询参数分离,避免按途径分发后被清空) */
|
||||||
const input = ref('')
|
const input = ref('')
|
||||||
const field = ref('综合')
|
const field = ref('综合')
|
||||||
const fields = ['综合', '题名', '责任者', '关键词', '出版社', 'ISBN']
|
const fields = ['综合', '题名', '责任者', '关键词', '出版社', '中图分类', 'ISBN']
|
||||||
|
|
||||||
/** 检索途径 → 查询参数字段 */
|
/** 检索途径 → 查询参数字段 */
|
||||||
const fieldParamMap: Record<string, 'keyword' | 'title' | 'author' | 'publisher' | 'isbn'> = {
|
const fieldParamMap: Record<string, 'keyword' | 'title' | 'author' | 'publisher' | 'clcCode' | 'isbn'> = {
|
||||||
综合: 'keyword',
|
综合: 'keyword',
|
||||||
题名: 'title',
|
题名: 'title',
|
||||||
责任者: 'author',
|
责任者: 'author',
|
||||||
关键词: 'keyword',
|
关键词: 'keyword',
|
||||||
出版社: 'publisher',
|
出版社: 'publisher',
|
||||||
|
中图分类: 'clcCode',
|
||||||
ISBN: 'isbn'
|
ISBN: 'isbn'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,6 +98,7 @@ const hitFieldMap: Record<string, string[]> = {
|
|||||||
责任者: ['author'],
|
责任者: ['author'],
|
||||||
关键词: ['keywords'],
|
关键词: ['keywords'],
|
||||||
出版社: ['publisher'],
|
出版社: ['publisher'],
|
||||||
|
中图分类: ['clcCode'],
|
||||||
ISBN: ['isbn']
|
ISBN: ['isbn']
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +108,7 @@ const fieldLabels: Record<string, string> = {
|
|||||||
keywords: '关键词',
|
keywords: '关键词',
|
||||||
summary: '摘要',
|
summary: '摘要',
|
||||||
publisher: '出版者',
|
publisher: '出版者',
|
||||||
|
clcCode: '中图分类',
|
||||||
isbn: 'ISBN'
|
isbn: 'ISBN'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,15 +148,50 @@ function snippets(row: VersionResource): { label: string; html: string }[] {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
async function doSearch() {
|
async function doSearch(fresh = false) {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
searched.value = true
|
searched.value = true
|
||||||
// 按所选途径分发检索词;多词用空格分隔,词与词之间为 AND
|
if (fresh) {
|
||||||
|
// 重新搜索:清空所有二次检索与分面限定,以输入框内容作为全新检索
|
||||||
|
withinTerms.value = []
|
||||||
|
addedTerms.value = []
|
||||||
|
excludeTerms.value = []
|
||||||
|
query.mediaTypes = []
|
||||||
|
query.sourceLibraries = []
|
||||||
|
query.sourceRepos = []
|
||||||
|
query.clcCodes = undefined
|
||||||
|
query.withinKeyword = ''
|
||||||
|
query.excludeKeyword = ''
|
||||||
|
query.mediaType = ''
|
||||||
|
query.sourceLibrary = ''
|
||||||
|
selectedClc.value = ''
|
||||||
|
// 按所选途径分发检索词
|
||||||
const kw = input.value.trim()
|
const kw = input.value.trim()
|
||||||
query.title = query.author = query.publisher = query.isbn = query.keyword = ''
|
query.title = query.author = query.publisher = query.isbn = query.keyword = ''
|
||||||
;(query as unknown as Record<string, string>)[fieldParamMap[field.value]] = kw
|
query.clcCode = ''
|
||||||
// 去除关键字:多个排除词以空格拼接提交后端统一排除
|
const fp = fieldParamMap[field.value]
|
||||||
query.excludeKeyword = excludeTerms.value.length ? excludeTerms.value.join(' ') : ''
|
// 用检索框按中图分类检索时,清掉左侧分类树的点选,避免两套 CLC 条件叠加
|
||||||
|
if (fp === 'clcCode') {
|
||||||
|
query.clcCodes = undefined
|
||||||
|
selectedClc.value = ''
|
||||||
|
}
|
||||||
|
;(query as unknown as Record<string, string>)[fp] = kw
|
||||||
|
baseKeyword.value = field.value === '综合' ? kw : ''
|
||||||
|
}
|
||||||
|
// 叠加二次检索词
|
||||||
|
query.withinKeyword = withinTerms.value.join(' ')
|
||||||
|
query.excludeKeyword = excludeTerms.value.join(' ')
|
||||||
|
// 在结果中添加:综合词 = 基础词 ∪ 附加词(OR 拓宽)
|
||||||
|
if (field.value === '综合') {
|
||||||
|
const base = baseKeyword.value ? baseKeyword.value.split(/\s+/).filter(Boolean) : []
|
||||||
|
query.keyword = Array.from(new Set([...base, ...addedTerms.value])).join(' ')
|
||||||
|
} else {
|
||||||
|
const kf = fieldParamMap[field.value] as string
|
||||||
|
const cur = (query as unknown as Record<string, string>)[kf] || ''
|
||||||
|
const base = cur ? cur.split(/\s+/).filter(Boolean) : []
|
||||||
|
;(query as unknown as Record<string, string>)[kf] =
|
||||||
|
Array.from(new Set([...base, ...addedTerms.value])).join(' ')
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const res = await unifiedSearch({ ...query })
|
const res = await unifiedSearch({ ...query })
|
||||||
rows.value = res.page?.records || []
|
rows.value = res.page?.records || []
|
||||||
@@ -145,6 +200,7 @@ async function doSearch() {
|
|||||||
maskedCount.value = res.maskedCount || 0
|
maskedCount.value = res.maskedCount || 0
|
||||||
mediaFacets.value = res.mediaTypeFacets || []
|
mediaFacets.value = res.mediaTypeFacets || []
|
||||||
libraryFacets.value = res.sourceLibraryFacets || []
|
libraryFacets.value = res.sourceLibraryFacets || []
|
||||||
|
repoFacets.value = res.sourceRepoFacets || []
|
||||||
clcFacets.value = res.clcFacets || []
|
clcFacets.value = res.clcFacets || []
|
||||||
if (res.sensitiveBlocked) {
|
if (res.sensitiveBlocked) {
|
||||||
ElMessage.warning('检索词命中敏感词库,结果已被屏蔽')
|
ElMessage.warning('检索词命中敏感词库,结果已被屏蔽')
|
||||||
@@ -156,6 +212,54 @@ async function doSearch() {
|
|||||||
loadClcTree()
|
loadClcTree()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合并到综合检索词:把题名/责任者/出版者/ISBN 等途径词并入综合 keyword,
|
||||||
|
* 避免二次检索时多字段 AND 叠加导致结果被错误收窄。
|
||||||
|
*/
|
||||||
|
function consolidateToKeyword() {
|
||||||
|
const parts: string[] = []
|
||||||
|
if (query.keyword) parts.push(query.keyword)
|
||||||
|
if (query.title) parts.push(query.title)
|
||||||
|
if (query.author) parts.push(query.author)
|
||||||
|
if (query.publisher) parts.push(query.publisher)
|
||||||
|
if (query.isbn) parts.push(query.isbn)
|
||||||
|
baseKeyword.value = parts.filter(Boolean).join(' ')
|
||||||
|
query.keyword = baseKeyword.value
|
||||||
|
query.title = query.author = query.publisher = query.isbn = query.clcCode = ''
|
||||||
|
field.value = '综合'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 二次检索(在结果中搜索 / 在结果中添加 / 在结果中去除):叠加附加词后重新检索 */
|
||||||
|
function applySecondary() {
|
||||||
|
const parts = secInput.value.trim().split(/\s+/).filter(Boolean)
|
||||||
|
if (!parts.length) return
|
||||||
|
if (secMode.value === 'within') {
|
||||||
|
const set = new Set(withinTerms.value)
|
||||||
|
parts.forEach((p) => set.add(p))
|
||||||
|
withinTerms.value = [...set]
|
||||||
|
} else if (secMode.value === 'add') {
|
||||||
|
consolidateToKeyword()
|
||||||
|
const set = new Set(addedTerms.value)
|
||||||
|
parts.forEach((p) => set.add(p))
|
||||||
|
addedTerms.value = [...set]
|
||||||
|
} else {
|
||||||
|
const set = new Set(excludeTerms.value)
|
||||||
|
parts.forEach((p) => set.add(p))
|
||||||
|
excludeTerms.value = [...set]
|
||||||
|
}
|
||||||
|
secInput.value = ''
|
||||||
|
doSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清除全部二次检索(在结果中搜索 / 添加 / 去除) */
|
||||||
|
function clearSecondary() {
|
||||||
|
withinTerms.value = []
|
||||||
|
addedTerms.value = []
|
||||||
|
excludeTerms.value = []
|
||||||
|
secInput.value = ''
|
||||||
|
doSearch()
|
||||||
|
}
|
||||||
|
|
||||||
/** 拉取中图法分类树:带上当前检索条件,数量与结果一致 */
|
/** 拉取中图法分类树:带上当前检索条件,数量与结果一致 */
|
||||||
async function loadClcTree() {
|
async function loadClcTree() {
|
||||||
try {
|
try {
|
||||||
@@ -166,8 +270,13 @@ async function loadClcTree() {
|
|||||||
publisher: query.publisher,
|
publisher: query.publisher,
|
||||||
isbn: query.isbn,
|
isbn: query.isbn,
|
||||||
excludeKeyword: query.excludeKeyword,
|
excludeKeyword: query.excludeKeyword,
|
||||||
|
withinKeyword: query.withinKeyword,
|
||||||
mediaType: query.mediaType,
|
mediaType: query.mediaType,
|
||||||
|
mediaTypes: query.mediaTypes,
|
||||||
sourceLibrary: query.sourceLibrary,
|
sourceLibrary: query.sourceLibrary,
|
||||||
|
sourceLibraries: query.sourceLibraries,
|
||||||
|
sourceRepos: query.sourceRepos,
|
||||||
|
clcCodes: query.clcCodes,
|
||||||
publishYearStart: query.publishYearStart,
|
publishYearStart: query.publishYearStart,
|
||||||
publishYearEnd: query.publishYearEnd,
|
publishYearEnd: query.publishYearEnd,
|
||||||
matchType: query.matchType
|
matchType: query.matchType
|
||||||
@@ -187,7 +296,12 @@ function clearClc() {
|
|||||||
|
|
||||||
/** 清除前置筛选条件(媒体类型 / 语种分组) */
|
/** 清除前置筛选条件(媒体类型 / 语种分组) */
|
||||||
function clearCond(key: 'mediaType' | 'languageGroup') {
|
function clearCond(key: 'mediaType' | 'languageGroup') {
|
||||||
query[key] = undefined
|
if (key === 'languageGroup') {
|
||||||
|
query.languageGroup = undefined
|
||||||
|
} else {
|
||||||
|
query.mediaTypes = []
|
||||||
|
query.mediaType = ''
|
||||||
|
}
|
||||||
query.current = 1
|
query.current = 1
|
||||||
doSearch()
|
doSearch()
|
||||||
}
|
}
|
||||||
@@ -211,6 +325,14 @@ function removeExclude(t: string) {
|
|||||||
excludeTerms.value = excludeTerms.value.filter((x) => x !== t)
|
excludeTerms.value = excludeTerms.value.filter((x) => x !== t)
|
||||||
doSearch()
|
doSearch()
|
||||||
}
|
}
|
||||||
|
function removeWithin(t: string) {
|
||||||
|
withinTerms.value = withinTerms.value.filter((x) => x !== t)
|
||||||
|
doSearch()
|
||||||
|
}
|
||||||
|
function removeAdded(t: string) {
|
||||||
|
addedTerms.value = addedTerms.value.filter((x) => x !== t)
|
||||||
|
doSearch()
|
||||||
|
}
|
||||||
|
|
||||||
function clearExclude() {
|
function clearExclude() {
|
||||||
excludeTerms.value = []
|
excludeTerms.value = []
|
||||||
@@ -227,13 +349,22 @@ function pickClc(node: ClcNode, codes: string[]) {
|
|||||||
doSearch()
|
doSearch()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 点选左侧分面:再点一次已选中的项即取消筛选 */
|
/** 点选左侧分面(资源类型 / 来源院校 / 资源库名):多选组合,再次点击取消 */
|
||||||
function pick(type: 'mediaType' | 'sourceLibrary' | 'clcCode', v: string) {
|
function toggleFacet(type: 'mediaType' | 'sourceLibrary' | 'sourceRepo', v: string) {
|
||||||
query[type] = query[type] === v ? '' : v
|
const arr =
|
||||||
|
type === 'mediaType' ? query.mediaTypes! : type === 'sourceLibrary' ? query.sourceLibraries! : query.sourceRepos!
|
||||||
|
const i = arr.indexOf(v)
|
||||||
|
if (i >= 0) arr.splice(i, 1)
|
||||||
|
else arr.push(v)
|
||||||
query.current = 1
|
query.current = 1
|
||||||
doSearch()
|
doSearch()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 条件标签:单独移除某个已选分面 */
|
||||||
|
function removeFacet(type: 'mediaType' | 'sourceLibrary' | 'sourceRepo', v: string) {
|
||||||
|
toggleFacet(type, v)
|
||||||
|
}
|
||||||
|
|
||||||
function goPage(p: number) {
|
function goPage(p: number) {
|
||||||
query.current = p
|
query.current = p
|
||||||
doSearch()
|
doSearch()
|
||||||
@@ -398,6 +529,44 @@ function originalUrl(r: VersionResource): string {
|
|||||||
return r.fulltextUrl || ''
|
return r.fulltextUrl || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取某条文献的来源列表。
|
||||||
|
* 优先用后端挂载的多来源 sources;旧数据未维护多来源时,
|
||||||
|
* 用主表单的单个来源字段兜底成一条,保证概览页始终能展示与下载。
|
||||||
|
*/
|
||||||
|
function toSources(row?: VersionResource): ResourceSource[] {
|
||||||
|
if (!row) return []
|
||||||
|
if (row.sources && row.sources.length) return row.sources
|
||||||
|
if (row.sourceRepo || row.sourceLibrary || row.fulltextUrl) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
sourceRepo: row.sourceRepo,
|
||||||
|
sourceLibrary: row.sourceLibrary,
|
||||||
|
sourceLibraryAddr: row.sourceLibraryAddr,
|
||||||
|
fulltextUrl: row.fulltextUrl,
|
||||||
|
processNo: row.processNo,
|
||||||
|
mediaType: row.mediaType
|
||||||
|
} as ResourceSource
|
||||||
|
]
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单来源的原始细览页地址(按来源馆地址 + 加工编号拼接) */
|
||||||
|
function sourceOriginalUrl(src?: ResourceSource): string {
|
||||||
|
if (src?.sourceLibraryAddr && src.processNo) {
|
||||||
|
const addr = src.sourceLibraryAddr.trim()
|
||||||
|
const base = addr.startsWith('http') ? addr : `http://${addr}`
|
||||||
|
return `${base}/resource/${encodeURIComponent(src.processNo.trim())}`
|
||||||
|
}
|
||||||
|
return src?.fulltextUrl || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 下拉「选择来源下载」:新开标签打开对应来源全文地址 */
|
||||||
|
function openSource(u?: string) {
|
||||||
|
if (u) window.open(u, '_blank')
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
const kw = route.query.keyword as string
|
const kw = route.query.keyword as string
|
||||||
const f = route.query.field as string
|
const f = route.query.field as string
|
||||||
@@ -408,7 +577,7 @@ onMounted(() => {
|
|||||||
// 主页「前置筛选」勾选带来的条件:媒体类型 + 语种分组
|
// 主页「前置筛选」勾选带来的条件:媒体类型 + 语种分组
|
||||||
const mt = route.query.mediaType as string
|
const mt = route.query.mediaType as string
|
||||||
if (mt === '纸质' || mt === '电子') {
|
if (mt === '纸质' || mt === '电子') {
|
||||||
query.mediaType = mt
|
query.mediaTypes = [mt]
|
||||||
}
|
}
|
||||||
const lg = route.query.languageGroup as string
|
const lg = route.query.languageGroup as string
|
||||||
if (lg === 'chi' || lg === 'foreign') {
|
if (lg === 'chi' || lg === 'foreign') {
|
||||||
@@ -417,7 +586,7 @@ onMounted(() => {
|
|||||||
// 检索条件为空时也执行检索 → 后端返回全部版本资源
|
// 检索条件为空时也执行检索 → 后端返回全部版本资源
|
||||||
input.value = kw || ''
|
input.value = kw || ''
|
||||||
fetchListFields()
|
fetchListFields()
|
||||||
doSearch()
|
doSearch(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
// 已在检索页时,主页/热词再次带词跳转也能触发新检索
|
// 已在检索页时,主页/热词再次带词跳转也能触发新检索
|
||||||
@@ -426,7 +595,7 @@ watch(
|
|||||||
(kw) => {
|
(kw) => {
|
||||||
if (route.path !== '/search') return
|
if (route.path !== '/search') return
|
||||||
input.value = (kw as string) || ''
|
input.value = (kw as string) || ''
|
||||||
doSearch()
|
doSearch(true)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
</script>
|
</script>
|
||||||
@@ -436,38 +605,38 @@ watch(
|
|||||||
<div class="bar">
|
<div class="bar">
|
||||||
<el-input v-model="input" 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" @change="searched && doSearch()">
|
<el-select v-model="field" style="width: 96px" @change="doSearch(true)">
|
||||||
<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>
|
||||||
<template #append><el-button type="primary" @click="doSearch">检索</el-button></template>
|
<template #append><el-button type="primary" @click="doSearch(true)">检索</el-button></template>
|
||||||
</el-input>
|
</el-input>
|
||||||
|
|
||||||
<!-- 去除关键字:在结果集中排除含指定词的记录 -->
|
<!-- 二次检索:在结果中搜索 / 在结果中添加 / 在结果中去除 -->
|
||||||
<div class="exclude-bar">
|
<div class="exclude-bar">
|
||||||
<span class="exclude-label">去除关键字</span>
|
<span class="exclude-label">二次检索</span>
|
||||||
|
<el-radio-group v-model="secMode" size="small">
|
||||||
|
<el-radio-button value="within">在结果中搜索</el-radio-button>
|
||||||
|
<el-radio-button value="add">在结果中添加</el-radio-button>
|
||||||
|
<el-radio-button value="remove">在结果中去除</el-radio-button>
|
||||||
|
</el-radio-group>
|
||||||
<el-input
|
<el-input
|
||||||
v-model="excludeText"
|
v-model="secInput"
|
||||||
class="exclude-input"
|
class="exclude-input"
|
||||||
size="default"
|
size="default"
|
||||||
clearable
|
clearable
|
||||||
placeholder="输入要排除的词,空格分隔可多个,如 999"
|
:placeholder="secMode === 'remove' ? '输入要排除的词,空格分隔可多个' : '输入检索词,空格分隔可多个'"
|
||||||
@keyup.enter="addExclude"
|
@keyup.enter="applySecondary"
|
||||||
>
|
>
|
||||||
<template #append><el-button @click="addExclude">去除</el-button></template>
|
<template #append><el-button @click="applySecondary">检索</el-button></template>
|
||||||
</el-input>
|
</el-input>
|
||||||
<div v-if="excludeTerms.length" class="exclude-tags">
|
<el-button
|
||||||
<el-tag
|
v-if="withinTerms.length || addedTerms.length || excludeTerms.length"
|
||||||
v-for="t in excludeTerms"
|
link
|
||||||
:key="t"
|
type="primary"
|
||||||
size="small"
|
size="small"
|
||||||
type="info"
|
@click="clearSecondary"
|
||||||
effect="plain"
|
>清除二次检索</el-button>
|
||||||
closable
|
|
||||||
@close="removeExclude(t)"
|
|
||||||
>{{ t }}</el-tag>
|
|
||||||
<el-button link type="primary" size="small" @click="clearExclude">清空</el-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -475,12 +644,17 @@ watch(
|
|||||||
<aside class="side">
|
<aside class="side">
|
||||||
<div class="side-title">资源类型</div>
|
<div class="side-title">资源类型</div>
|
||||||
<div v-for="f in mediaFacets" :key="f.name" class="side-item"
|
<div v-for="f in mediaFacets" :key="f.name" class="side-item"
|
||||||
:class="{ on: query.mediaType === f.name }" @click="pick('mediaType', f.name)">
|
:class="{ on: query.mediaTypes?.includes(f.name) }" @click="toggleFacet('mediaType', f.name)">
|
||||||
<span>{{ f.name }}</span><em>{{ f.value }}</em>
|
<span>{{ f.name }}</span><em>{{ f.value }}</em>
|
||||||
</div>
|
</div>
|
||||||
<div class="side-title">来源院校</div>
|
<div class="side-title">来源院校</div>
|
||||||
<div v-for="f in libraryFacets" :key="f.name" class="side-item"
|
<div v-for="f in libraryFacets" :key="f.name" class="side-item"
|
||||||
:class="{ on: query.sourceLibrary === f.name }" @click="pick('sourceLibrary', f.name)">
|
:class="{ on: query.sourceLibraries?.includes(f.name) }" @click="toggleFacet('sourceLibrary', f.name)">
|
||||||
|
<span>{{ f.name }}</span><em>{{ f.value }}</em>
|
||||||
|
</div>
|
||||||
|
<div class="side-title">资源库名</div>
|
||||||
|
<div v-for="f in repoFacets" :key="f.name" class="side-item"
|
||||||
|
:class="{ on: query.sourceRepos?.includes(f.name) }" @click="toggleFacet('sourceRepo', f.name)">
|
||||||
<span>{{ f.name }}</span><em>{{ f.value }}</em>
|
<span>{{ f.name }}</span><em>{{ f.value }}</em>
|
||||||
</div>
|
</div>
|
||||||
<div class="side-title">
|
<div class="side-title">
|
||||||
@@ -500,26 +674,36 @@ watch(
|
|||||||
<el-tag v-if="maskedCount" type="warning" effect="plain" size="small" class="cond-tag">
|
<el-tag v-if="maskedCount" type="warning" effect="plain" size="small" class="cond-tag">
|
||||||
已隐藏 {{ maskedCount }} 条被屏蔽/下架的记录
|
已隐藏 {{ maskedCount }} 条被屏蔽/下架的记录
|
||||||
</el-tag>
|
</el-tag>
|
||||||
<el-tag v-if="query.mediaType" class="cond-tag" size="small" closable @close="clearCond('mediaType')">{{ query.mediaType }}</el-tag>
|
|
||||||
<el-tag v-if="query.languageGroup" class="cond-tag" size="small" closable @close="clearCond('languageGroup')">
|
<el-tag v-if="query.languageGroup" class="cond-tag" size="small" closable @close="clearCond('languageGroup')">
|
||||||
{{ query.languageGroup === 'chi' ? '中文文献' : '外文文献' }}
|
{{ query.languageGroup === 'chi' ? '中文文献' : '外文文献' }}
|
||||||
</el-tag>
|
</el-tag>
|
||||||
<el-tag
|
<el-tag
|
||||||
v-for="t in excludeTerms"
|
v-for="t in query.mediaTypes" :key="'mt' + t"
|
||||||
:key="'ex' + t"
|
class="cond-tag" size="small" closable @close="removeFacet('mediaType', t)"
|
||||||
class="cond-tag"
|
>资源类型:{{ t }}</el-tag>
|
||||||
size="small"
|
<el-tag
|
||||||
type="info"
|
v-for="t in query.sourceLibraries" :key="'sl' + t"
|
||||||
closable
|
class="cond-tag" size="small" closable @close="removeFacet('sourceLibrary', t)"
|
||||||
@close="removeExclude(t)"
|
>来源院校:{{ t }}</el-tag>
|
||||||
>去除:{{ t }}</el-tag>
|
<el-tag
|
||||||
<el-tag v-if="maskedCount" type="warning" effect="plain" size="small" class="cond-tag">
|
v-for="t in query.sourceRepos" :key="'sr' + t"
|
||||||
已隐藏 {{ maskedCount }} 条被屏蔽/下架的记录
|
class="cond-tag" size="small" closable @close="removeFacet('sourceRepo', t)"
|
||||||
</el-tag>
|
>资源库名:{{ t }}</el-tag>
|
||||||
<el-tag v-if="query.mediaType" class="cond-tag" size="small" closable @close="clearCond('mediaType')">{{ query.mediaType }}</el-tag>
|
<el-tag v-if="query.clcCodes && query.clcCodes.length" class="cond-tag" size="small" closable @close="clearClc">
|
||||||
<el-tag v-if="query.languageGroup" class="cond-tag" size="small" closable @close="clearCond('languageGroup')">
|
中图分类:{{ query.clcCodes.join(' / ') }}
|
||||||
{{ query.languageGroup === 'chi' ? '中文文献' : '外文文献' }}
|
|
||||||
</el-tag>
|
</el-tag>
|
||||||
|
<el-tag
|
||||||
|
v-for="t in withinTerms" :key="'w' + t"
|
||||||
|
class="cond-tag" size="small" type="success" closable @close="removeWithin(t)"
|
||||||
|
>在结果中搜索:{{ t }}</el-tag>
|
||||||
|
<el-tag
|
||||||
|
v-for="t in addedTerms" :key="'a' + t"
|
||||||
|
class="cond-tag" size="small" type="success" closable @close="removeAdded(t)"
|
||||||
|
>在结果中添加:{{ t }}</el-tag>
|
||||||
|
<el-tag
|
||||||
|
v-for="t in excludeTerms" :key="'ex' + t"
|
||||||
|
class="cond-tag" size="small" type="info" closable @close="removeExclude(t)"
|
||||||
|
>在结果中去除:{{ t }}</el-tag>
|
||||||
</div>
|
</div>
|
||||||
<div class="ops">
|
<div class="ops">
|
||||||
<el-checkbox
|
<el-checkbox
|
||||||
@@ -550,6 +734,44 @@ watch(
|
|||||||
<span class="snippet-label">{{ s.label }}:</span>
|
<span class="snippet-label">{{ s.label }}:</span>
|
||||||
<span v-html="s.html"></span>
|
<span v-html="s.html"></span>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 多来源:按资源库图标+名称展示,点击可下载;多个来源时提供「选择来源下载」 -->
|
||||||
|
<div v-if="toSources(r).length" class="srcs" @click.stop>
|
||||||
|
<span class="srcs-k">来源</span>
|
||||||
|
<a
|
||||||
|
v-for="(src, i) in toSources(r)"
|
||||||
|
:key="src.id || src.fulltextUrl || i"
|
||||||
|
class="src-chip"
|
||||||
|
:href="src.fulltextUrl"
|
||||||
|
target="_blank"
|
||||||
|
:title="`下载全文 · ${src.sourceLibrary || src.sourceRepo || '未知来源'}`"
|
||||||
|
>
|
||||||
|
<el-icon :size="13"><Reading /></el-icon>
|
||||||
|
<span class="src-name">{{ src.sourceRepo || src.sourceLibrary || '未知来源' }}</span>
|
||||||
|
<span v-if="src.mediaType" class="src-mt">{{ src.mediaType }}</span>
|
||||||
|
</a>
|
||||||
|
<el-dropdown
|
||||||
|
v-if="toSources(r).length > 1"
|
||||||
|
trigger="click"
|
||||||
|
class="src-dd"
|
||||||
|
@command="openSource"
|
||||||
|
>
|
||||||
|
<el-button size="small" type="primary" plain>
|
||||||
|
选择来源下载<el-icon><ArrowDown /></el-icon>
|
||||||
|
</el-button>
|
||||||
|
<template #dropdown>
|
||||||
|
<el-dropdown-menu>
|
||||||
|
<el-dropdown-item
|
||||||
|
v-for="(src, i) in toSources(r)"
|
||||||
|
:key="src.id || src.fulltextUrl || i"
|
||||||
|
:command="src.fulltextUrl"
|
||||||
|
>
|
||||||
|
{{ src.sourceRepo || src.sourceLibrary || '未知来源' }}
|
||||||
|
<span v-if="src.mediaType">({{ src.mediaType }})</span>
|
||||||
|
</el-dropdown-item>
|
||||||
|
</el-dropdown-menu>
|
||||||
|
</template>
|
||||||
|
</el-dropdown>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -611,19 +833,25 @@ watch(
|
|||||||
<el-descriptions-item label="摘要">{{ detail.summary || '-' }}</el-descriptions-item>
|
<el-descriptions-item label="摘要">{{ detail.summary || '-' }}</el-descriptions-item>
|
||||||
</el-descriptions>
|
</el-descriptions>
|
||||||
|
|
||||||
<!-- 原始细览页跳转 + 文献直接下载 -->
|
<!-- 多来源:逐来源提供原始页跳转 + 全文下载 -->
|
||||||
<div style="margin: 14px 0">
|
<div style="margin: 14px 0">
|
||||||
<el-button
|
<div class="src-list-title">
|
||||||
v-if="originalUrl(detail)"
|
来源({{ toSources(detail).length }})<span class="src-list-sub">可分别选择来源下载</span>
|
||||||
tag="a"
|
</div>
|
||||||
:href="originalUrl(detail)"
|
<div v-for="(src, i) in toSources(detail)" :key="src.id || src.fulltextUrl || i" class="src-row">
|
||||||
target="_blank"
|
<span class="src-row-name">
|
||||||
>
|
<el-icon :size="15"><Reading /></el-icon>
|
||||||
{{ detail.sourceRepo ? `进入${detail.sourceRepo}原始页` : '查看来源库原始页' }}
|
{{ src.sourceRepo || src.sourceLibrary || '未知来源' }}
|
||||||
</el-button>
|
<span v-if="src.sourceLibrary && src.sourceRepo" class="src-row-lib">· {{ src.sourceLibrary }}</span>
|
||||||
<el-button v-else disabled>暂无来源库地址</el-button>
|
<span v-if="src.mediaType" class="src-row-mt">{{ src.mediaType }}</span>
|
||||||
<el-button v-if="detail.fulltextUrl" type="primary" tag="a" :href="detail.fulltextUrl" target="_blank">下载全文</el-button>
|
</span>
|
||||||
<el-button v-else type="primary" disabled>暂无全文地址</el-button>
|
<span class="src-row-ops">
|
||||||
|
<el-button v-if="sourceOriginalUrl(src)" link type="primary" tag="a" :href="sourceOriginalUrl(src)" target="_blank">原始页</el-button>
|
||||||
|
<el-button v-if="src.fulltextUrl" type="primary" tag="a" :href="src.fulltextUrl" target="_blank">下载全文</el-button>
|
||||||
|
<span v-else class="src-none">无全文</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<el-empty v-if="!toSources(detail).length" description="暂无来源与全文" :image-size="56" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 相似文献推荐:点击切换到该文献的细览 -->
|
<!-- 相似文献推荐:点击切换到该文献的细览 -->
|
||||||
@@ -891,4 +1119,117 @@ watch(
|
|||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 概览页卡片多来源:资源库图标 + 名称,点击可下载 */
|
||||||
|
.srcs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 8px;
|
||||||
|
|
||||||
|
.srcs-k {
|
||||||
|
flex: none;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #8b93a1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
max-width: 240px;
|
||||||
|
padding: 2px 9px;
|
||||||
|
border: 1px solid var(--card-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--brand-light, #f3f7f4);
|
||||||
|
color: var(--brand-primary, #2f6b4f);
|
||||||
|
font-size: 12px;
|
||||||
|
text-decoration: none;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.15s, box-shadow 0.15s;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #e6f0ea;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-name {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-mt {
|
||||||
|
flex: none;
|
||||||
|
color: #9aa3b2;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-dd {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 细览页来源列表 */
|
||||||
|
.src-list-title {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #5b6472;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
|
||||||
|
.src-list-sub {
|
||||||
|
margin-left: 6px;
|
||||||
|
font-weight: 400;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #9aa3b2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid var(--card-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
margin-bottom: 8px;
|
||||||
|
|
||||||
|
.src-row-name {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #1f2937;
|
||||||
|
font-weight: 600;
|
||||||
|
|
||||||
|
.src-row-lib {
|
||||||
|
color: #8b93a1;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-row-mt {
|
||||||
|
flex: none;
|
||||||
|
color: #9aa3b2;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-row-ops {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.src-none {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #b6bcc7;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,675 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, reactive, ref } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||||
|
import {
|
||||||
|
listSyncDatasources,
|
||||||
|
listSyncTasks,
|
||||||
|
listTargetColumns,
|
||||||
|
listTargetTables,
|
||||||
|
pageSyncLogs,
|
||||||
|
previewSyncColumns,
|
||||||
|
removeSyncDatasource,
|
||||||
|
removeSyncTask,
|
||||||
|
runSyncTask,
|
||||||
|
saveSyncDatasource,
|
||||||
|
saveSyncTask,
|
||||||
|
testSyncDatasource,
|
||||||
|
type SyncDatasource,
|
||||||
|
type SyncFieldMap,
|
||||||
|
type SyncLog,
|
||||||
|
type SyncTask,
|
||||||
|
type TargetColumn
|
||||||
|
} from '@/api/sync'
|
||||||
|
|
||||||
|
const tab = ref('source')
|
||||||
|
const sources = ref<SyncDatasource[]>([])
|
||||||
|
const tasks = ref<SyncTask[]>([])
|
||||||
|
const logs = ref<SyncLog[]>([])
|
||||||
|
const logTotal = ref(0)
|
||||||
|
const logQuery = reactive({ current: 1, size: 10, taskId: undefined as number | undefined })
|
||||||
|
const tables = ref<string[]>([])
|
||||||
|
const columns = ref<TargetColumn[]>([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const runningId = ref<number | null>(null)
|
||||||
|
|
||||||
|
const sourceVisible = ref(false)
|
||||||
|
const sourceRef = ref<FormInstance>()
|
||||||
|
const testing = ref(false)
|
||||||
|
const sourceForm = reactive<SyncDatasource>({
|
||||||
|
name: '',
|
||||||
|
dbType: 'POSTGRESQL',
|
||||||
|
host: '',
|
||||||
|
port: 5432,
|
||||||
|
dbName: '',
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
jdbcParams: '',
|
||||||
|
enabled: 1,
|
||||||
|
remark: ''
|
||||||
|
})
|
||||||
|
const sourceRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
|
||||||
|
dbType: [{ required: true, message: '请选择类型', trigger: 'change' }],
|
||||||
|
host: [{ required: true, message: '请填写地址', trigger: 'blur' }],
|
||||||
|
port: [{ required: true, message: '请填写端口', trigger: 'blur' }],
|
||||||
|
dbName: [{ required: true, message: '请填写库名', trigger: 'blur' }],
|
||||||
|
username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
|
||||||
|
password: [{
|
||||||
|
validator: (_rule, value, callback) => {
|
||||||
|
if (!sourceForm.id && !value) callback(new Error('请填写密码'))
|
||||||
|
else callback()
|
||||||
|
},
|
||||||
|
trigger: 'blur'
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskVisible = ref(false)
|
||||||
|
const taskRef = ref<FormInstance>()
|
||||||
|
const previewing = ref(false)
|
||||||
|
const taskForm = reactive<SyncTask>(emptyTask())
|
||||||
|
const taskRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '请填写任务名称', trigger: 'blur' }],
|
||||||
|
datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
|
||||||
|
querySql: [{ required: true, message: '请填写查询 SQL', trigger: 'blur' }],
|
||||||
|
targetTable: [{ required: true, message: '请选择目标表', trigger: 'change' }]
|
||||||
|
}
|
||||||
|
|
||||||
|
const dataTypes = ['STRING', 'INTEGER', 'LONG', 'DECIMAL', 'DATE', 'DATETIME']
|
||||||
|
const cleanRules = [
|
||||||
|
{ value: 'TRIM', label: '去空格' },
|
||||||
|
{ value: 'NONE', label: '不处理' },
|
||||||
|
{ value: 'UPPER', label: '转大写' },
|
||||||
|
{ value: 'LOWER', label: '转小写' },
|
||||||
|
{ value: 'DIGITS', label: '只留数字' },
|
||||||
|
{ value: 'COMPACT_DATE', label: '压成日期' }
|
||||||
|
]
|
||||||
|
const ports: Record<string, number> = {
|
||||||
|
MYSQL: 3306,
|
||||||
|
ORACLE: 1521,
|
||||||
|
SQLSERVER: 1433,
|
||||||
|
POSTGRESQL: 5432,
|
||||||
|
HIGHGO: 5866
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyTask(): SyncTask {
|
||||||
|
return {
|
||||||
|
name: '',
|
||||||
|
querySql: '',
|
||||||
|
targetTable: 'version_resource',
|
||||||
|
batchSize: 200,
|
||||||
|
retryTimes: 1,
|
||||||
|
cronExpr: '',
|
||||||
|
scheduleEnabled: 0,
|
||||||
|
syncMode: 'FULL',
|
||||||
|
incrementColumn: '',
|
||||||
|
uniqueFields: 'process_no',
|
||||||
|
enabled: 1,
|
||||||
|
mappings: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
refresh()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const [sourceList, taskList, tableList] = await Promise.all([
|
||||||
|
listSyncDatasources(),
|
||||||
|
listSyncTasks(),
|
||||||
|
listTargetTables()
|
||||||
|
])
|
||||||
|
sources.value = sourceList
|
||||||
|
tasks.value = taskList
|
||||||
|
tables.value = tableList
|
||||||
|
await fetchLogs()
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLogs() {
|
||||||
|
const page = await pageSyncLogs({
|
||||||
|
taskId: logQuery.taskId,
|
||||||
|
current: logQuery.current,
|
||||||
|
size: logQuery.size
|
||||||
|
})
|
||||||
|
logs.value = page.records
|
||||||
|
logTotal.value = page.total
|
||||||
|
}
|
||||||
|
|
||||||
|
function openSource() {
|
||||||
|
Object.assign(sourceForm, {
|
||||||
|
id: undefined,
|
||||||
|
name: '',
|
||||||
|
dbType: 'POSTGRESQL',
|
||||||
|
host: '',
|
||||||
|
port: 5432,
|
||||||
|
dbName: '',
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
jdbcParams: '',
|
||||||
|
enabled: 1,
|
||||||
|
remark: ''
|
||||||
|
})
|
||||||
|
sourceVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function editSource(row: SyncDatasource) {
|
||||||
|
Object.assign(sourceForm, { ...row, password: '' })
|
||||||
|
sourceVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDbType(value: string) {
|
||||||
|
sourceForm.port = ports[value] || sourceForm.port
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testSource() {
|
||||||
|
await sourceRef.value?.validate()
|
||||||
|
testing.value = true
|
||||||
|
try {
|
||||||
|
await testSyncDatasource(sourceForm)
|
||||||
|
ElMessage.success('连接成功')
|
||||||
|
} finally {
|
||||||
|
testing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSource() {
|
||||||
|
await sourceRef.value?.validate()
|
||||||
|
await saveSyncDatasource(sourceForm)
|
||||||
|
ElMessage.success('数据源已保存')
|
||||||
|
sourceVisible.value = false
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeSource(row: SyncDatasource) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确认删除数据源「${row.name}」?`, '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await removeSyncDatasource(row.id as number)
|
||||||
|
ElMessage.success('已删除')
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openTask() {
|
||||||
|
Object.assign(taskForm, emptyTask(), { mappings: [] })
|
||||||
|
await loadColumns(taskForm.targetTable)
|
||||||
|
taskVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function editTask(row: SyncTask) {
|
||||||
|
Object.assign(taskForm, {
|
||||||
|
...row,
|
||||||
|
mappings: (row.mappings || []).map((item) => ({ ...item }))
|
||||||
|
})
|
||||||
|
await loadColumns(taskForm.targetTable)
|
||||||
|
taskVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadColumns(table: string) {
|
||||||
|
columns.value = await listTargetColumns(table)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onTargetTable(table: string) {
|
||||||
|
await loadColumns(table)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readSourceColumns() {
|
||||||
|
if (!taskForm.datasourceId) {
|
||||||
|
ElMessage.warning('请先选择数据源')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!taskForm.querySql.trim()) {
|
||||||
|
ElMessage.warning('请先填写查询 SQL')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
previewing.value = true
|
||||||
|
try {
|
||||||
|
const names = await previewSyncColumns({ id: taskForm.datasourceId } as SyncDatasource, taskForm.querySql)
|
||||||
|
const exists = new Set(taskForm.mappings.map((item) => item.sourceField.toLowerCase()))
|
||||||
|
names.forEach((name) => {
|
||||||
|
if (!exists.has(name.toLowerCase())) {
|
||||||
|
taskForm.mappings.push({
|
||||||
|
sourceField: name,
|
||||||
|
targetField: '',
|
||||||
|
dataType: 'STRING',
|
||||||
|
cleanRule: 'TRIM',
|
||||||
|
requiredFlag: 0
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
ElMessage.success(`读到 ${names.length} 个源字段`)
|
||||||
|
} finally {
|
||||||
|
previewing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addMap() {
|
||||||
|
taskForm.mappings.push({
|
||||||
|
sourceField: '',
|
||||||
|
targetField: '',
|
||||||
|
dataType: 'STRING',
|
||||||
|
cleanRule: 'TRIM',
|
||||||
|
requiredFlag: 0
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeMap(index: number) {
|
||||||
|
taskForm.mappings.splice(index, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTask() {
|
||||||
|
await taskRef.value?.validate()
|
||||||
|
const maps = taskForm.mappings.filter((item) => item.sourceField && item.targetField)
|
||||||
|
if (!maps.length) {
|
||||||
|
ElMessage.error('请至少配置一条字段映射')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await saveSyncTask({ ...taskForm, mappings: maps })
|
||||||
|
ElMessage.success('同步任务已保存')
|
||||||
|
taskVisible.value = false
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeTask(row: SyncTask) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确认删除同步任务「${row.name}」?`, '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await removeSyncTask(row.id as number)
|
||||||
|
ElMessage.success('已删除')
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runTask(row: SyncTask) {
|
||||||
|
runningId.value = row.id as number
|
||||||
|
try {
|
||||||
|
await runSyncTask(row.id as number)
|
||||||
|
ElMessage.success('已开始同步,结果请看同步日志')
|
||||||
|
tab.value = 'log'
|
||||||
|
logQuery.current = 1
|
||||||
|
await fetchLogs()
|
||||||
|
} finally {
|
||||||
|
runningId.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function columnLabel(column: TargetColumn) {
|
||||||
|
return column.comment ? `${column.comment}(${column.name})` : column.name
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusText(status?: string) {
|
||||||
|
if (status === 'SUCCESS') return '成功'
|
||||||
|
if (status === 'FAILED') return '失败'
|
||||||
|
if (status === 'PARTIAL') return '部分成功'
|
||||||
|
if (status === 'RUNNING') return '执行中'
|
||||||
|
return status || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusType(status?: string) {
|
||||||
|
if (status === 'SUCCESS') return 'success'
|
||||||
|
if (status === 'FAILED') return 'danger'
|
||||||
|
if (status === 'PARTIAL') return 'warning'
|
||||||
|
return 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
function dbTypeText(type?: string) {
|
||||||
|
if (type === 'HIGHGO') return '瀚高'
|
||||||
|
if (type === 'SQLSERVER') return 'SQL Server'
|
||||||
|
return type || ''
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="page-card" v-loading="loading">
|
||||||
|
<div class="head">
|
||||||
|
<h3 class="page-title">数据同步</h3>
|
||||||
|
<el-button @click="refresh">刷新</el-button>
|
||||||
|
</div>
|
||||||
|
<p class="tip">
|
||||||
|
四个外部库的地址、查询语句和字段对应都保存在配置里。开发环境连不上外部库时,可以先把配置存好,到现场网络再点测试和手动同步。
|
||||||
|
图书检索结果里常见列名有 title、author、publisher、isbn、publishYear、subject、description、recordId,现场以实际视图列名为准。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<el-tabs v-model="tab">
|
||||||
|
<el-tab-pane label="数据源" name="source">
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-button type="primary" @click="openSource">新增</el-button>
|
||||||
|
</div>
|
||||||
|
<el-table :data="sources" border>
|
||||||
|
<el-table-column prop="name" label="名称" min-width="140" />
|
||||||
|
<el-table-column label="类型" width="120">
|
||||||
|
<template #default="{ row }">{{ dbTypeText(row.dbType) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="地址" min-width="200">
|
||||||
|
<template #default="{ row }">{{ row.host }}:{{ row.port }}/{{ row.dbName }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="username" label="用户名" width="120" />
|
||||||
|
<el-table-column label="状态" width="80">
|
||||||
|
<template #default="{ row }">{{ row.enabled === 0 ? '停用' : '启用' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column label="操作" width="140" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="editSource(row)">编辑</el-button>
|
||||||
|
<el-button link type="danger" @click="removeSource(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<el-tab-pane label="同步任务" name="task">
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-button type="primary" @click="openTask">新增</el-button>
|
||||||
|
</div>
|
||||||
|
<el-table :data="tasks" border>
|
||||||
|
<el-table-column prop="name" label="任务" min-width="140" />
|
||||||
|
<el-table-column prop="datasourceName" label="数据源" min-width="140" />
|
||||||
|
<el-table-column prop="targetTable" label="目标表" width="160" />
|
||||||
|
<el-table-column label="方式" width="90">
|
||||||
|
<template #default="{ row }">{{ row.syncMode === 'INCREMENT' ? '增量' : '全量' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="定时" min-width="160">
|
||||||
|
<template #default="{ row }">{{ row.scheduleEnabled === 1 ? row.cronExpr : '仅手动' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="映射" width="80">
|
||||||
|
<template #default="{ row }">{{ row.mappings?.length || 0 }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="140" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="editTask(row)">编辑</el-button>
|
||||||
|
<el-button link type="danger" @click="removeTask(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<el-tab-pane label="手动同步" name="run">
|
||||||
|
<el-table :data="tasks" border>
|
||||||
|
<el-table-column prop="name" label="任务" min-width="160" />
|
||||||
|
<el-table-column prop="datasourceName" label="数据源" min-width="140" />
|
||||||
|
<el-table-column prop="targetTable" label="写入表" width="160" />
|
||||||
|
<el-table-column prop="batchSize" label="批次" width="80" />
|
||||||
|
<el-table-column prop="retryTimes" label="重试" width="80" />
|
||||||
|
<el-table-column label="状态" width="80">
|
||||||
|
<template #default="{ row }">{{ row.enabled === 0 ? '停用' : '启用' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="120" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
link
|
||||||
|
:loading="runningId === row.id"
|
||||||
|
:disabled="row.enabled === 0"
|
||||||
|
@click="runTask(row)"
|
||||||
|
>
|
||||||
|
手动同步
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<el-tab-pane label="同步日志" name="log">
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-select v-model="logQuery.taskId" clearable placeholder="全部任务" style="width: 220px" @change="logQuery.current = 1; fetchLogs()">
|
||||||
|
<el-option v-for="item in tasks" :key="item.id" :label="item.name" :value="item.id" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
<el-table :data="logs" border>
|
||||||
|
<el-table-column prop="taskName" label="任务" min-width="140" />
|
||||||
|
<el-table-column prop="datasourceName" label="数据源" min-width="120" />
|
||||||
|
<el-table-column label="触发" width="80">
|
||||||
|
<template #default="{ row }">{{ row.triggerType === 'SCHEDULE' ? '定时' : '手动' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="statusType(row.status)" size="small">{{ statusText(row.status) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="successCount" label="成功" width="70" />
|
||||||
|
<el-table-column prop="failCount" label="失败" width="70" />
|
||||||
|
<el-table-column prop="skipCount" label="去重" width="70" />
|
||||||
|
<el-table-column prop="startTime" label="开始" min-width="170" />
|
||||||
|
<el-table-column prop="endTime" label="结束" min-width="170" />
|
||||||
|
<el-table-column prop="errorMessage" label="异常" min-width="220" show-overflow-tooltip />
|
||||||
|
<el-table-column type="expand">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<pre class="detail">{{ row.detail || row.errorMessage || '无详细错误' }}</pre>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div class="pager">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="logQuery.current"
|
||||||
|
v-model:page-size="logQuery.size"
|
||||||
|
layout="total, prev, pager, next"
|
||||||
|
:total="logTotal"
|
||||||
|
@current-change="fetchLogs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
|
||||||
|
<el-dialog v-model="sourceVisible" :title="sourceForm.id ? '编辑数据源' : '新增数据源'" width="640px">
|
||||||
|
<el-form ref="sourceRef" :model="sourceForm" :rules="sourceRules" label-width="108px">
|
||||||
|
<el-form-item label="名称" prop="name">
|
||||||
|
<el-input v-model="sourceForm.name" placeholder="如 一号馆藏库" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="数据库类型" prop="dbType">
|
||||||
|
<el-select v-model="sourceForm.dbType" style="width: 100%" @change="onDbType">
|
||||||
|
<el-option label="PostgreSQL" value="POSTGRESQL" />
|
||||||
|
<el-option label="瀚高" value="HIGHGO" />
|
||||||
|
<el-option label="MySQL" value="MYSQL" />
|
||||||
|
<el-option label="Oracle" value="ORACLE" />
|
||||||
|
<el-option label="SQL Server" value="SQLSERVER" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="地址" prop="host">
|
||||||
|
<el-input v-model="sourceForm.host" placeholder="现场网络中的主机地址" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="端口" prop="port">
|
||||||
|
<el-input-number v-model="sourceForm.port" :min="1" :max="65535" style="width: 100%" />
|
||||||
|
<p class="hint">切换类型会填入常用端口,仍可改成现场实际端口。Oracle 的库名填写服务名。</p>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="数据库名" prop="dbName">
|
||||||
|
<el-input v-model="sourceForm.dbName" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="用户名" prop="username">
|
||||||
|
<el-input v-model="sourceForm.username" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="密码" prop="password">
|
||||||
|
<el-input v-model="sourceForm.password" type="password" show-password :placeholder="sourceForm.id ? '不修改请留空' : '数据库密码'" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="连接参数">
|
||||||
|
<el-input v-model="sourceForm.jdbcParams" placeholder="可空。如 useSSL=false,不要加问号" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="备注">
|
||||||
|
<el-input v-model="sourceForm.remark" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用">
|
||||||
|
<el-switch v-model="sourceForm.enabled" :active-value="1" :inactive-value="0" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button :loading="testing" @click="testSource">测试连通性</el-button>
|
||||||
|
<el-button @click="sourceVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="saveSource">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog v-model="taskVisible" class="sync-task-dialog" :title="taskForm.id ? '编辑同步任务' : '新增同步任务'" width="920px" top="6vh">
|
||||||
|
<el-form ref="taskRef" :model="taskForm" :rules="taskRules" label-width="108px">
|
||||||
|
<el-form-item label="任务名称" prop="name">
|
||||||
|
<el-input v-model="taskForm.name" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="数据源" prop="datasourceId">
|
||||||
|
<el-select v-model="taskForm.datasourceId" style="width: 100%" placeholder="选择已保存的数据源">
|
||||||
|
<el-option v-for="item in sources" :key="item.id" :label="item.name" :value="item.id" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="查询 SQL" prop="querySql">
|
||||||
|
<el-input
|
||||||
|
v-model="taskForm.querySql"
|
||||||
|
type="textarea"
|
||||||
|
:rows="4"
|
||||||
|
placeholder="SELECT title, author FROM 现场视图。增量时在条件里写 ${watermark}"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="目标表" prop="targetTable">
|
||||||
|
<el-select v-model="taskForm.targetTable" filterable style="width: 100%" @change="onTargetTable">
|
||||||
|
<el-option v-for="item in tables" :key="item" :label="item" :value="item" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="字段映射">
|
||||||
|
<div class="map-box">
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-button :loading="previewing" @click="readSourceColumns">读取源字段</el-button>
|
||||||
|
<el-button @click="addMap">新增一行</el-button>
|
||||||
|
</div>
|
||||||
|
<el-table :data="taskForm.mappings" border size="small" max-height="280">
|
||||||
|
<el-table-column label="源字段" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-input v-model="row.sourceField" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="目标字段" min-width="220">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-select v-model="row.targetField" filterable style="width: 100%">
|
||||||
|
<el-option v-for="column in columns" :key="column.name" :label="columnLabel(column)" :value="column.name" />
|
||||||
|
</el-select>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="类型" width="130">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-select v-model="row.dataType">
|
||||||
|
<el-option v-for="item in dataTypes" :key="item" :label="item" :value="item" />
|
||||||
|
</el-select>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="清洗" width="130">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-select v-model="row.cleanRule">
|
||||||
|
<el-option v-for="item in cleanRules" :key="item.value" :label="item.label" :value="item.value" />
|
||||||
|
</el-select>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="必填" width="70">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch v-model="row.requiredFlag" :active-value="1" :inactive-value="0" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="空值默认" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-input v-model="row.defaultValue" placeholder="${today} 等" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="" width="70">
|
||||||
|
<template #default="{ $index }">
|
||||||
|
<el-button link type="danger" @click="removeMap($index)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<p class="hint">默认值可用 ${uuid}、${today}、${year}、${seq}、${task}。读取源字段需要能连上外部库,现场再点。</p>
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="去重字段">
|
||||||
|
<el-input v-model="taskForm.uniqueFields" placeholder="目标表列名,多个用英文逗号,如 process_no" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="批次 / 重试">
|
||||||
|
<el-input-number v-model="taskForm.batchSize" :min="1" :max="2000" />
|
||||||
|
<el-input-number v-model="taskForm.retryTimes" :min="0" :max="5" class="gap" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="同步方式">
|
||||||
|
<el-radio-group v-model="taskForm.syncMode">
|
||||||
|
<el-radio value="FULL">全量</el-radio>
|
||||||
|
<el-radio value="INCREMENT">增量</el-radio>
|
||||||
|
</el-radio-group>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="水位列">
|
||||||
|
<el-input v-model="taskForm.incrementColumn" placeholder="增量时填写来源列名,成功后记下最大值" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="定时">
|
||||||
|
<el-switch v-model="taskForm.scheduleEnabled" :active-value="1" :inactive-value="0" />
|
||||||
|
<el-input v-model="taskForm.cronExpr" class="cron" placeholder="秒 分 时 日 月 周,如 0 0 2 * * ?" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用">
|
||||||
|
<el-switch v-model="taskForm.enabled" :active-value="1" :inactive-value="0" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="taskVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="saveTask">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tip,
|
||||||
|
.hint {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
margin: 6px 0 0;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-box {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pager {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail {
|
||||||
|
margin: 0;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
font-family: inherit;
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gap {
|
||||||
|
margin-left: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cron {
|
||||||
|
width: 280px;
|
||||||
|
margin-left: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.sync-task-dialog.el-dialog {
|
||||||
|
max-height: 88vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-bottom: 4vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sync-task-dialog .el-dialog__body {
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
package com.banben.site;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.nio.charset.CharacterCodingException;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.nio.charset.CharsetDecoder;
|
||||||
|
import java.nio.charset.CodingErrorAction;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 现场离线验证:按配置文件连接外部库,确认端口、账号和查询能不能读到数据。
|
||||||
|
* 不依赖项目里的 Spring,光盘上的 java 目录和 lib 目录就能跑。
|
||||||
|
*/
|
||||||
|
public class SiteProbe {
|
||||||
|
|
||||||
|
private static final Charset GBK = Charset.forName("GBK");
|
||||||
|
private static final int CONNECT_MS = 8000;
|
||||||
|
private static final int QUERY_SECONDS = 30;
|
||||||
|
private static final int SAMPLE_ROWS = 5;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Path config = Path.of(args.length > 0 ? args[0] : "config.txt");
|
||||||
|
Path report = Path.of(args.length > 1 ? args[1] : "result.txt");
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
line(out, "现场库验证");
|
||||||
|
line(out, "时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||||
|
line(out, "配置:" + config.toAbsolutePath());
|
||||||
|
line(out, "");
|
||||||
|
int failed = 0;
|
||||||
|
int checked = 0;
|
||||||
|
try {
|
||||||
|
List<Source> sources = parse(readText(config));
|
||||||
|
if (sources.isEmpty()) {
|
||||||
|
line(out, "配置里没有数据源。请打开 config.txt,按里面的说明填好后再运行。");
|
||||||
|
failed = 1;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < sources.size(); i++) {
|
||||||
|
Source source = sources.get(i);
|
||||||
|
line(out, "======== 第 " + (i + 1) + " 个:" + source.name + " ========");
|
||||||
|
if (source.host.isBlank()) {
|
||||||
|
line(out, "结果:跳过。地址还没填。");
|
||||||
|
line(out, "");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
checked++;
|
||||||
|
if (!probe(source, out)) {
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
line(out, "");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
line(out, "读取配置失败:" + e.getMessage());
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
line(out, checked == 0 ? "没有实际检查任何库。" : (failed == 0 ? "全部通过。" : "有 " + failed + " 个没有通过,看上面的原因。"));
|
||||||
|
String text = out.toString();
|
||||||
|
System.out.print(text);
|
||||||
|
try {
|
||||||
|
Files.writeString(report, text, GBK);
|
||||||
|
System.out.println("结果文件:" + report.toAbsolutePath());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("结果写不进文件(如果程序还在光盘上,请先把整个文件夹复制到桌面再运行):" + e.getMessage());
|
||||||
|
}
|
||||||
|
System.exit(failed == 0 && checked > 0 ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean probe(Source source, StringBuilder out) {
|
||||||
|
if (source.type.isBlank()) {
|
||||||
|
line(out, "结果:失败。类型还没填。只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO。瀚高填 HIGHGO。");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (source.port <= 0 || source.port > 65535) {
|
||||||
|
line(out, "结果:失败。端口还没填,或不是 1 到 65535 的数字。");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
line(out, "类型:" + source.type);
|
||||||
|
line(out, "地址:" + source.host + ":" + source.port + "/" + source.database);
|
||||||
|
line(out, "用户:" + source.user);
|
||||||
|
long started = System.currentTimeMillis();
|
||||||
|
try (Socket socket = new Socket()) {
|
||||||
|
socket.connect(new InetSocketAddress(source.host, source.port), CONNECT_MS);
|
||||||
|
} catch (IOException e) {
|
||||||
|
line(out, "结果:失败。端口不通,还没有检查账号。");
|
||||||
|
line(out, "说明:这台电脑到 " + source.host + ":" + source.port + " 连不上。请核对 IP、端口,以及现场网络是否允许访问。");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
line(out, "端口:通");
|
||||||
|
boolean viewNameMissing = source.sql.contains("【视图名】");
|
||||||
|
String sql = source.sql.isBlank() || viewNameMissing ? pingSql(source.type) : source.sql;
|
||||||
|
boolean business = !source.sql.isBlank() && !viewNameMissing;
|
||||||
|
if (!isSelect(sql)) {
|
||||||
|
line(out, "结果:失败。查询只能写一条 SELECT,不能是增删改。");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Class.forName(driver(source.type));
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
line(out, "结果:失败。光盘里的驱动不完整,缺少 " + source.type + "。");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.setProperty("user", source.user);
|
||||||
|
props.setProperty("password", source.password);
|
||||||
|
if ("ORACLE".equals(source.type)) {
|
||||||
|
props.setProperty("oracle.net.CONNECT_TIMEOUT", String.valueOf(CONNECT_MS));
|
||||||
|
props.setProperty("oracle.jdbc.ReadTimeout", "30000");
|
||||||
|
}
|
||||||
|
try (Connection connection = DriverManager.getConnection(url(source), props);
|
||||||
|
Statement statement = connection.createStatement()) {
|
||||||
|
statement.setQueryTimeout(QUERY_SECONDS);
|
||||||
|
statement.setMaxRows(SAMPLE_ROWS);
|
||||||
|
String product = connection.getMetaData().getDatabaseProductName();
|
||||||
|
String version = connection.getMetaData().getDatabaseProductVersion();
|
||||||
|
line(out, "登录:成功(" + product + " " + oneLine(version, 80) + ")");
|
||||||
|
try (ResultSet rs = statement.executeQuery(sql)) {
|
||||||
|
ResultSetMetaData meta = rs.getMetaData();
|
||||||
|
int columns = Math.min(meta.getColumnCount(), 12);
|
||||||
|
StringBuilder names = new StringBuilder();
|
||||||
|
for (int i = 1; i <= columns; i++) {
|
||||||
|
if (i > 1) {
|
||||||
|
names.append(" | ");
|
||||||
|
}
|
||||||
|
names.append(meta.getColumnLabel(i));
|
||||||
|
}
|
||||||
|
if (meta.getColumnCount() > columns) {
|
||||||
|
names.append(" | ...共 ").append(meta.getColumnCount()).append(" 列");
|
||||||
|
}
|
||||||
|
int rows = 0;
|
||||||
|
List<String> samples = new ArrayList<>();
|
||||||
|
while (rs.next()) {
|
||||||
|
rows++;
|
||||||
|
if (samples.size() < SAMPLE_ROWS) {
|
||||||
|
StringBuilder row = new StringBuilder();
|
||||||
|
for (int i = 1; i <= columns; i++) {
|
||||||
|
if (i > 1) {
|
||||||
|
row.append(" | ");
|
||||||
|
}
|
||||||
|
row.append(oneLine(rs.getString(i), 40));
|
||||||
|
}
|
||||||
|
samples.add(row.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line(out, "查询:成功,返回 " + rows + " 行" + (business ? "(最多展示 " + SAMPLE_ROWS + " 行)" : "(这条只证明账号能执行查询)"));
|
||||||
|
line(out, "列名:" + names);
|
||||||
|
for (int i = 0; i < samples.size(); i++) {
|
||||||
|
line(out, "第" + (i + 1) + "行:" + samples.get(i));
|
||||||
|
}
|
||||||
|
if (viewNameMissing) {
|
||||||
|
line(out, "注意:账号已经能登录。查询里的【视图名】还没改成陆工大现场的真实视图名,所以这次还没有读到图书数据。改完后再运行一次。");
|
||||||
|
} else if (!business) {
|
||||||
|
line(out, "注意:查询那一行还是空的,现在只能说明库能登录。把现场的表或视图写进查询后,再运行一次,才能确认业务数据。");
|
||||||
|
} else if (rows == 0) {
|
||||||
|
line(out, "注意:语句执行了,但没有行。请确认表名、视图名和筛选条件。");
|
||||||
|
} else {
|
||||||
|
line(out, "结论:这个库可以读到数据。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line(out, "耗时:" + (System.currentTimeMillis() - started) + " 毫秒");
|
||||||
|
return business;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
line(out, "结果:失败。" + explain(e, source.password));
|
||||||
|
line(out, "耗时:" + (System.currentTimeMillis() - started) + " 毫秒");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isSelect(String sql) {
|
||||||
|
String text = sql.trim();
|
||||||
|
if (text.endsWith(";")) {
|
||||||
|
text = text.substring(0, text.length() - 1).trim();
|
||||||
|
}
|
||||||
|
if (text.indexOf(';') >= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String head = text.toLowerCase(Locale.ROOT);
|
||||||
|
return head.startsWith("select") || head.startsWith("with");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String pingSql(String type) {
|
||||||
|
return "ORACLE".equals(type) ? "SELECT 1 FROM dual" : "SELECT 1";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String driver(String type) {
|
||||||
|
return switch (type) {
|
||||||
|
case "MYSQL" -> "com.mysql.cj.jdbc.Driver";
|
||||||
|
case "ORACLE" -> "oracle.jdbc.OracleDriver";
|
||||||
|
case "SQLSERVER" -> "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
||||||
|
case "POSTGRESQL", "HIGHGO" -> "org.postgresql.Driver";
|
||||||
|
default -> throw new IllegalArgumentException("类型只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String url(Source source) {
|
||||||
|
return switch (source.type) {
|
||||||
|
case "MYSQL" -> "jdbc:mysql://" + source.host + ":" + source.port + "/" + source.database
|
||||||
|
+ "?useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&connectTimeout=" + CONNECT_MS;
|
||||||
|
case "ORACLE" -> "jdbc:oracle:thin:@//" + source.host + ":" + source.port + "/" + source.database;
|
||||||
|
case "SQLSERVER" -> "jdbc:sqlserver://" + source.host + ":" + source.port
|
||||||
|
+ ";databaseName=" + source.database + ";encrypt=false;trustServerCertificate=true;loginTimeout=8";
|
||||||
|
case "POSTGRESQL", "HIGHGO" -> "jdbc:postgresql://" + source.host + ":" + source.port + "/" + source.database
|
||||||
|
+ "?connectTimeout=8";
|
||||||
|
default -> throw new IllegalArgumentException("类型只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String explain(SQLException exception, String password) {
|
||||||
|
String message = exception.getMessage() == null ? "查询失败" : exception.getMessage();
|
||||||
|
String lower = message.toLowerCase(Locale.ROOT);
|
||||||
|
String text;
|
||||||
|
if (lower.contains("access denied") || lower.contains("password authentication failed")
|
||||||
|
|| lower.contains("login failed") || lower.contains("ora-01017")) {
|
||||||
|
text = "用户名或密码错误";
|
||||||
|
} else if (lower.contains("unknown database") || lower.contains("does not exist")
|
||||||
|
|| lower.contains("ora-12514") || lower.contains("cannot open database")) {
|
||||||
|
text = "库名不对。Oracle 的库名要填服务名";
|
||||||
|
} else if (lower.contains("timeout") || lower.contains("timed out")) {
|
||||||
|
text = "登录或查询超时";
|
||||||
|
} else {
|
||||||
|
text = oneLine(message, 300);
|
||||||
|
}
|
||||||
|
if (password != null && !password.isBlank()) {
|
||||||
|
text = text.replace(password, "******");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Source> parse(String text) {
|
||||||
|
List<Source> sources = new ArrayList<>();
|
||||||
|
Source current = null;
|
||||||
|
for (String raw : text.split("\\R")) {
|
||||||
|
String line = raw.trim();
|
||||||
|
if (line.isEmpty() || line.startsWith("#")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ("[数据源]".equals(line)) {
|
||||||
|
current = new Source();
|
||||||
|
sources.add(current);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int split = line.indexOf('=');
|
||||||
|
if (split <= 0 || current == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String key = line.substring(0, split).trim();
|
||||||
|
String value = line.substring(split + 1).trim();
|
||||||
|
switch (key) {
|
||||||
|
case "名称" -> current.name = value.isBlank() ? "未命名" : value;
|
||||||
|
case "类型" -> current.type = value.isBlank() ? "" : normalizeType(value);
|
||||||
|
case "地址" -> current.host = value;
|
||||||
|
case "端口" -> current.port = value.isBlank() ? 0 : parsePort(value);
|
||||||
|
case "库名" -> current.database = value;
|
||||||
|
case "用户名" -> current.user = value;
|
||||||
|
case "密码" -> current.password = value;
|
||||||
|
case "查询" -> current.sql = placeholder(value) ? "" : strip(value);
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sources;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean placeholder(String value) {
|
||||||
|
return value.isBlank() || value.contains("这里换成") || value.contains("现场填写");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String strip(String sql) {
|
||||||
|
String text = sql.trim();
|
||||||
|
if (text.endsWith(";")) {
|
||||||
|
text = text.substring(0, text.length() - 1).trim();
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeType(String value) {
|
||||||
|
String text = value.trim().toUpperCase(Locale.ROOT).replace(" ", "");
|
||||||
|
return switch (text) {
|
||||||
|
case "MYSQL" -> "MYSQL";
|
||||||
|
case "ORACLE" -> "ORACLE";
|
||||||
|
case "SQLSERVER", "MSSQL" -> "SQLSERVER";
|
||||||
|
case "POSTGRESQL", "POSTGRES", "PG" -> "POSTGRESQL";
|
||||||
|
case "HIGHGO", "瀚高" -> "HIGHGO";
|
||||||
|
default -> throw new IllegalArgumentException("无法识别的数据库类型:" + value);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int parsePort(String value) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(value.trim());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw new IllegalArgumentException("端口不是数字:" + value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readText(Path path) throws IOException {
|
||||||
|
if (!Files.exists(path)) {
|
||||||
|
throw new IllegalArgumentException("找不到配置文件 " + path.toAbsolutePath());
|
||||||
|
}
|
||||||
|
byte[] bytes = Files.readAllBytes(path);
|
||||||
|
if (bytes.length >= 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
|
||||||
|
return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
|
||||||
|
.onMalformedInput(CodingErrorAction.REPORT)
|
||||||
|
.onUnmappableCharacter(CodingErrorAction.REPORT);
|
||||||
|
try {
|
||||||
|
return decoder.decode(java.nio.ByteBuffer.wrap(bytes)).toString();
|
||||||
|
} catch (CharacterCodingException e) {
|
||||||
|
return new String(bytes, GBK);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String oneLine(String text, int max) {
|
||||||
|
if (text == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String flat = text.replace('\r', ' ').replace('\n', ' ').trim();
|
||||||
|
return flat.length() <= max ? flat : flat.substring(0, max) + "...";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void line(StringBuilder out, String text) {
|
||||||
|
out.append(text).append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Source {
|
||||||
|
private String name = "未命名";
|
||||||
|
private String type = "";
|
||||||
|
private String host = "";
|
||||||
|
private int port = 5432;
|
||||||
|
private String database = "";
|
||||||
|
private String user = "";
|
||||||
|
private String password = "";
|
||||||
|
private String sql = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user