Compare commits
38 Commits
09b8a39ec5
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
| eb985706c4 | |||
| 37566e9d7e | |||
| f1765c039c | |||
| 7794716861 | |||
| 3d2a3e7766 | |||
| 5cf7b35a58 | |||
| 7438f558e2 | |||
| 0b5c0a40e9 | |||
| 4f3fc578d0 | |||
| 0d8fdbd35a | |||
| b76a7ccce4 | |||
| f4f24398ee | |||
| 8546afa24e | |||
| 3dca829cf3 | |||
| a2ea2389e5 | |||
| 8bdaafb69b | |||
| 28fd91e46e | |||
| f1e68697b5 | |||
| 3a0705692a | |||
| f02323e350 | |||
| 7024ad09ac | |||
| 4e5eb6ca5b | |||
| b24c5e3849 | |||
| 4990a48b2c | |||
| 6998d6c805 | |||
| 7d87511790 | |||
| 72b6804dad | |||
| e8455c7ba6 | |||
| 66c3b73c3f | |||
| 94b7c8010a | |||
| 3e3a1b8465 | |||
| b522734c92 | |||
| ddc0864f06 | |||
| 8b6f00b117 | |||
| 20660da286 | |||
| a68f27f7f2 | |||
| b735c1465a | |||
| 3626939ccb |
@@ -63,6 +63,29 @@
|
|||||||
<artifactId>postgresql</artifactId>
|
<artifactId>postgresql</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- 现场外部库可能是 Oracle / SQL Server,驱动随包提供,连接信息仍从配置表读取 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.oracle.database.jdbc</groupId>
|
||||||
|
<artifactId>ojdbc11</artifactId>
|
||||||
|
<version>23.4.0.24.05</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.microsoft.sqlserver</groupId>
|
||||||
|
<artifactId>mssql-jdbc</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- 南昌总库汇总用 Elasticsearch。连不上时开发配置可改走本地表,避免拖垮已有业务。 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>co.elastic.clients</groupId>
|
||||||
|
<artifactId>elasticsearch-java</artifactId>
|
||||||
|
<version>8.13.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- 连接池 -->
|
<!-- 连接池 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -84,6 +107,13 @@
|
|||||||
<version>${hutool.version}</version>
|
<version>${hutool.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Excel 导入导出 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-ooxml</artifactId>
|
||||||
|
<version>5.2.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- JWT -->
|
<!-- JWT -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.jsonwebtoken</groupId>
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package com.banben.config;
|
package com.banben.config;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.service.RoleService;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -21,28 +24,56 @@ import org.springframework.stereotype.Component;
|
|||||||
public class DataInitializer implements ApplicationRunner {
|
public class DataInitializer implements ApplicationRunner {
|
||||||
|
|
||||||
private final SysUserMapper sysUserMapper;
|
private final SysUserMapper sysUserMapper;
|
||||||
|
private final SysRoleMapper sysRoleMapper;
|
||||||
|
private final RoleService roleService;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) {
|
public void run(ApplicationArguments args) {
|
||||||
|
ensureRoles();
|
||||||
try {
|
try {
|
||||||
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
|
||||||
wrapper.eq(SysUser::getUsername, "admin");
|
wrapper.eq(SysUser::getUsername, "admin");
|
||||||
Long count = sysUserMapper.selectCount(wrapper);
|
Long count = sysUserMapper.selectCount(wrapper);
|
||||||
if (count != null && count > 0) {
|
if (count == null || count == 0) {
|
||||||
return;
|
SysUser admin = new SysUser();
|
||||||
|
admin.setUsername("admin");
|
||||||
|
admin.setPassword(passwordEncoder.encode("admin123"));
|
||||||
|
admin.setRealName("系统管理员");
|
||||||
|
admin.setRole("ADMIN");
|
||||||
|
admin.setOrgName("版本资源联合服务中心");
|
||||||
|
admin.setStatus(1);
|
||||||
|
sysUserMapper.insert(admin);
|
||||||
|
log.info("已创建默认管理员账号:admin / admin123");
|
||||||
}
|
}
|
||||||
SysUser admin = new SysUser();
|
|
||||||
admin.setUsername("admin");
|
|
||||||
admin.setPassword(passwordEncoder.encode("admin123"));
|
|
||||||
admin.setRealName("系统管理员");
|
|
||||||
admin.setRole("ADMIN");
|
|
||||||
admin.setOrgName("版本资源联合服务中心");
|
|
||||||
admin.setStatus(1);
|
|
||||||
sysUserMapper.insert(admin);
|
|
||||||
log.info("已创建默认管理员账号:admin / admin123");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
|
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
bindAdminRole();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureRoles() {
|
||||||
|
try {
|
||||||
|
roleService.ensureBuiltin();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("初始化内置角色失败(可能表未创建):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void bindAdminRole() {
|
||||||
|
try {
|
||||||
|
SysRole adminRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, "ADMIN"));
|
||||||
|
if (adminRole == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SysUser admin = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, "admin"));
|
||||||
|
if (admin != null && admin.getRoleId() == null) {
|
||||||
|
admin.setRoleId(adminRole.getId());
|
||||||
|
admin.setRole("ADMIN");
|
||||||
|
sysUserMapper.updateById(admin);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("回填管理员角色失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.banben.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
|
||||||
|
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一 java.time 类型的 JSON 序列化格式。
|
||||||
|
*
|
||||||
|
* <p>Spring 的 {@code spring.jackson.date-format} 只作用于 {@code java.util.Date},
|
||||||
|
* 对 {@code LocalDateTime/LocalDate/LocalTime} 默认序列化为带 T 的 ISO-8601(如 2026-11-04T10:30:00),
|
||||||
|
* 前端展示与解析都不友好。这里统一改为可读格式:</p>
|
||||||
|
* <ul>
|
||||||
|
* <li>LocalDateTime → yyyy-MM-dd HH:mm:ss</li>
|
||||||
|
* <li>LocalDate → yyyy-MM-dd</li>
|
||||||
|
* <li>LocalTime → HH:mm:ss</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class JacksonConfig {
|
||||||
|
|
||||||
|
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
|
||||||
|
private static final String DATE_PATTERN = "yyyy-MM-dd";
|
||||||
|
private static final String TIME_PATTERN = "HH:mm:ss";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
|
||||||
|
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
|
||||||
|
DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERN);
|
||||||
|
DateTimeFormatter tf = DateTimeFormatter.ofPattern(TIME_PATTERN);
|
||||||
|
return builder -> builder
|
||||||
|
.serializerByType(java.time.LocalDateTime.class, new LocalDateTimeSerializer(dtf))
|
||||||
|
.serializerByType(java.time.LocalDate.class, new LocalDateSerializer(df))
|
||||||
|
.serializerByType(java.time.LocalTime.class, new LocalTimeSerializer(tf))
|
||||||
|
.deserializerByType(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(dtf))
|
||||||
|
.deserializerByType(java.time.LocalDate.class, new LocalDateDeserializer(df))
|
||||||
|
.deserializerByType(java.time.LocalTime.class, new LocalTimeDeserializer(tf));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.banben.config;
|
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/**");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.banben.modules.admin.controller;
|
||||||
|
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.entity.ListFieldConfig;
|
||||||
|
import com.banben.modules.admin.service.ListFieldConfigService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台管理 - 列表显示字段配置。
|
||||||
|
*
|
||||||
|
* <p>控制检索结果列表展示哪些字段、显示名与顺序。</p>
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-列表字段配置")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/list-fields")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ListFieldConfigController {
|
||||||
|
|
||||||
|
private final ListFieldConfigService listFieldConfigService;
|
||||||
|
|
||||||
|
@Operation(summary = "查询场景的展示字段配置(为空时返回并写入默认配置)")
|
||||||
|
@GetMapping("/{scene}")
|
||||||
|
public Result<List<ListFieldConfig>> list(@PathVariable String scene) {
|
||||||
|
return Result.success(listFieldConfigService.listScene(scene));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "全量覆盖保存展示字段配置")
|
||||||
|
@PutMapping("/{scene}")
|
||||||
|
public Result<Void> save(@PathVariable String scene, @RequestBody List<ListFieldConfig> items) {
|
||||||
|
listFieldConfigService.saveScene(scene, items);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "恢复场景默认展示字段")
|
||||||
|
@PostMapping("/{scene}/reset")
|
||||||
|
public Result<List<ListFieldConfig>> reset(@PathVariable String scene) {
|
||||||
|
return Result.success(listFieldConfigService.resetScene(scene));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package com.banben.modules.admin.controller;
|
||||||
|
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||||
|
import com.banben.modules.admin.service.OrgService;
|
||||||
|
import com.banben.modules.admin.support.AdminAccess;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多层级组织管理。
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-组织")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/orgs")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class OrgController {
|
||||||
|
|
||||||
|
private final OrgService orgService;
|
||||||
|
private final AdminAccess adminAccess;
|
||||||
|
|
||||||
|
@Operation(summary = "组织树")
|
||||||
|
@GetMapping("/tree")
|
||||||
|
public Result<List<OrgTreeVO>> tree() {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(orgService.tree());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增组织")
|
||||||
|
@PostMapping
|
||||||
|
public Result<Void> create(@Valid @RequestBody OrgSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
orgService.create(request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改组织")
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody OrgSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
orgService.update(id, request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除组织")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public Result<Void> remove(@PathVariable Long id) {
|
||||||
|
adminAccess.require();
|
||||||
|
orgService.remove(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package com.banben.modules.admin.controller;
|
||||||
|
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.service.RoleService;
|
||||||
|
import com.banben.modules.admin.support.AdminAccess;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色管理。
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-角色")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/roles")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RoleController {
|
||||||
|
|
||||||
|
private final RoleService roleService;
|
||||||
|
private final AdminAccess adminAccess;
|
||||||
|
|
||||||
|
@Operation(summary = "角色列表")
|
||||||
|
@GetMapping
|
||||||
|
public Result<List<SysRole>> list() {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(roleService.listAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增角色")
|
||||||
|
@PostMapping
|
||||||
|
public Result<Void> create(@Valid @RequestBody RoleSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
roleService.create(request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改角色")
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RoleSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
roleService.update(id, request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除角色")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public Result<Void> remove(@PathVariable Long id) {
|
||||||
|
adminAccess.require();
|
||||||
|
roleService.remove(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.banben.modules.admin.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.UserVO;
|
||||||
|
import com.banben.modules.admin.service.UserAdminService;
|
||||||
|
import com.banben.modules.admin.service.UserExcelService;
|
||||||
|
import com.banben.modules.admin.support.AdminAccess;
|
||||||
|
import com.banben.modules.resource.dto.ImportResult;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户管理,含导入模板导出和批量导入。
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-用户")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/users")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserAdminController {
|
||||||
|
|
||||||
|
private final UserAdminService userAdminService;
|
||||||
|
private final UserExcelService userExcelService;
|
||||||
|
private final AdminAccess adminAccess;
|
||||||
|
|
||||||
|
@Operation(summary = "分页查询用户")
|
||||||
|
@GetMapping("/page")
|
||||||
|
public Result<Page<UserVO>> page(@RequestParam(defaultValue = "1") long current,
|
||||||
|
@RequestParam(defaultValue = "10") long size,
|
||||||
|
@RequestParam(required = false) String keyword,
|
||||||
|
@RequestParam(required = false) Long orgId,
|
||||||
|
@RequestParam(required = false) Long roleId) {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(userAdminService.page(current, size, keyword, orgId, roleId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增用户")
|
||||||
|
@PostMapping
|
||||||
|
public Result<Void> create(@Valid @RequestBody UserSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
userAdminService.create(request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改用户")
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserSaveRequest request) {
|
||||||
|
adminAccess.require();
|
||||||
|
userAdminService.update(id, request);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除用户")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public Result<Void> remove(@PathVariable Long id) {
|
||||||
|
adminAccess.require();
|
||||||
|
userAdminService.remove(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "导出用户导入模板")
|
||||||
|
@GetMapping("/import-template")
|
||||||
|
public void template(jakarta.servlet.http.HttpServletResponse response) throws IOException {
|
||||||
|
adminAccess.require();
|
||||||
|
String fileName = URLEncoder.encode("用户导入模板.xlsx", StandardCharsets.UTF_8);
|
||||||
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
|
response.setCharacterEncoding("UTF-8");
|
||||||
|
response.setHeader("Content-Disposition",
|
||||||
|
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
|
||||||
|
userExcelService.writeTemplate(response.getOutputStream());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "批量导入用户")
|
||||||
|
@PostMapping("/import")
|
||||||
|
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(userExcelService.importExcel(file));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.admin.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增或修改组织。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class OrgSaveRequest {
|
||||||
|
|
||||||
|
/** 上级组织,空表示顶级 */
|
||||||
|
private Long parentId;
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写组织名称")
|
||||||
|
@Size(max = 128, message = "组织名称不能超过128字")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Size(max = 64, message = "组织编码不能超过64字")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
private Integer sortNo;
|
||||||
|
|
||||||
|
/** 1启用 0停用 */
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Size(max = 256, message = "备注不能超过256字")
|
||||||
|
private String remark;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.banben.modules.admin.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组织树节点。叶子节点不带 children。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class OrgTreeVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private Long parentId;
|
||||||
|
private String name;
|
||||||
|
private String code;
|
||||||
|
private Integer sortNo;
|
||||||
|
private Integer status;
|
||||||
|
private String remark;
|
||||||
|
private List<OrgTreeVO> children;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.banben.modules.admin.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增或修改角色。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class RoleSaveRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写角色编码")
|
||||||
|
@Size(max = 32, message = "角色编码不能超过32字")
|
||||||
|
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]{0,31}", message = "角色编码需以字母开头,只能包含字母、数字和下划线")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写角色名称")
|
||||||
|
@Size(max = 64, message = "角色名称不能超过64字")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Size(max = 256, message = "备注不能超过256字")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
/** 1启用 0停用 */
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
/** 顶部导航编码。空列表表示该角色看不到任何顶部栏目。 */
|
||||||
|
private List<String> menuCodes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.banben.modules.admin.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增或修改用户。修改时密码留空表示不改密码。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class UserSaveRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写登录账号")
|
||||||
|
@Size(max = 64, message = "登录账号不能超过64字")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Size(max = 64, message = "密码不能超过64字")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@NotBlank(message = "请填写姓名")
|
||||||
|
@Size(max = 128, message = "姓名不能超过128字")
|
||||||
|
private String realName;
|
||||||
|
|
||||||
|
@NotNull(message = "请选择角色")
|
||||||
|
private Long roleId;
|
||||||
|
|
||||||
|
private Long orgId;
|
||||||
|
|
||||||
|
/** 1启用 0停用 */
|
||||||
|
private Integer status;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.banben.modules.admin.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户列表行,不包含密码。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class UserVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String username;
|
||||||
|
private String realName;
|
||||||
|
private Long roleId;
|
||||||
|
private String roleCode;
|
||||||
|
private String roleName;
|
||||||
|
private Long orgId;
|
||||||
|
private String orgName;
|
||||||
|
private Integer status;
|
||||||
|
private LocalDateTime lastLoginTime;
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.banben.modules.admin.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表显示字段配置(检索结果列表展示哪些字段、显示名与顺序)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("list_field_config")
|
||||||
|
@Schema(description = "列表显示字段配置")
|
||||||
|
public class ListFieldConfig implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "配置场景:SEARCH 检索结果列表")
|
||||||
|
private String scene;
|
||||||
|
|
||||||
|
@Schema(description = "字段键,对应 VersionResource 的驼峰属性名")
|
||||||
|
private String fieldKey;
|
||||||
|
|
||||||
|
@Schema(description = "列表与导出时的显示名")
|
||||||
|
private String fieldLabel;
|
||||||
|
|
||||||
|
@Schema(description = "展示顺序,数值小的靠前")
|
||||||
|
private Integer sortNo;
|
||||||
|
|
||||||
|
@Schema(description = "是否显示:1显示 0隐藏")
|
||||||
|
private Integer visible;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.banben.modules.admin.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多层级组织。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sys_org")
|
||||||
|
@Schema(description = "组织")
|
||||||
|
public class SysOrg implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "上级组织,空为顶级")
|
||||||
|
private Long parentId;
|
||||||
|
|
||||||
|
@Schema(description = "组织名称")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "组织编码")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
@Schema(description = "同级排序,小的在前")
|
||||||
|
private Integer sortNo;
|
||||||
|
|
||||||
|
@Schema(description = "1启用 0停用")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.banben.modules.admin.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色。内置角色不可删除,编码供登录令牌使用。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sys_role")
|
||||||
|
@Schema(description = "角色")
|
||||||
|
public class SysRole implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "角色编码")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
@Schema(description = "角色名称")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "备注")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
@Schema(description = "1启用 0停用")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Schema(description = "1内置 0自建")
|
||||||
|
private Integer builtin;
|
||||||
|
|
||||||
|
@Schema(description = "1表示顶部导航已初始化")
|
||||||
|
private Integer menuInited;
|
||||||
|
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "可访问的顶部导航编码")
|
||||||
|
private List<String> menuCodes = new ArrayList<>();
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.banben.modules.admin.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色与顶部导航的对应关系。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sys_role_menu")
|
||||||
|
public class SysRoleMenu implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private Long roleId;
|
||||||
|
|
||||||
|
private String menuCode;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.banben.modules.admin.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.admin.entity.ListFieldConfig;
|
||||||
|
|
||||||
|
/** 列表显示字段配置 Mapper。 */
|
||||||
|
public interface ListFieldConfigMapper extends BaseMapper<ListFieldConfig> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.admin.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.admin.entity.SysOrg;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组织 Mapper。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface SysOrgMapper extends BaseMapper<SysOrg> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.admin.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色 Mapper。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface SysRoleMapper extends BaseMapper<SysRole> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.banben.modules.admin.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色导航权限。
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.banben.modules.admin.service;
|
||||||
|
|
||||||
|
import com.banben.modules.admin.entity.ListFieldConfig;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表显示字段配置服务。
|
||||||
|
*
|
||||||
|
* <p>管理员可在后台调整检索结果列表展示的字段、显示名与顺序。</p>
|
||||||
|
*/
|
||||||
|
public interface ListFieldConfigService {
|
||||||
|
|
||||||
|
/** 查询场景配置(为空时自动写入默认字段),按 sort_no 升序 */
|
||||||
|
List<ListFieldConfig> listScene(String scene);
|
||||||
|
|
||||||
|
/** 全量覆盖保存场景配置 */
|
||||||
|
void saveScene(String scene, List<ListFieldConfig> items);
|
||||||
|
|
||||||
|
/** 恢复场景默认配置 */
|
||||||
|
List<ListFieldConfig> resetScene(String scene);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.banben.modules.admin.service;
|
||||||
|
|
||||||
|
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多层级组织。
|
||||||
|
*/
|
||||||
|
public interface OrgService {
|
||||||
|
|
||||||
|
List<OrgTreeVO> tree();
|
||||||
|
|
||||||
|
void create(OrgSaveRequest request);
|
||||||
|
|
||||||
|
void update(Long id, OrgSaveRequest request);
|
||||||
|
|
||||||
|
void remove(Long id);
|
||||||
|
|
||||||
|
/** 本级及全部下级的 id,含自身。 */
|
||||||
|
Set<Long> subtreeIds(Long orgId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.banben.modules.admin.service;
|
||||||
|
|
||||||
|
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色维护。内置角色不可删除,编码变更时同步用户表上的角色编码。
|
||||||
|
*/
|
||||||
|
public interface RoleService {
|
||||||
|
|
||||||
|
List<SysRole> listAll();
|
||||||
|
|
||||||
|
void create(RoleSaveRequest request);
|
||||||
|
|
||||||
|
void update(Long id, RoleSaveRequest request);
|
||||||
|
|
||||||
|
void remove(Long id);
|
||||||
|
|
||||||
|
void ensureBuiltin();
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.banben.modules.admin.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.UserVO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户管理。
|
||||||
|
*/
|
||||||
|
public interface UserAdminService {
|
||||||
|
|
||||||
|
Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId);
|
||||||
|
|
||||||
|
void create(UserSaveRequest request);
|
||||||
|
|
||||||
|
void update(Long id, UserSaveRequest request);
|
||||||
|
|
||||||
|
void remove(Long id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
package com.banben.modules.admin.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||||
|
import com.banben.modules.admin.entity.SysOrg;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import com.banben.modules.resource.dto.ImportResult;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
|
import org.apache.poi.ss.usermodel.CellStyle;
|
||||||
|
import org.apache.poi.ss.usermodel.DataFormatter;
|
||||||
|
import org.apache.poi.ss.usermodel.DataValidation;
|
||||||
|
import org.apache.poi.ss.usermodel.DataValidationConstraint;
|
||||||
|
import org.apache.poi.ss.usermodel.DataValidationHelper;
|
||||||
|
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||||
|
import org.apache.poi.ss.usermodel.Font;
|
||||||
|
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||||
|
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||||
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
|
import org.apache.poi.ss.usermodel.Sheet;
|
||||||
|
import org.apache.poi.ss.usermodel.VerticalAlignment;
|
||||||
|
import org.apache.poi.ss.usermodel.Workbook;
|
||||||
|
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||||
|
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户导入模板与批量导入。
|
||||||
|
*
|
||||||
|
* <p>模板第 1 行是表头,第 2 行是说明,第 3 行起为数据。账号已存在时更新该用户,密码留空则不改原密码。</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserExcelService {
|
||||||
|
|
||||||
|
private static final String[] HEADERS = {"登录账号*", "姓名*", "初始密码", "角色编码*", "组织编码", "状态"};
|
||||||
|
private static final String[] HINTS = {
|
||||||
|
"必填。示例行以「示例:」开头,导入时自动跳过",
|
||||||
|
"必填",
|
||||||
|
"选填。新增留空则为 123456;更新留空则不修改密码",
|
||||||
|
"必填。填角色编码,见「可选数据」页",
|
||||||
|
"选填。填组织编码,或「上级/本级」路径",
|
||||||
|
"选填。启用 或 停用,默认启用"
|
||||||
|
};
|
||||||
|
private static final String[] SAMPLE = {"示例:zhangsan", "张三", "123456", "USER", "", "启用"};
|
||||||
|
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
private final SysRoleMapper roleMapper;
|
||||||
|
private final SysOrgMapper orgMapper;
|
||||||
|
private final UserAdminService userAdminService;
|
||||||
|
private final DataFormatter formatter = new DataFormatter();
|
||||||
|
|
||||||
|
public void writeTemplate(OutputStream out) throws IOException {
|
||||||
|
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>().orderByAsc(SysRole::getId));
|
||||||
|
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>().orderByAsc(SysOrg::getSortNo).orderByAsc(SysOrg::getId));
|
||||||
|
Map<Long, SysOrg> byId = new HashMap<>();
|
||||||
|
for (SysOrg org : orgs) {
|
||||||
|
byId.put(org.getId(), org);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
|
Sheet sheet = wb.createSheet("用户");
|
||||||
|
CellStyle headStyle = headStyle(wb);
|
||||||
|
CellStyle hintStyle = hintStyle(wb);
|
||||||
|
Row head = sheet.createRow(0);
|
||||||
|
Row hint = sheet.createRow(1);
|
||||||
|
head.setHeightInPoints(22);
|
||||||
|
hint.setHeightInPoints(32);
|
||||||
|
int[] widths = {22, 16, 28, 22, 28, 16};
|
||||||
|
for (int i = 0; i < HEADERS.length; i++) {
|
||||||
|
Cell h = head.createCell(i);
|
||||||
|
h.setCellValue(HEADERS[i]);
|
||||||
|
h.setCellStyle(headStyle);
|
||||||
|
Cell t = hint.createCell(i);
|
||||||
|
t.setCellValue(HINTS[i]);
|
||||||
|
t.setCellStyle(hintStyle);
|
||||||
|
sheet.setColumnWidth(i, widths[i] * 256);
|
||||||
|
}
|
||||||
|
Row sample = sheet.createRow(2);
|
||||||
|
for (int i = 0; i < SAMPLE.length; i++) {
|
||||||
|
sample.createCell(i).setCellValue(SAMPLE[i]);
|
||||||
|
}
|
||||||
|
sheet.createFreezePane(0, 2);
|
||||||
|
|
||||||
|
Sheet dict = wb.createSheet("可选数据");
|
||||||
|
Row dictHead = dict.createRow(0);
|
||||||
|
dictHead.createCell(0).setCellValue("角色编码");
|
||||||
|
dictHead.createCell(1).setCellValue("角色名称");
|
||||||
|
dictHead.createCell(2).setCellValue("组织编码");
|
||||||
|
dictHead.createCell(3).setCellValue("组织路径");
|
||||||
|
for (int i = 0; i < roles.size(); i++) {
|
||||||
|
Row row = dict.createRow(i + 1);
|
||||||
|
row.createCell(0).setCellValue(roles.get(i).getCode());
|
||||||
|
row.createCell(1).setCellValue(roles.get(i).getName());
|
||||||
|
}
|
||||||
|
int orgRow = 1;
|
||||||
|
for (SysOrg org : orgs) {
|
||||||
|
Row row = dict.getRow(orgRow);
|
||||||
|
if (row == null) {
|
||||||
|
row = dict.createRow(orgRow);
|
||||||
|
}
|
||||||
|
row.createCell(2).setCellValue(org.getCode() == null ? "" : org.getCode());
|
||||||
|
row.createCell(3).setCellValue(pathOf(org, byId));
|
||||||
|
orgRow++;
|
||||||
|
}
|
||||||
|
dict.setColumnWidth(0, 18 * 256);
|
||||||
|
dict.setColumnWidth(1, 18 * 256);
|
||||||
|
dict.setColumnWidth(2, 18 * 256);
|
||||||
|
dict.setColumnWidth(3, 36 * 256);
|
||||||
|
|
||||||
|
if (!roles.isEmpty()) {
|
||||||
|
dropdown(sheet, 3, "'可选数据'!$A$2:$A$" + (roles.size() + 1));
|
||||||
|
}
|
||||||
|
dropdown(sheet, 5, "\"启用,停用\"");
|
||||||
|
wb.setActiveSheet(0);
|
||||||
|
wb.write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImportResult importExcel(MultipartFile file) throws IOException {
|
||||||
|
ImportResult result = new ImportResult();
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
result.addError(0, "请选择要导入的 Excel 文件");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>());
|
||||||
|
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>());
|
||||||
|
Map<Long, SysOrg> byId = new HashMap<>();
|
||||||
|
for (SysOrg org : orgs) {
|
||||||
|
byId.put(org.getId(), org);
|
||||||
|
}
|
||||||
|
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
|
||||||
|
Sheet sheet = wb.getNumberOfSheets() == 0 ? null : wb.getSheetAt(0);
|
||||||
|
if (sheet == null || sheet.getLastRowNum() < 1) {
|
||||||
|
result.addError(0, "表格为空,请使用系统导出的导入模板");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
Map<String, Integer> columns = headerIndex(sheet.getRow(0));
|
||||||
|
if (!columns.containsKey("登录账号") || !columns.containsKey("姓名") || !columns.containsKey("角色编码")) {
|
||||||
|
result.addError(1, "表头缺少登录账号、姓名或角色编码,请使用系统导出的导入模板");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
int start = hintRow(sheet) ? 2 : 1;
|
||||||
|
for (int r = start; r <= sheet.getLastRowNum(); r++) {
|
||||||
|
Row row = sheet.getRow(r);
|
||||||
|
if (row == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String username = cell(row, columns.get("登录账号"));
|
||||||
|
String realName = cell(row, columns.get("姓名"));
|
||||||
|
String password = cell(row, columns.get("初始密码"));
|
||||||
|
String roleText = cell(row, columns.get("角色编码"));
|
||||||
|
String orgText = cell(row, columns.get("组织编码"));
|
||||||
|
String statusText = cell(row, columns.get("状态"));
|
||||||
|
if (!StringUtils.hasText(username) && !StringUtils.hasText(realName)
|
||||||
|
&& !StringUtils.hasText(roleText)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int excelRow = r + 1;
|
||||||
|
if (isSample(username) || isSample(realName)) {
|
||||||
|
result.setSkipped(result.getSkipped() + 1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.setTotal(result.getTotal() + 1);
|
||||||
|
try {
|
||||||
|
importRow(username, realName, password, roleText, orgText, statusText, roles, orgs, byId, result);
|
||||||
|
} catch (BusinessException e) {
|
||||||
|
result.addError(excelRow, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (result.getTotal() == 0 && result.getFailed() == 0) {
|
||||||
|
result.addError(0, result.getSkipped() > 0
|
||||||
|
? "仅读取到模板示例数据,请填写实际数据后再导入"
|
||||||
|
: "未读取到有效数据行,请从第 3 行开始填写");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (BusinessException e) {
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
result.addError(0, "文件解析失败:" + e.getMessage());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void importRow(String username, String realName, String password, String roleText, String orgText,
|
||||||
|
String statusText, List<SysRole> roles, List<SysOrg> orgs, Map<Long, SysOrg> byId,
|
||||||
|
ImportResult result) {
|
||||||
|
if (!StringUtils.hasText(username)) {
|
||||||
|
throw new BusinessException("登录账号不能为空");
|
||||||
|
}
|
||||||
|
if (!StringUtils.hasText(realName)) {
|
||||||
|
throw new BusinessException("姓名不能为空");
|
||||||
|
}
|
||||||
|
SysRole role = matchRole(roleText, roles);
|
||||||
|
if (role == null) {
|
||||||
|
throw new BusinessException("角色不存在:" + roleText);
|
||||||
|
}
|
||||||
|
Long orgId = matchOrg(orgText, orgs, byId);
|
||||||
|
Integer status = parseStatus(statusText);
|
||||||
|
SysUser existing = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||||
|
.eq(SysUser::getUsername, username.trim()));
|
||||||
|
UserSaveRequest request = new UserSaveRequest();
|
||||||
|
request.setUsername(username.trim());
|
||||||
|
request.setRealName(realName.trim());
|
||||||
|
request.setPassword(StringUtils.hasText(password) ? password.trim() : null);
|
||||||
|
request.setRoleId(role.getId());
|
||||||
|
request.setOrgId(orgId);
|
||||||
|
request.setStatus(status);
|
||||||
|
if (existing == null) {
|
||||||
|
userAdminService.create(request);
|
||||||
|
result.setInserted(result.getInserted() + 1);
|
||||||
|
} else {
|
||||||
|
userAdminService.update(existing.getId(), request);
|
||||||
|
result.setUpdated(result.getUpdated() + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysRole matchRole(String text, List<SysRole> roles) {
|
||||||
|
if (!StringUtils.hasText(text)) {
|
||||||
|
throw new BusinessException("角色编码不能为空");
|
||||||
|
}
|
||||||
|
String value = text.trim();
|
||||||
|
for (SysRole role : roles) {
|
||||||
|
if (role.getCode() != null && role.getCode().equalsIgnoreCase(value)) {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (SysRole role : roles) {
|
||||||
|
if (value.equals(role.getName())) {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long matchOrg(String text, List<SysOrg> orgs, Map<Long, SysOrg> byId) {
|
||||||
|
if (!StringUtils.hasText(text)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String value = text.trim();
|
||||||
|
for (SysOrg org : orgs) {
|
||||||
|
if (value.equals(org.getCode())) {
|
||||||
|
return org.getId();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<SysOrg> byPath = new ArrayList<>();
|
||||||
|
List<SysOrg> byName = new ArrayList<>();
|
||||||
|
for (SysOrg org : orgs) {
|
||||||
|
if (value.equals(pathOf(org, byId))) {
|
||||||
|
byPath.add(org);
|
||||||
|
}
|
||||||
|
if (value.equals(org.getName())) {
|
||||||
|
byName.add(org);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (byPath.size() == 1) {
|
||||||
|
return byPath.get(0).getId();
|
||||||
|
}
|
||||||
|
if (byName.size() == 1) {
|
||||||
|
return byName.get(0).getId();
|
||||||
|
}
|
||||||
|
if (byName.size() > 1) {
|
||||||
|
throw new BusinessException("组织名称不唯一,请填写组织编码");
|
||||||
|
}
|
||||||
|
throw new BusinessException("组织不存在:" + value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer parseStatus(String text) {
|
||||||
|
if (!StringUtils.hasText(text) || "启用".equals(text.trim()) || "1".equals(text.trim())) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if ("停用".equals(text.trim()) || "0".equals(text.trim())) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
throw new BusinessException("状态只能填启用或停用");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String pathOf(SysOrg org, Map<Long, SysOrg> byId) {
|
||||||
|
LinkedHashMap<Long, String> guard = new LinkedHashMap<>();
|
||||||
|
List<String> parts = new ArrayList<>();
|
||||||
|
SysOrg cursor = org;
|
||||||
|
while (cursor != null && guard.put(cursor.getId(), cursor.getName()) == null) {
|
||||||
|
parts.add(0, cursor.getName());
|
||||||
|
cursor = cursor.getParentId() == null ? null : byId.get(cursor.getParentId());
|
||||||
|
}
|
||||||
|
return String.join("/", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Integer> headerIndex(Row head) {
|
||||||
|
Map<String, Integer> columns = new HashMap<>();
|
||||||
|
if (head == null) {
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
for (Cell cell : head) {
|
||||||
|
String name = formatter.formatCellValue(cell).replace("*", "").replace("*", "").trim();
|
||||||
|
if (StringUtils.hasText(name)) {
|
||||||
|
columns.put(name, cell.getColumnIndex());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hintRow(Sheet sheet) {
|
||||||
|
Row second = sheet.getRow(1);
|
||||||
|
if (second == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String first = formatter.formatCellValue(second.getCell(0));
|
||||||
|
return first.startsWith("必填") || first.startsWith("选填");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String cell(Row row, Integer index) {
|
||||||
|
if (index == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return formatter.formatCellValue(row.getCell(index)).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSample(String value) {
|
||||||
|
return value != null && (value.startsWith("示例:") || value.startsWith("示例:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void dropdown(Sheet sheet, int column, String formula) {
|
||||||
|
DataValidationHelper helper = sheet.getDataValidationHelper();
|
||||||
|
DataValidationConstraint constraint = formula.startsWith("\"")
|
||||||
|
? helper.createExplicitListConstraint(new String[]{"启用", "停用"})
|
||||||
|
: helper.createFormulaListConstraint(formula);
|
||||||
|
CellRangeAddressList range = new CellRangeAddressList(2, 5000, column, column);
|
||||||
|
DataValidation validation = helper.createValidation(constraint, range);
|
||||||
|
validation.setSuppressDropDownArrow(true);
|
||||||
|
validation.setShowErrorBox(true);
|
||||||
|
sheet.addValidationData(validation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CellStyle headStyle(Workbook wb) {
|
||||||
|
CellStyle style = wb.createCellStyle();
|
||||||
|
Font font = wb.createFont();
|
||||||
|
font.setBold(true);
|
||||||
|
font.setColor(IndexedColors.WHITE.getIndex());
|
||||||
|
style.setFont(font);
|
||||||
|
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||||
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
|
style.setAlignment(HorizontalAlignment.CENTER);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CellStyle hintStyle(Workbook wb) {
|
||||||
|
CellStyle style = wb.createCellStyle();
|
||||||
|
Font font = wb.createFont();
|
||||||
|
font.setFontHeightInPoints((short) 9);
|
||||||
|
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||||
|
style.setFont(font);
|
||||||
|
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
|
||||||
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
|
style.setWrapText(true);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
package com.banben.modules.admin.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.modules.admin.entity.ListFieldConfig;
|
||||||
|
import com.banben.modules.admin.mapper.ListFieldConfigMapper;
|
||||||
|
import com.banben.modules.admin.service.ListFieldConfigService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表显示字段配置服务实现。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ListFieldConfigServiceImpl implements ListFieldConfigService {
|
||||||
|
|
||||||
|
private final ListFieldConfigMapper listFieldConfigMapper;
|
||||||
|
|
||||||
|
/** 默认展示字段:字段键 / 显示名 */
|
||||||
|
private static final List<String[]> DEFAULT_SEARCH_FIELDS = Arrays.asList(
|
||||||
|
new String[]{"title", "文献题名"},
|
||||||
|
new String[]{"publishYear", "发行时间"},
|
||||||
|
new String[]{"author", "作者"},
|
||||||
|
new String[]{"authorOrg", "作者单位"},
|
||||||
|
new String[]{"publisher", "来源刊名/出版社"},
|
||||||
|
new String[]{"mediaType", "资源类型"},
|
||||||
|
new String[]{"sourceLibrary", "来源院校"},
|
||||||
|
new String[]{"sourceRepo", "来源资源库名"}
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ListFieldConfig> listScene(String scene) {
|
||||||
|
List<ListFieldConfig> list = queryScene(scene);
|
||||||
|
if (list.isEmpty()) {
|
||||||
|
return resetScene(scene);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void saveScene(String scene, List<ListFieldConfig> items) {
|
||||||
|
// 场景内全量覆盖:先删除旧配置(物理删除,避免历史脏数据堆积)
|
||||||
|
listFieldConfigMapper.delete(new LambdaQueryWrapper<ListFieldConfig>().eq(ListFieldConfig::getScene, scene));
|
||||||
|
if (items == null || items.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int no = 1;
|
||||||
|
for (ListFieldConfig item : items) {
|
||||||
|
ListFieldConfig cfg = new ListFieldConfig();
|
||||||
|
cfg.setScene(scene);
|
||||||
|
cfg.setFieldKey(item.getFieldKey());
|
||||||
|
cfg.setFieldLabel(item.getFieldLabel());
|
||||||
|
cfg.setSortNo(item.getSortNo() != null ? item.getSortNo() : no * 10);
|
||||||
|
cfg.setVisible(item.getVisible() == null ? 1 : item.getVisible());
|
||||||
|
listFieldConfigMapper.insert(cfg);
|
||||||
|
no++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public List<ListFieldConfig> resetScene(String scene) {
|
||||||
|
listFieldConfigMapper.delete(new LambdaQueryWrapper<ListFieldConfig>().eq(ListFieldConfig::getScene, scene));
|
||||||
|
List<ListFieldConfig> defaults = new ArrayList<>();
|
||||||
|
int no = 1;
|
||||||
|
for (String[] kv : DEFAULT_SEARCH_FIELDS) {
|
||||||
|
ListFieldConfig cfg = new ListFieldConfig();
|
||||||
|
cfg.setScene(scene);
|
||||||
|
cfg.setFieldKey(kv[0]);
|
||||||
|
cfg.setFieldLabel(kv[1]);
|
||||||
|
cfg.setSortNo(no * 10);
|
||||||
|
cfg.setVisible(1);
|
||||||
|
listFieldConfigMapper.insert(cfg);
|
||||||
|
defaults.add(cfg);
|
||||||
|
no++;
|
||||||
|
}
|
||||||
|
return defaults;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<ListFieldConfig> queryScene(String scene) {
|
||||||
|
return listFieldConfigMapper.selectList(
|
||||||
|
new LambdaQueryWrapper<ListFieldConfig>()
|
||||||
|
.eq(ListFieldConfig::getScene, scene)
|
||||||
|
.orderByAsc(ListFieldConfig::getSortNo)
|
||||||
|
.orderByAsc(ListFieldConfig::getId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
package com.banben.modules.admin.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||||
|
import com.banben.modules.admin.entity.SysOrg;
|
||||||
|
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||||
|
import com.banben.modules.admin.service.OrgService;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组织树的增删改。删除时若仍有下级或用户则拒绝。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class OrgServiceImpl implements OrgService {
|
||||||
|
|
||||||
|
private final SysOrgMapper orgMapper;
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OrgTreeVO> tree() {
|
||||||
|
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>()
|
||||||
|
.orderByAsc(SysOrg::getSortNo)
|
||||||
|
.orderByAsc(SysOrg::getId));
|
||||||
|
Map<Long, OrgTreeVO> nodes = new HashMap<>();
|
||||||
|
for (SysOrg org : all) {
|
||||||
|
nodes.put(org.getId(), toVo(org));
|
||||||
|
}
|
||||||
|
List<OrgTreeVO> roots = new ArrayList<>();
|
||||||
|
for (SysOrg org : all) {
|
||||||
|
OrgTreeVO node = nodes.get(org.getId());
|
||||||
|
OrgTreeVO parent = org.getParentId() == null ? null : nodes.get(org.getParentId());
|
||||||
|
if (parent == null) {
|
||||||
|
roots.add(node);
|
||||||
|
} else {
|
||||||
|
if (parent.getChildren() == null) {
|
||||||
|
parent.setChildren(new ArrayList<>());
|
||||||
|
}
|
||||||
|
parent.getChildren().add(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sortTree(roots);
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void create(OrgSaveRequest request) {
|
||||||
|
SysOrg org = new SysOrg();
|
||||||
|
fill(org, request, null);
|
||||||
|
orgMapper.insert(org);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(Long id, OrgSaveRequest request) {
|
||||||
|
SysOrg org = require(id);
|
||||||
|
fill(org, request, id);
|
||||||
|
orgMapper.update(null, new LambdaUpdateWrapper<SysOrg>()
|
||||||
|
.eq(SysOrg::getId, id)
|
||||||
|
.set(SysOrg::getParentId, org.getParentId())
|
||||||
|
.set(SysOrg::getName, org.getName())
|
||||||
|
.set(SysOrg::getCode, org.getCode())
|
||||||
|
.set(SysOrg::getSortNo, org.getSortNo())
|
||||||
|
.set(SysOrg::getStatus, org.getStatus())
|
||||||
|
.set(SysOrg::getRemark, org.getRemark()));
|
||||||
|
syncUserOrgName(org);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Long id) {
|
||||||
|
require(id);
|
||||||
|
Long children = orgMapper.selectCount(new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getParentId, id));
|
||||||
|
if (children != null && children > 0) {
|
||||||
|
throw new BusinessException("请先删除下级组织");
|
||||||
|
}
|
||||||
|
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, id));
|
||||||
|
if (users != null && users > 0) {
|
||||||
|
throw new BusinessException("该组织下还有用户,不能删除");
|
||||||
|
}
|
||||||
|
orgMapper.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<Long> subtreeIds(Long orgId) {
|
||||||
|
require(orgId);
|
||||||
|
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<>());
|
||||||
|
Map<Long, List<Long>> children = new HashMap<>();
|
||||||
|
for (SysOrg org : all) {
|
||||||
|
if (org.getParentId() != null) {
|
||||||
|
children.computeIfAbsent(org.getParentId(), key -> new ArrayList<>()).add(org.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Set<Long> ids = new HashSet<>();
|
||||||
|
collect(orgId, children, ids);
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collect(Long id, Map<Long, List<Long>> children, Set<Long> ids) {
|
||||||
|
if (!ids.add(id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Long child : children.getOrDefault(id, List.of())) {
|
||||||
|
collect(child, children, ids);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fill(SysOrg org, OrgSaveRequest request, Long selfId) {
|
||||||
|
Long parentId = request.getParentId();
|
||||||
|
if (parentId != null) {
|
||||||
|
if (parentId.equals(selfId)) {
|
||||||
|
throw new BusinessException("上级组织不能是自己");
|
||||||
|
}
|
||||||
|
require(parentId);
|
||||||
|
assertNoCycle(selfId, parentId);
|
||||||
|
}
|
||||||
|
String code = blankToNull(request.getCode());
|
||||||
|
assertCodeUnique(code, selfId);
|
||||||
|
org.setParentId(parentId);
|
||||||
|
org.setName(request.getName().trim());
|
||||||
|
org.setCode(code);
|
||||||
|
org.setSortNo(request.getSortNo() == null ? 0 : request.getSortNo());
|
||||||
|
org.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
|
||||||
|
org.setRemark(blankToNull(request.getRemark()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertNoCycle(Long selfId, Long parentId) {
|
||||||
|
if (selfId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Long cursor = parentId;
|
||||||
|
Set<Long> seen = new HashSet<>();
|
||||||
|
while (cursor != null) {
|
||||||
|
if (cursor.equals(selfId)) {
|
||||||
|
throw new BusinessException("不能把组织移动到自己的下级");
|
||||||
|
}
|
||||||
|
if (!seen.add(cursor)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
SysOrg parent = orgMapper.selectById(cursor);
|
||||||
|
cursor = parent == null ? null : parent.getParentId();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertCodeUnique(String code, Long selfId) {
|
||||||
|
if (code == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LambdaQueryWrapper<SysOrg> query = new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getCode, code);
|
||||||
|
if (selfId != null) {
|
||||||
|
query.ne(SysOrg::getId, selfId);
|
||||||
|
}
|
||||||
|
Long count = orgMapper.selectCount(query);
|
||||||
|
if (count != null && count > 0) {
|
||||||
|
throw new BusinessException("组织编码已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void syncUserOrgName(SysOrg org) {
|
||||||
|
SysUser patch = new SysUser();
|
||||||
|
patch.setOrgName(org.getName());
|
||||||
|
userMapper.update(patch, new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, org.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysOrg require(Long id) {
|
||||||
|
SysOrg org = orgMapper.selectById(id);
|
||||||
|
if (org == null) {
|
||||||
|
throw new BusinessException("组织不存在");
|
||||||
|
}
|
||||||
|
return org;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrgTreeVO toVo(SysOrg org) {
|
||||||
|
OrgTreeVO vo = new OrgTreeVO();
|
||||||
|
vo.setId(org.getId());
|
||||||
|
vo.setParentId(org.getParentId());
|
||||||
|
vo.setName(org.getName());
|
||||||
|
vo.setCode(org.getCode());
|
||||||
|
vo.setSortNo(org.getSortNo());
|
||||||
|
vo.setStatus(org.getStatus());
|
||||||
|
vo.setRemark(org.getRemark());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sortTree(List<OrgTreeVO> nodes) {
|
||||||
|
nodes.sort(Comparator
|
||||||
|
.comparing((OrgTreeVO node) -> node.getSortNo() == null ? 0 : node.getSortNo())
|
||||||
|
.thenComparing(OrgTreeVO::getId));
|
||||||
|
for (OrgTreeVO node : nodes) {
|
||||||
|
if (node.getChildren() != null) {
|
||||||
|
sortTree(node.getChildren());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String blankToNull(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package com.banben.modules.admin.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
|
import com.banben.modules.admin.service.RoleService;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import com.banben.modules.auth.nav.NavMenus;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色增删改。ADMIN、USER 为内置角色。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RoleServiceImpl implements RoleService {
|
||||||
|
|
||||||
|
private final SysRoleMapper roleMapper;
|
||||||
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SysRole> listAll() {
|
||||||
|
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
|
||||||
|
.orderByDesc(SysRole::getBuiltin)
|
||||||
|
.orderByAsc(SysRole::getId));
|
||||||
|
Map<Long, List<String>> menus = roleMenuMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||||
|
.collect(Collectors.groupingBy(SysRoleMenu::getRoleId,
|
||||||
|
Collectors.mapping(SysRoleMenu::getMenuCode, Collectors.toList())));
|
||||||
|
for (SysRole role : roles) {
|
||||||
|
if (isAdminCode(role)) {
|
||||||
|
role.setMenuCodes(new ArrayList<>(NavMenus.CODES));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
role.setMenuCodes(menus.getOrDefault(role.getId(), List.of()).stream()
|
||||||
|
.filter(NavMenus::contains)
|
||||||
|
.distinct()
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
return roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void create(RoleSaveRequest request) {
|
||||||
|
SysRole role = new SysRole();
|
||||||
|
role.setBuiltin(0);
|
||||||
|
fill(role, request, null);
|
||||||
|
roleMapper.insert(role);
|
||||||
|
replaceMenus(role.getId(), request.getMenuCodes());
|
||||||
|
markMenusInited(role.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(Long id, RoleSaveRequest request) {
|
||||||
|
SysRole role = require(id);
|
||||||
|
String previousCode = role.getCode();
|
||||||
|
if (isBuiltin(role) && !previousCode.equalsIgnoreCase(request.getCode().trim())) {
|
||||||
|
throw new BusinessException("内置角色不能修改编码");
|
||||||
|
}
|
||||||
|
fill(role, request, id);
|
||||||
|
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
|
||||||
|
.eq(SysRole::getId, id)
|
||||||
|
.set(SysRole::getCode, role.getCode())
|
||||||
|
.set(SysRole::getName, role.getName())
|
||||||
|
.set(SysRole::getRemark, role.getRemark())
|
||||||
|
.set(SysRole::getStatus, role.getStatus()));
|
||||||
|
if (!previousCode.equals(role.getCode())) {
|
||||||
|
userMapper.update(null, new LambdaUpdateWrapper<SysUser>()
|
||||||
|
.set(SysUser::getRole, role.getCode())
|
||||||
|
.eq(SysUser::getRoleId, id));
|
||||||
|
}
|
||||||
|
if (isAdminCode(role)) {
|
||||||
|
replaceMenus(id, NavMenus.CODES);
|
||||||
|
markMenusInited(id);
|
||||||
|
} else if (request.getMenuCodes() != null) {
|
||||||
|
replaceMenus(id, request.getMenuCodes());
|
||||||
|
markMenusInited(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Long id) {
|
||||||
|
SysRole role = require(id);
|
||||||
|
if (isBuiltin(role)) {
|
||||||
|
throw new BusinessException("内置角色不能删除");
|
||||||
|
}
|
||||||
|
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRoleId, id));
|
||||||
|
if (users != null && users > 0) {
|
||||||
|
throw new BusinessException("该角色下还有用户,不能删除");
|
||||||
|
}
|
||||||
|
roleMapper.deleteById(id);
|
||||||
|
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void ensureBuiltin() {
|
||||||
|
ensure("ADMIN", "系统管理员", "系统内置,可管理组织、用户与角色");
|
||||||
|
ensure("USER", "普通用户", "系统内置普通用户");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensure(String code, String name, String remark) {
|
||||||
|
SysRole existing = roleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
|
||||||
|
if (existing != null) {
|
||||||
|
if ("ADMIN".equalsIgnoreCase(code)) {
|
||||||
|
replaceMenus(existing.getId(), NavMenus.CODES);
|
||||||
|
markMenusInited(existing.getId());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SysRole role = new SysRole();
|
||||||
|
role.setCode(code);
|
||||||
|
role.setName(name);
|
||||||
|
role.setRemark(remark);
|
||||||
|
role.setStatus(1);
|
||||||
|
role.setBuiltin(1);
|
||||||
|
roleMapper.insert(role);
|
||||||
|
replaceMenus(role.getId(), NavMenus.CODES);
|
||||||
|
markMenusInited(role.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
|
||||||
|
String code = request.getCode().trim().toUpperCase();
|
||||||
|
LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code);
|
||||||
|
if (selfId != null) {
|
||||||
|
query.ne(SysRole::getId, selfId);
|
||||||
|
}
|
||||||
|
Long count = roleMapper.selectCount(query);
|
||||||
|
if (count != null && count > 0) {
|
||||||
|
throw new BusinessException("角色编码已存在");
|
||||||
|
}
|
||||||
|
role.setCode(code);
|
||||||
|
role.setName(request.getName().trim());
|
||||||
|
role.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
|
||||||
|
role.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysRole require(Long id) {
|
||||||
|
SysRole role = roleMapper.selectById(id);
|
||||||
|
if (role == null) {
|
||||||
|
throw new BusinessException("角色不存在");
|
||||||
|
}
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isBuiltin(SysRole role) {
|
||||||
|
return role.getBuiltin() != null && role.getBuiltin() == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAdminCode(SysRole role) {
|
||||||
|
return role.getCode() != null && "ADMIN".equalsIgnoreCase(role.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void replaceMenus(Long roleId, List<String> menuCodes) {
|
||||||
|
List<String> codes = menuCodes == null ? new ArrayList<>(NavMenus.CODES) : normalize(menuCodes);
|
||||||
|
roleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
|
||||||
|
for (String code : codes) {
|
||||||
|
SysRoleMenu row = new SysRoleMenu();
|
||||||
|
row.setRoleId(roleId);
|
||||||
|
row.setMenuCode(code);
|
||||||
|
roleMenuMapper.insert(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> normalize(List<String> menuCodes) {
|
||||||
|
LinkedHashSet<String> codes = new LinkedHashSet<>();
|
||||||
|
for (String code : menuCodes) {
|
||||||
|
if (NavMenus.contains(code)) {
|
||||||
|
codes.add(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ArrayList<>(codes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markMenusInited(Long roleId) {
|
||||||
|
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
|
||||||
|
.eq(SysRole::getId, roleId)
|
||||||
|
.set(SysRole::getMenuInited, 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
+216
@@ -0,0 +1,216 @@
|
|||||||
|
package com.banben.modules.admin.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||||
|
import com.banben.modules.admin.dto.UserVO;
|
||||||
|
import com.banben.modules.admin.entity.SysOrg;
|
||||||
|
import com.banben.modules.admin.entity.SysRole;
|
||||||
|
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.service.OrgService;
|
||||||
|
import com.banben.modules.admin.service.UserAdminService;
|
||||||
|
import com.banben.modules.auth.context.UserContext;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户新增、修改、删除。密码留空时,新增使用 123456,修改则保持原密码。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserAdminServiceImpl implements UserAdminService {
|
||||||
|
|
||||||
|
static final String DEFAULT_PASSWORD = "123456";
|
||||||
|
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
private final SysRoleMapper roleMapper;
|
||||||
|
private final SysOrgMapper orgMapper;
|
||||||
|
private final OrgService orgService;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId) {
|
||||||
|
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
|
||||||
|
if (StringUtils.hasText(keyword)) {
|
||||||
|
String word = keyword.trim();
|
||||||
|
query.and(w -> w.like(SysUser::getUsername, word).or().like(SysUser::getRealName, word));
|
||||||
|
}
|
||||||
|
if (orgId != null) {
|
||||||
|
query.in(SysUser::getOrgId, orgService.subtreeIds(orgId));
|
||||||
|
}
|
||||||
|
if (roleId != null) {
|
||||||
|
query.eq(SysUser::getRoleId, roleId);
|
||||||
|
}
|
||||||
|
query.orderByDesc(SysUser::getId);
|
||||||
|
Page<SysUser> raw = userMapper.selectPage(new Page<>(current, size), query);
|
||||||
|
|
||||||
|
Map<Long, SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||||
|
.collect(Collectors.toMap(SysRole::getId, role -> role, (a, b) -> a));
|
||||||
|
Map<Long, SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||||
|
.collect(Collectors.toMap(SysOrg::getId, org -> org, (a, b) -> a));
|
||||||
|
|
||||||
|
Page<UserVO> page = new Page<>(raw.getCurrent(), raw.getSize(), raw.getTotal());
|
||||||
|
page.setRecords(raw.getRecords().stream().map(user -> toVo(user, roles, orgs)).toList());
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void create(UserSaveRequest request) {
|
||||||
|
SysRole role = requireRole(request.getRoleId());
|
||||||
|
SysOrg org = optionalOrg(request.getOrgId());
|
||||||
|
assertUsernameFree(request.getUsername().trim(), null);
|
||||||
|
assertPassword(request.getPassword(), true);
|
||||||
|
SysUser user = new SysUser();
|
||||||
|
user.setUsername(request.getUsername().trim());
|
||||||
|
user.setPassword(passwordEncoder.encode(passwordOrDefault(request.getPassword())));
|
||||||
|
user.setRealName(request.getRealName().trim());
|
||||||
|
user.setRoleId(role.getId());
|
||||||
|
user.setRole(role.getCode());
|
||||||
|
user.setOrgId(org == null ? null : org.getId());
|
||||||
|
user.setOrgName(org == null ? null : org.getName());
|
||||||
|
user.setStatus(statusOf(request.getStatus()));
|
||||||
|
try {
|
||||||
|
userMapper.insert(user);
|
||||||
|
} catch (DuplicateKeyException e) {
|
||||||
|
throw new BusinessException("登录账号已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(Long id, UserSaveRequest request) {
|
||||||
|
SysUser existing = requireUser(id);
|
||||||
|
SysRole role = requireRole(request.getRoleId());
|
||||||
|
SysOrg org = optionalOrg(request.getOrgId());
|
||||||
|
assertUsernameFree(request.getUsername().trim(), id);
|
||||||
|
assertPassword(request.getPassword(), false);
|
||||||
|
guardLastAdmin(existing, role.getCode(), statusOf(request.getStatus()), false);
|
||||||
|
LambdaUpdateWrapper<SysUser> update = new LambdaUpdateWrapper<SysUser>()
|
||||||
|
.eq(SysUser::getId, id)
|
||||||
|
.set(SysUser::getUsername, request.getUsername().trim())
|
||||||
|
.set(SysUser::getRealName, request.getRealName().trim())
|
||||||
|
.set(SysUser::getRoleId, role.getId())
|
||||||
|
.set(SysUser::getRole, role.getCode())
|
||||||
|
.set(SysUser::getOrgId, org == null ? null : org.getId())
|
||||||
|
.set(SysUser::getOrgName, org == null ? null : org.getName())
|
||||||
|
.set(SysUser::getStatus, statusOf(request.getStatus()));
|
||||||
|
if (StringUtils.hasText(request.getPassword())) {
|
||||||
|
update.set(SysUser::getPassword, passwordEncoder.encode(request.getPassword().trim()));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
userMapper.update(null, update);
|
||||||
|
} catch (DuplicateKeyException e) {
|
||||||
|
throw new BusinessException("登录账号已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Long id) {
|
||||||
|
SysUser existing = requireUser(id);
|
||||||
|
if (id.equals(UserContext.currentUserId())) {
|
||||||
|
throw new BusinessException("不能删除当前登录账号");
|
||||||
|
}
|
||||||
|
guardLastAdmin(existing, null, 0, true);
|
||||||
|
userMapper.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void guardLastAdmin(SysUser existing, String nextRole, int nextStatus, boolean deleting) {
|
||||||
|
if (!"ADMIN".equalsIgnoreCase(existing.getRole())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
boolean stillAdmin = !deleting && "ADMIN".equalsIgnoreCase(nextRole) && nextStatus == 1;
|
||||||
|
if (stillAdmin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Long admins = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
|
||||||
|
.eq(SysUser::getRole, "ADMIN")
|
||||||
|
.eq(SysUser::getStatus, 1)
|
||||||
|
.ne(SysUser::getId, existing.getId()));
|
||||||
|
if (admins == null || admins == 0) {
|
||||||
|
throw new BusinessException("至少保留一个启用的系统管理员");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertUsernameFree(String username, Long selfId) {
|
||||||
|
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
|
||||||
|
if (selfId != null) {
|
||||||
|
query.ne(SysUser::getId, selfId);
|
||||||
|
}
|
||||||
|
Long count = userMapper.selectCount(query);
|
||||||
|
if (count != null && count > 0) {
|
||||||
|
throw new BusinessException("登录账号已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysUser requireUser(Long id) {
|
||||||
|
SysUser user = userMapper.selectById(id);
|
||||||
|
if (user == null) {
|
||||||
|
throw new BusinessException("用户不存在");
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysRole requireRole(Long roleId) {
|
||||||
|
SysRole role = roleMapper.selectById(roleId);
|
||||||
|
if (role == null) {
|
||||||
|
throw new BusinessException("角色不存在");
|
||||||
|
}
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysOrg optionalOrg(Long orgId) {
|
||||||
|
if (orgId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
SysOrg org = orgMapper.selectById(orgId);
|
||||||
|
if (org == null) {
|
||||||
|
throw new BusinessException("组织不存在");
|
||||||
|
}
|
||||||
|
return org;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int statusOf(Integer status) {
|
||||||
|
return status != null && status == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String passwordOrDefault(String password) {
|
||||||
|
return StringUtils.hasText(password) ? password.trim() : DEFAULT_PASSWORD;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertPassword(String password, boolean creating) {
|
||||||
|
if (!StringUtils.hasText(password)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password.trim().length() < 6) {
|
||||||
|
throw new BusinessException(creating ? "密码至少 6 位,留空则使用 123456" : "密码至少 6 位");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserVO toVo(SysUser user, Map<Long, SysRole> roles, Map<Long, SysOrg> orgs) {
|
||||||
|
UserVO vo = new UserVO();
|
||||||
|
vo.setId(user.getId());
|
||||||
|
vo.setUsername(user.getUsername());
|
||||||
|
vo.setRealName(user.getRealName());
|
||||||
|
vo.setRoleId(user.getRoleId());
|
||||||
|
vo.setRoleCode(user.getRole());
|
||||||
|
SysRole role = user.getRoleId() == null ? null : roles.get(user.getRoleId());
|
||||||
|
vo.setRoleName(role == null ? user.getRole() : role.getName());
|
||||||
|
vo.setOrgId(user.getOrgId());
|
||||||
|
SysOrg org = user.getOrgId() == null ? null : orgs.get(user.getOrgId());
|
||||||
|
vo.setOrgName(org == null ? user.getOrgName() : org.getName());
|
||||||
|
vo.setStatus(user.getStatus());
|
||||||
|
vo.setLastLoginTime(user.getLastLoginTime());
|
||||||
|
vo.setCreateTime(user.getCreateTime());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.banben.modules.admin.support;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
|
import com.banben.modules.admin.entity.SysRoleMenu;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
|
import com.banben.modules.auth.context.LoginUser;
|
||||||
|
import com.banben.modules.auth.context.UserContext;
|
||||||
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台管理接口:角色勾选了「后台管理」栏目才能调用。
|
||||||
|
* 权限表暂时不可用时,仍放行角色编码为 ADMIN 的账号,避免把管理员锁在外面。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AdminAccess {
|
||||||
|
|
||||||
|
private final SysUserMapper userMapper;
|
||||||
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
|
|
||||||
|
public void require() {
|
||||||
|
LoginUser login = UserContext.get();
|
||||||
|
if (login == null || login.id() == null || !allowed(login.id(), login.role())) {
|
||||||
|
throw new BusinessException(403, "需要后台管理权限");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean allowed(Long userId, String roleCode) {
|
||||||
|
if (isAdminCode(roleCode)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
SysUser user = userMapper.selectById(userId);
|
||||||
|
if (user == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isAdminCode(user.getRole())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (user.getRoleId() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Long count = roleMenuMapper.selectCount(new LambdaQueryWrapper<SysRoleMenu>()
|
||||||
|
.eq(SysRoleMenu::getRoleId, user.getRoleId())
|
||||||
|
.eq(SysRoleMenu::getMenuCode, "admin"));
|
||||||
|
return count != null && count > 0;
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
return isAdminCode(roleCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAdminCode(String roleCode) {
|
||||||
|
return roleCode != null && "ADMIN".equalsIgnoreCase(roleCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
-2
@@ -126,14 +126,49 @@ public class AnalysisServiceImpl implements AnalysisService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<FacetItem> hotKeywords(int limit) {
|
public List<FacetItem> hotKeywords(int limit) {
|
||||||
|
int top = Math.max(1, limit);
|
||||||
|
// 热词 = 检索日志真实检索词 + 元数据关键词(库内真实数据),合并累计
|
||||||
|
Map<String, Long> merged = new LinkedHashMap<>();
|
||||||
|
|
||||||
QueryWrapper<SearchLog> wrapper = new QueryWrapper<>();
|
QueryWrapper<SearchLog> wrapper = new QueryWrapper<>();
|
||||||
wrapper.select("keyword AS name", "COUNT(*) AS cnt")
|
wrapper.select("keyword AS name", "COUNT(*) AS cnt")
|
||||||
.isNotNull("keyword")
|
.isNotNull("keyword")
|
||||||
.ne("keyword", "")
|
.ne("keyword", "")
|
||||||
.groupBy("keyword")
|
.groupBy("keyword")
|
||||||
.orderByDesc("cnt")
|
.orderByDesc("cnt")
|
||||||
.last("limit " + Math.max(1, limit));
|
.last("limit " + top * 3);
|
||||||
return toFacets(searchLogMapper.selectMaps(wrapper));
|
for (Map<String, Object> m : searchLogMapper.selectMaps(wrapper)) {
|
||||||
|
Object name = m.get("name");
|
||||||
|
if (name == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String word = String.valueOf(name).trim();
|
||||||
|
if (!word.isEmpty()) {
|
||||||
|
merged.merge(word, toLong(m.get("cnt")), Long::sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 元数据关键词按分号/逗号拆分后的高频词(补充检索日志条数不足时的词云展示)
|
||||||
|
try {
|
||||||
|
for (Map<String, Object> m : resourceMapper.splitKeywordCounts(top * 3)) {
|
||||||
|
Object name = m.get("name");
|
||||||
|
if (name == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String word = String.valueOf(name).trim();
|
||||||
|
if (!word.isEmpty()) {
|
||||||
|
merged.merge(word, toLong(m.get("cnt")), Long::sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 拆分统计失败时退化为仅检索日志热词
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged.entrySet().stream()
|
||||||
|
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
|
||||||
|
.limit(top)
|
||||||
|
.map(e -> new FacetItem(e.getKey(), e.getValue()))
|
||||||
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.banben.modules.auth;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志表自举建表。
|
||||||
|
*
|
||||||
|
* <p>应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
|
||||||
|
* 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
|
||||||
|
* 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。</p>
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class LoginLogTableInitializer {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public LoginLogTableInitializer(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS login_log ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "user_id BIGINT, "
|
||||||
|
+ "username VARCHAR(128), "
|
||||||
|
+ "real_name VARCHAR(128), "
|
||||||
|
+ "org_name VARCHAR(256), "
|
||||||
|
+ "ip VARCHAR(64), "
|
||||||
|
+ "user_agent VARCHAR(512), "
|
||||||
|
+ "login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "logout_time TIMESTAMP, "
|
||||||
|
+ "online SMALLINT DEFAULT 1, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online)");
|
||||||
|
log.info("登录日志表 login_log 已就绪(不存在则已自动创建)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 建表失败不应阻断启动;缺表时登录日志接口已做优雅降级
|
||||||
|
log.warn("自动创建 login_log 表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,12 +5,16 @@ import com.banben.modules.auth.dto.LoginRequest;
|
|||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.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;
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
|
|||||||
import com.baomidou.mybatisplus.annotation.TableId;
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
import com.baomidou.mybatisplus.annotation.TableName;
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@@ -26,18 +27,25 @@ public class SysUser implements Serializable {
|
|||||||
@Schema(description = "登录账号")
|
@Schema(description = "登录账号")
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
|
@JsonIgnore
|
||||||
@Schema(description = "BCrypt 加密后的密码")
|
@Schema(description = "BCrypt 加密后的密码")
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
@Schema(description = "姓名")
|
@Schema(description = "姓名")
|
||||||
private String realName;
|
private String realName;
|
||||||
|
|
||||||
@Schema(description = "角色:ADMIN / USER")
|
@Schema(description = "角色编码,与 sys_role.code 一致,写入登录令牌")
|
||||||
private String role;
|
private String role;
|
||||||
|
|
||||||
@Schema(description = "所属单位")
|
@Schema(description = "角色,对应 sys_role.id")
|
||||||
|
private Long roleId;
|
||||||
|
|
||||||
|
@Schema(description = "所属单位名称,与组织名称同步")
|
||||||
private String orgName;
|
private String orgName;
|
||||||
|
|
||||||
|
@Schema(description = "所属组织,对应 sys_org.id")
|
||||||
|
private Long orgId;
|
||||||
|
|
||||||
@Schema(description = "状态:1启用 0停用")
|
@Schema(description = "状态:1启用 0停用")
|
||||||
private Integer status;
|
private Integer status;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.banben.modules.auth.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志 Mapper。
|
||||||
|
*/
|
||||||
|
public interface LoginLogMapper extends BaseMapper<LoginLog> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.auth.nav;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 顶部导航。编码与前端路由一致,角色按编码授权。
|
||||||
|
*/
|
||||||
|
public final class NavMenus {
|
||||||
|
|
||||||
|
public static final List<String> CODES = List.of(
|
||||||
|
"dashboard",
|
||||||
|
"search",
|
||||||
|
"hotwords",
|
||||||
|
"special",
|
||||||
|
"deposit",
|
||||||
|
"analysis",
|
||||||
|
"resource",
|
||||||
|
"collect",
|
||||||
|
"sync",
|
||||||
|
"governance",
|
||||||
|
"admin"
|
||||||
|
);
|
||||||
|
|
||||||
|
private NavMenus() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean contains(String code) {
|
||||||
|
return code != null && CODES.contains(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import com.banben.modules.auth.dto.LoginRequest;
|
|||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.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,20 +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.SysRoleMenu;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||||
|
import com.banben.modules.admin.mapper.SysRoleMenuMapper;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证服务实现。
|
* 认证服务实现。
|
||||||
@@ -25,8 +37,11 @@ import java.time.LocalDateTime;
|
|||||||
public class AuthServiceImpl implements AuthService {
|
public class AuthServiceImpl implements AuthService {
|
||||||
|
|
||||||
private final SysUserMapper sysUserMapper;
|
private final SysUserMapper sysUserMapper;
|
||||||
|
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) {
|
||||||
@@ -40,10 +55,23 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
if (user.getStatus() != null && user.getStatus() == 0) {
|
if (user.getStatus() != null && user.getStatus() == 0) {
|
||||||
throw new BusinessException("账号已停用,请联系管理员");
|
throw new BusinessException("账号已停用,请联系管理员");
|
||||||
}
|
}
|
||||||
|
if (user.getRoleId() != null) {
|
||||||
|
SysRole role = sysRoleMapper.selectById(user.getRoleId());
|
||||||
|
if (role == null || (role.getStatus() != null && role.getStatus() == 0)) {
|
||||||
|
throw new BusinessException("角色已停用,请联系管理员");
|
||||||
|
}
|
||||||
|
user.setRole(role.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
user.setLastLoginTime(LocalDateTime.now());
|
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();
|
||||||
@@ -53,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();
|
||||||
@@ -68,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;
|
||||||
|
}
|
||||||
@@ -30,6 +30,20 @@ public class CollectController {
|
|||||||
return Result.success(collectService.createTask(task));
|
return Result.success(collectService.createTask(task));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "修改采集任务")
|
||||||
|
@PutMapping("/task/{id}")
|
||||||
|
public Result<Void> updateTask(@PathVariable Long id, @RequestBody CollectTask task) {
|
||||||
|
collectService.updateTask(id, task);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除采集任务")
|
||||||
|
@DeleteMapping("/task/{id}")
|
||||||
|
public Result<Void> removeTask(@PathVariable Long id) {
|
||||||
|
collectService.removeTask(id);
|
||||||
|
return Result.success();
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表")
|
@Operation(summary = "测试来源库连接,并查看表字段如何写入版本资源表")
|
||||||
@PostMapping("/preview")
|
@PostMapping("/preview")
|
||||||
public Result<CollectTableVO> preview(@RequestBody CollectTask source) {
|
public Result<CollectTableVO> preview(@RequestBody CollectTask source) {
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.banben.modules.collect.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源表字段与来源列的对照。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "版本资源字段对照")
|
||||||
|
public class CollectFieldCompareVO {
|
||||||
|
|
||||||
|
@Schema(description = "version_resource 字段名")
|
||||||
|
private String targetField;
|
||||||
|
|
||||||
|
@Schema(description = "字段中文名")
|
||||||
|
private String targetLabel;
|
||||||
|
|
||||||
|
@Schema(description = "是否为必备字段")
|
||||||
|
private boolean required;
|
||||||
|
|
||||||
|
@Schema(description = "对应的来源列名,没有则为空")
|
||||||
|
private String sourceColumn;
|
||||||
|
|
||||||
|
@Schema(description = "来源表是否有列对应到该字段")
|
||||||
|
private boolean matched;
|
||||||
|
}
|
||||||
@@ -21,4 +21,7 @@ public class CollectTableVO {
|
|||||||
|
|
||||||
@Schema(description = "列与版本资源字段的对应关系")
|
@Schema(description = "列与版本资源字段的对应关系")
|
||||||
private List<CollectColumnVO> columns = new ArrayList<>();
|
private List<CollectColumnVO> columns = new ArrayList<>();
|
||||||
|
|
||||||
|
@Schema(description = "版本资源表字段与来源列的对照")
|
||||||
|
private List<CollectFieldCompareVO> compares = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,10 @@ public class CollectTask implements Serializable {
|
|||||||
@Schema(description = "数据库地址,如 10.1.1.14")
|
@Schema(description = "数据库地址,如 10.1.1.14")
|
||||||
private String dbHost;
|
private String dbHost;
|
||||||
|
|
||||||
@Schema(description = "数据库端口,瀚高默认 5866,PostgreSQL 默认 5432")
|
@Schema(description = "来源数据库类型:MYSQL 或 POSTGRESQL(瀚高走 PostgreSQL 协议)")
|
||||||
|
private String dbType;
|
||||||
|
|
||||||
|
@Schema(description = "数据库端口。MySQL 常用 3306,PostgreSQL 常用 5432,瀚高常用 5866")
|
||||||
private Integer dbPort;
|
private Integer dbPort;
|
||||||
|
|
||||||
@Schema(description = "数据库名")
|
@Schema(description = "数据库名")
|
||||||
|
|||||||
@@ -16,6 +16,16 @@ public interface CollectService extends IService<CollectTask> {
|
|||||||
*/
|
*/
|
||||||
Long createTask(CollectTask task);
|
Long createTask(CollectTask task);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改采集任务的连接信息。密码留空则保持原密码。
|
||||||
|
*/
|
||||||
|
void updateTask(Long id, CollectTask task);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除采集任务。
|
||||||
|
*/
|
||||||
|
void removeTask(Long id);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行采集任务,返回执行后的任务(含采集条数和结果说明)。
|
* 执行采集任务,返回执行后的任务(含采集条数和结果说明)。
|
||||||
*/
|
*/
|
||||||
|
|||||||
+64
-1
@@ -50,7 +50,7 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
|
|||||||
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
|
.collect(Collectors.toMap(c -> c.sourceType().toUpperCase(), Function.identity(), (a, b) -> a));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 创建任务:初始状态 PENDING、已采集量 0,目标量缺省为 20 万条。 */
|
/** 创建任务:初始状态 PENDING、已采集量 0。来源表至少要有一列能写入版本资源表。 */
|
||||||
@Override
|
@Override
|
||||||
public Long createTask(CollectTask task) {
|
public Long createTask(CollectTask task) {
|
||||||
task.setId(null);
|
task.setId(null);
|
||||||
@@ -59,15 +59,78 @@ public class CollectServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTa
|
|||||||
if (task.getTargetCount() == null) {
|
if (task.getTargetCount() == null) {
|
||||||
task.setTargetCount(200000);
|
task.setTargetCount(200000);
|
||||||
}
|
}
|
||||||
|
ensureMapped(task);
|
||||||
this.save(task);
|
this.save(task);
|
||||||
return task.getId();
|
return task.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updateTask(Long id, CollectTask task) {
|
||||||
|
CollectTask stored = requireTask(id);
|
||||||
|
if ("RUNNING".equals(stored.getStatus())) {
|
||||||
|
throw new BusinessException("任务正在执行,不能修改");
|
||||||
|
}
|
||||||
|
stored.setLibraryCode(task.getLibraryCode());
|
||||||
|
stored.setLibraryName(task.getLibraryName());
|
||||||
|
stored.setSourceType(task.getSourceType() == null ? "DB" : task.getSourceType());
|
||||||
|
stored.setDbHost(task.getDbHost());
|
||||||
|
stored.setDbType(task.getDbType());
|
||||||
|
stored.setDbPort(task.getDbPort());
|
||||||
|
stored.setDbName(task.getDbName());
|
||||||
|
stored.setDbUsername(task.getDbUsername());
|
||||||
|
stored.setSourceTable(task.getSourceTable());
|
||||||
|
if (task.getDbPassword() != null && !task.getDbPassword().isBlank()) {
|
||||||
|
stored.setDbPassword(task.getDbPassword());
|
||||||
|
}
|
||||||
|
ensureMapped(stored);
|
||||||
|
this.updateById(stored);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void removeTask(Long id) {
|
||||||
|
CollectTask stored = requireTask(id);
|
||||||
|
if ("RUNNING".equals(stored.getStatus())) {
|
||||||
|
throw new BusinessException("任务正在执行,不能删除");
|
||||||
|
}
|
||||||
|
this.removeById(id);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CollectTableVO previewSource(CollectTask source) {
|
public CollectTableVO previewSource(CollectTask source) {
|
||||||
|
fillPassword(source);
|
||||||
return dbTableCollector.preview(source);
|
return dbTableCollector.preview(source);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private CollectTask requireTask(Long id) {
|
||||||
|
CollectTask stored = this.getById(id);
|
||||||
|
if (stored == null) {
|
||||||
|
throw new BusinessException("采集任务不存在");
|
||||||
|
}
|
||||||
|
return stored;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 编辑时密码留空,沿用已保存的密码再去测试连接。 */
|
||||||
|
private void fillPassword(CollectTask source) {
|
||||||
|
if (source.getDbPassword() != null && !source.getDbPassword().isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (source.getId() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CollectTask stored = this.getById(source.getId());
|
||||||
|
if (stored != null) {
|
||||||
|
source.setDbPassword(stored.getDbPassword());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureMapped(CollectTask task) {
|
||||||
|
CollectTableVO preview = previewSource(task);
|
||||||
|
boolean matched = preview.getColumns().stream().anyMatch(column -> column.getTargetField() != null);
|
||||||
|
if (!matched) {
|
||||||
|
throw new BusinessException("来源表至少要有一列能对应到版本资源表");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CollectTask startTask(Long taskId) {
|
public CollectTask startTask(Long taskId) {
|
||||||
CollectTask task = this.getById(taskId);
|
CollectTask task = this.getById(taskId);
|
||||||
|
|||||||
+114
-26
@@ -3,6 +3,7 @@ package com.banben.modules.collect.service.impl;
|
|||||||
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.collect.dto.CollectColumnVO;
|
import com.banben.modules.collect.dto.CollectColumnVO;
|
||||||
|
import com.banben.modules.collect.dto.CollectFieldCompareVO;
|
||||||
import com.banben.modules.collect.dto.CollectTableVO;
|
import com.banben.modules.collect.dto.CollectTableVO;
|
||||||
import com.banben.modules.collect.entity.CollectTask;
|
import com.banben.modules.collect.entity.CollectTask;
|
||||||
import com.banben.modules.collect.service.Collector;
|
import com.banben.modules.collect.service.Collector;
|
||||||
@@ -44,6 +45,12 @@ public class DbTableCollector implements Collector {
|
|||||||
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
|
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||||
private static final int MAX_ROWS = 200000;
|
private static final int MAX_ROWS = 200000;
|
||||||
|
|
||||||
|
/** 写入 version_resource 时建议具备的字段。正题名未对应则该行无法入库。 */
|
||||||
|
private static final List<String> REQUIRED_FIELDS = List.of(
|
||||||
|
"title", "processNo", "clcCode", "keywords", "summary", "publishYear", "processDate",
|
||||||
|
"contentForm", "mediaType", "format", "language", "fulltextUrl"
|
||||||
|
);
|
||||||
|
|
||||||
private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>();
|
private static final Map<String, String> FIELD_BY_COLUMN = new HashMap<>();
|
||||||
private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>();
|
private static final Map<String, String> FIELD_LABEL = new LinkedHashMap<>();
|
||||||
private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>();
|
private static final Map<String, BiConsumer<VersionResource, String>> SETTERS = new HashMap<>();
|
||||||
@@ -151,13 +158,14 @@ public class DbTableCollector implements Collector {
|
|||||||
* 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。
|
* 用页面填写的地址、账号和表名连接来源库,返回行数以及列如何写入版本资源表。
|
||||||
*/
|
*/
|
||||||
public CollectTableVO preview(CollectTask task) {
|
public CollectTableVO preview(CollectTask task) {
|
||||||
String[] qualified = qualify(task.getSourceTable());
|
String[] qualified = qualify(task);
|
||||||
try (Connection connection = openConnection(task)) {
|
try (Connection connection = openConnection(task)) {
|
||||||
ensureTable(connection, qualified[0], qualified[1]);
|
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
|
||||||
CollectTableVO table = new CollectTableVO();
|
CollectTableVO table = new CollectTableVO();
|
||||||
table.setTableName(qualified[0] + "." + qualified[1]);
|
table.setTableName(qualified[0] + "." + qualified[1]);
|
||||||
table.setRowCount(countRows(connection, qualified[0], qualified[1]));
|
table.setRowCount(countRows(connection, qualified[0], qualified[1], mysql(task)));
|
||||||
table.setColumns(readColumns(connection, qualified[0], qualified[1]));
|
table.setColumns(readColumns(connection, qualified[0], qualified[1]));
|
||||||
|
table.setCompares(buildCompares(table.getColumns()));
|
||||||
return table;
|
return table;
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
throw new BusinessException(sqlMessage(e));
|
throw new BusinessException(sqlMessage(e));
|
||||||
@@ -166,12 +174,16 @@ public class DbTableCollector implements Collector {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int collect(CollectTask task) {
|
public int collect(CollectTask task) {
|
||||||
String[] qualified = qualify(task.getSourceTable());
|
String[] qualified = qualify(task);
|
||||||
int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS);
|
int limit = task.getTargetCount() == null ? MAX_ROWS : Math.min(Math.max(task.getTargetCount(), 1), MAX_ROWS);
|
||||||
List<Map<String, Object>> rows;
|
List<Map<String, Object>> rows;
|
||||||
try (Connection connection = openConnection(task)) {
|
try (Connection connection = openConnection(task)) {
|
||||||
ensureTable(connection, qualified[0], qualified[1]);
|
qualified[1] = canonicalTable(connection, qualified[0], qualified[1], mysql(task));
|
||||||
rows = readRows(connection, qualified[0], qualified[1], limit);
|
List<CollectColumnVO> columns = readColumns(connection, qualified[0], qualified[1]);
|
||||||
|
if (columns.stream().noneMatch(column -> column.getTargetField() != null)) {
|
||||||
|
throw new BusinessException("来源表至少要有一列能对应到版本资源表,无法写入");
|
||||||
|
}
|
||||||
|
rows = readRows(connection, qualified[0], qualified[1], limit, mysql(task));
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
throw new BusinessException(sqlMessage(e));
|
throw new BusinessException(sqlMessage(e));
|
||||||
}
|
}
|
||||||
@@ -260,7 +272,11 @@ public class DbTableCollector implements Collector {
|
|||||||
if (blank(task.getDbPassword())) {
|
if (blank(task.getDbPassword())) {
|
||||||
throw new BusinessException("请填写数据库密码");
|
throw new BusinessException("请填写数据库密码");
|
||||||
}
|
}
|
||||||
String url = "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
|
String url = mysql(task)
|
||||||
|
? "jdbc:mysql://" + task.getDbHost().trim() + ":" + port + "/" + task.getDbName().trim()
|
||||||
|
+ "?connectTimeout=8000&socketTimeout=30000&useSSL=false&allowPublicKeyRetrieval=true"
|
||||||
|
+ "&characterEncoding=utf8&serverTimezone=Asia/Shanghai"
|
||||||
|
: "jdbc:postgresql://" + task.getDbHost().trim() + ":" + port + "/"
|
||||||
+ task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30";
|
+ task.getDbName().trim() + "?connectTimeout=8&socketTimeout=30";
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
properties.setProperty("user", task.getDbUsername().trim());
|
properties.setProperty("user", task.getDbUsername().trim());
|
||||||
@@ -272,47 +288,87 @@ public class DbTableCollector implements Collector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String[] qualify(String raw) {
|
/**
|
||||||
if (blank(raw)) {
|
* 按页面选择的数据库类型决定驱动。未填写类型的旧任务仍按 3306 识别为 MySQL。
|
||||||
|
*/
|
||||||
|
private boolean mysql(CollectTask task) {
|
||||||
|
String type = task.getDbType() == null ? "" : task.getDbType().trim().toUpperCase(Locale.ROOT);
|
||||||
|
if ("MYSQL".equals(type)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if ("POSTGRESQL".equals(type) || "HIGHGO".equals(type)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (type.isEmpty()) {
|
||||||
|
return task.getDbPort() != null && task.getDbPort() == 3306;
|
||||||
|
}
|
||||||
|
throw new BusinessException("数据库类型只支持 MySQL 或 PostgreSQL");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String[] qualify(CollectTask task) {
|
||||||
|
if (blank(task.getSourceTable())) {
|
||||||
throw new BusinessException("请填写要采集的表名");
|
throw new BusinessException("请填写要采集的表名");
|
||||||
}
|
}
|
||||||
String[] parts = raw.trim().split("\\.");
|
String[] parts = task.getSourceTable().trim().split("\\.");
|
||||||
if (parts.length > 2) {
|
if (parts.length > 2) {
|
||||||
throw new BusinessException("表名格式应为表名,或模式名.表名");
|
throw new BusinessException("表名格式应为表名,或模式名.表名");
|
||||||
}
|
}
|
||||||
String schema = parts.length == 2 ? parts[0] : "public";
|
boolean mysql = mysql(task);
|
||||||
|
String schema = parts.length == 2 ? parts[0] : (mysql ? task.getDbName().trim() : "public");
|
||||||
String table = parts.length == 2 ? parts[1] : parts[0];
|
String table = parts.length == 2 ? parts[1] : parts[0];
|
||||||
if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) {
|
if (!schema.matches("[A-Za-z_][A-Za-z0-9_]*") || !table.matches("[A-Za-z_][A-Za-z0-9_]*")) {
|
||||||
throw new BusinessException("表名只能包含字母、数字和下划线");
|
throw new BusinessException("表名只能包含字母、数字和下划线");
|
||||||
}
|
}
|
||||||
return new String[]{schema.toLowerCase(Locale.ROOT), table.toLowerCase(Locale.ROOT)};
|
if (!mysql) {
|
||||||
|
schema = schema.toLowerCase(Locale.ROOT);
|
||||||
|
table = table.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
return new String[]{schema, table};
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ensureTable(Connection connection, String schema, String table) throws SQLException {
|
private String canonicalTable(Connection connection, String schema, String table, boolean mysql) throws SQLException {
|
||||||
try (PreparedStatement statement = connection.prepareStatement("""
|
String sql = mysql
|
||||||
SELECT COUNT(*) FROM information_schema.tables
|
? """
|
||||||
|
SELECT table_name FROM information_schema.tables
|
||||||
|
WHERE table_schema = ? AND LOWER(table_name) = LOWER(?)
|
||||||
|
"""
|
||||||
|
: """
|
||||||
|
SELECT table_name FROM information_schema.tables
|
||||||
WHERE table_schema = ? AND table_name = ?
|
WHERE table_schema = ? AND table_name = ?
|
||||||
""")) {
|
""";
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||||
statement.setString(1, schema);
|
statement.setString(1, schema);
|
||||||
statement.setString(2, table);
|
statement.setString(2, table);
|
||||||
try (ResultSet resultSet = statement.executeQuery()) {
|
try (ResultSet resultSet = statement.executeQuery()) {
|
||||||
resultSet.next();
|
String found = null;
|
||||||
if (resultSet.getInt(1) == 0) {
|
while (resultSet.next()) {
|
||||||
|
String name = resultSet.getString(1);
|
||||||
|
if (name.equals(table)) {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
found = name;
|
||||||
|
}
|
||||||
|
if (found == null) {
|
||||||
throw new BusinessException("来源库中不存在表:" + schema + "." + table);
|
throw new BusinessException("来源库中不存在表:" + schema + "." + table);
|
||||||
}
|
}
|
||||||
|
return found;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private long countRows(Connection connection, String schema, String table) throws SQLException {
|
private long countRows(Connection connection, String schema, String table, boolean mysql) throws SQLException {
|
||||||
try (PreparedStatement statement = connection.prepareStatement(
|
try (PreparedStatement statement = connection.prepareStatement(
|
||||||
"SELECT COUNT(*) FROM \"" + schema + "\".\"" + table + "\"");
|
"SELECT COUNT(*) FROM " + quote(schema, mysql) + "." + quote(table, mysql));
|
||||||
ResultSet resultSet = statement.executeQuery()) {
|
ResultSet resultSet = statement.executeQuery()) {
|
||||||
resultSet.next();
|
resultSet.next();
|
||||||
return resultSet.getLong(1);
|
return resultSet.getLong(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String quote(String identifier, boolean mysql) {
|
||||||
|
return mysql ? "`" + identifier + "`" : "\"" + identifier + "\"";
|
||||||
|
}
|
||||||
|
|
||||||
private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException {
|
private List<CollectColumnVO> readColumns(Connection connection, String schema, String table) throws SQLException {
|
||||||
List<CollectColumnVO> columns = new ArrayList<>();
|
List<CollectColumnVO> columns = new ArrayList<>();
|
||||||
try (PreparedStatement statement = connection.prepareStatement("""
|
try (PreparedStatement statement = connection.prepareStatement("""
|
||||||
@@ -337,11 +393,11 @@ public class DbTableCollector implements Collector {
|
|||||||
return columns;
|
return columns;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit)
|
private List<Map<String, Object>> readRows(Connection connection, String schema, String table, int limit,
|
||||||
throws SQLException {
|
boolean mysql) throws SQLException {
|
||||||
List<Map<String, Object>> rows = new ArrayList<>();
|
List<Map<String, Object>> rows = new ArrayList<>();
|
||||||
try (PreparedStatement statement = connection.prepareStatement(
|
try (PreparedStatement statement = connection.prepareStatement(
|
||||||
"SELECT * FROM \"" + schema + "\".\"" + table + "\" LIMIT " + limit);
|
"SELECT * FROM " + quote(schema, mysql) + "." + quote(table, mysql) + " LIMIT " + limit);
|
||||||
ResultSet resultSet = statement.executeQuery()) {
|
ResultSet resultSet = statement.executeQuery()) {
|
||||||
ResultSetMetaData meta = resultSet.getMetaData();
|
ResultSetMetaData meta = resultSet.getMetaData();
|
||||||
while (resultSet.next()) {
|
while (resultSet.next()) {
|
||||||
@@ -358,13 +414,14 @@ public class DbTableCollector implements Collector {
|
|||||||
private String sqlMessage(SQLException exception) {
|
private String sqlMessage(SQLException exception) {
|
||||||
String message = exception.getMessage() == null ? "" : exception.getMessage();
|
String message = exception.getMessage() == null ? "" : exception.getMessage();
|
||||||
String lower = message.toLowerCase(Locale.ROOT);
|
String lower = message.toLowerCase(Locale.ROOT);
|
||||||
if (lower.contains("password authentication failed") || lower.contains("authentication failed")) {
|
if (lower.contains("password authentication failed") || lower.contains("authentication failed")
|
||||||
|
|| lower.contains("access denied")) {
|
||||||
return "数据库用户名或密码错误";
|
return "数据库用户名或密码错误";
|
||||||
}
|
}
|
||||||
if (lower.contains("does not exist") && lower.contains("database")) {
|
if ((lower.contains("does not exist") && lower.contains("database")) || lower.contains("unknown database")) {
|
||||||
return "数据库不存在";
|
return "数据库不存在";
|
||||||
}
|
}
|
||||||
if (lower.contains("connection refused")) {
|
if (lower.contains("connection refused") || lower.contains("communications link failure")) {
|
||||||
return "连接被拒绝,请检查数据库地址和端口";
|
return "连接被拒绝,请检查数据库地址和端口";
|
||||||
}
|
}
|
||||||
if (lower.contains("timeout") || lower.contains("timed out")) {
|
if (lower.contains("timeout") || lower.contains("timed out")) {
|
||||||
@@ -377,6 +434,37 @@ public class DbTableCollector implements Collector {
|
|||||||
return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief;
|
return brief.isEmpty() ? "连接数据库失败" : "连接数据库失败:" + brief;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<CollectFieldCompareVO> buildCompares(List<CollectColumnVO> columns) {
|
||||||
|
Map<String, String> sourceByField = new LinkedHashMap<>();
|
||||||
|
for (CollectColumnVO column : columns) {
|
||||||
|
if (column.getTargetField() != null) {
|
||||||
|
sourceByField.putIfAbsent(column.getTargetField(), column.getColumnName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<CollectFieldCompareVO> compares = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String field : REQUIRED_FIELDS) {
|
||||||
|
compares.add(compareItem(field, true, sourceByField));
|
||||||
|
seen.add(field);
|
||||||
|
}
|
||||||
|
for (String field : FIELD_LABEL.keySet()) {
|
||||||
|
if (!seen.contains(field)) {
|
||||||
|
compares.add(compareItem(field, false, sourceByField));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return compares;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CollectFieldCompareVO compareItem(String field, boolean required, Map<String, String> sourceByField) {
|
||||||
|
CollectFieldCompareVO item = new CollectFieldCompareVO();
|
||||||
|
item.setTargetField(field);
|
||||||
|
item.setTargetLabel(FIELD_LABEL.get(field));
|
||||||
|
item.setRequired(required);
|
||||||
|
item.setSourceColumn(sourceByField.get(field));
|
||||||
|
item.setMatched(item.getSourceColumn() != null);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
private Set<String> loadProcessNos() {
|
private Set<String> loadProcessNos() {
|
||||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo);
|
query.select(VersionResource::getProcessNo).isNotNull(VersionResource::getProcessNo);
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
package com.banben.modules.deposit.controller;
|
package com.banben.modules.deposit.controller;
|
||||||
|
|
||||||
|
import com.banben.common.BusinessException;
|
||||||
import com.banben.common.PageResult;
|
import com.banben.common.PageResult;
|
||||||
import com.banben.common.Result;
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.auth.context.UserContext;
|
||||||
|
import com.banben.modules.auth.context.LoginUser;
|
||||||
import com.banben.modules.deposit.dto.DepositQuery;
|
import com.banben.modules.deposit.dto.DepositQuery;
|
||||||
import com.banben.modules.deposit.entity.DepositRecord;
|
import com.banben.modules.deposit.entity.DepositRecord;
|
||||||
import com.banben.modules.deposit.service.DepositService;
|
import com.banben.modules.deposit.service.DepositService;
|
||||||
@@ -30,31 +33,43 @@ public class DepositController {
|
|||||||
return Result.success(depositService.submit(record));
|
return Result.success(depositService.submit(record));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理端查看呈缴列表")
|
@Operation(summary = "管理端查看呈缴列表(仅管理员)")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
public Result<PageResult<DepositRecord>> page(DepositQuery query) {
|
public Result<PageResult<DepositRecord>> page(DepositQuery query) {
|
||||||
|
requireAdmin();
|
||||||
return Result.success(depositService.pageQuery(query));
|
return Result.success(depositService.pageQuery(query));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理端查看呈缴详情")
|
@Operation(summary = "管理端查看呈缴详情(仅管理员)")
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public Result<DepositRecord> detail(@PathVariable Long id) {
|
public Result<DepositRecord> detail(@PathVariable Long id) {
|
||||||
|
requireAdmin();
|
||||||
return Result.success(depositService.getById(id));
|
return Result.success(depositService.getById(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理端接收呈缴")
|
@Operation(summary = "管理端接收呈缴(仅管理员)")
|
||||||
@PostMapping("/{id}/accept")
|
@PostMapping("/{id}/accept")
|
||||||
public Result<Void> accept(@PathVariable Long id,
|
public Result<Void> accept(@PathVariable Long id,
|
||||||
@RequestParam(required = false) String auditRemark) {
|
@RequestParam(required = false) String auditRemark) {
|
||||||
|
requireAdmin();
|
||||||
depositService.audit(id, true, auditRemark);
|
depositService.audit(id, true, auditRemark);
|
||||||
return Result.success();
|
return Result.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理端退回呈缴")
|
@Operation(summary = "管理端退回呈缴(仅管理员)")
|
||||||
@PostMapping("/{id}/reject")
|
@PostMapping("/{id}/reject")
|
||||||
public Result<Void> reject(@PathVariable Long id,
|
public Result<Void> reject(@PathVariable Long id,
|
||||||
@RequestParam(required = false) String auditRemark) {
|
@RequestParam(required = false) String auditRemark) {
|
||||||
|
requireAdmin();
|
||||||
depositService.audit(id, false, auditRemark);
|
depositService.audit(id, false, auditRemark);
|
||||||
return Result.success();
|
return Result.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 管理端接口统一校验:仅管理员可访问(提交呈缴不受限) */
|
||||||
|
private void requireAdmin() {
|
||||||
|
LoginUser user = UserContext.get();
|
||||||
|
if (user == null || !"ADMIN".equalsIgnoreCase(user.role())) {
|
||||||
|
throw new BusinessException("仅管理员可执行该操作");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ import java.util.List;
|
|||||||
/**
|
/**
|
||||||
* 数据治理接口。
|
* 数据治理接口。
|
||||||
*
|
*
|
||||||
* <p>对应「数据治理」四动作:聚同、优化、提示、提纯。</p>
|
* <p>对应「数据治理」:聚同、优化、提示、提纯。</p>
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li>
|
* <li>优化:整合聚同文献的不同描述元数据,生成质量更高、要素更完整的元数据。</li>
|
||||||
* <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li>
|
* <li>提示:生成疑似同一文献提示清单、疑似元数据错漏提示清单。</li>
|
||||||
|
|||||||
+237
-2
@@ -78,6 +78,30 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
|
|
||||||
private static final int BATCH = 500;
|
private static final int BATCH = 500;
|
||||||
|
|
||||||
|
/** 不超过该行数时,提示和提纯仍在内存里做题名包含等细查。超过后改走数据库聚合,避免整表进堆。 */
|
||||||
|
private static final int FULL_SCAN_MAX = 20000;
|
||||||
|
|
||||||
|
/** 清单返回给页面的上限。条数仍按全库统计。 */
|
||||||
|
private static final int HINT_LIST_LIMIT = 200;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 与 {@link #defectsOf} 一致的错漏条件。只在超过 {@link #FULL_SCAN_MAX} 时使用,
|
||||||
|
* 用来计数和打标,不再把整表装进内存。
|
||||||
|
*/
|
||||||
|
private static final String DEFECT_SQL = """
|
||||||
|
(btrim(coalesce(clc_code, '')) = ''
|
||||||
|
OR btrim(coalesce(keywords, '')) = ''
|
||||||
|
OR char_length(btrim(coalesce(summary, ''))) < 100
|
||||||
|
OR btrim(coalesce(publish_year, '')) !~ '^[0-9]{4}$'
|
||||||
|
OR btrim(coalesce(media_type, '')) NOT IN ('纸质', '电子')
|
||||||
|
OR btrim(coalesce(language, '')) !~ '^[A-Za-z]{3}$'
|
||||||
|
OR btrim(coalesce(page_count, '')) !~ '^[0-9]+$'
|
||||||
|
OR btrim(coalesce(author, '')) = ''
|
||||||
|
OR btrim(coalesce(fulltext_url, '')) = ''
|
||||||
|
OR btrim(coalesce(source_library, '')) = ''
|
||||||
|
OR (btrim(coalesce(isbn, '')) <> '' AND btrim(isbn) !~ '^97[89](-[0-9]+){4}$'))
|
||||||
|
""";
|
||||||
|
|
||||||
private final VersionResourceMapper resourceMapper;
|
private final VersionResourceMapper resourceMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -117,9 +141,14 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
try {
|
try {
|
||||||
vo = buildHints(true);
|
vo = buildHints(true);
|
||||||
job.setAffectedCount(vo.getDuplicateGroupCount() + vo.getDefectCount());
|
job.setAffectedCount(vo.getDuplicateGroupCount() + vo.getDefectCount());
|
||||||
job.setResultSummary(String.format(
|
String summary = String.format(
|
||||||
"疑似同一文献 %d 组;疑似元数据错漏 %d 条(错漏记录已标记,请人工核验)",
|
"疑似同一文献 %d 组;疑似元数据错漏 %d 条(错漏记录已标记,请人工核验)",
|
||||||
vo.getDuplicateGroupCount(), vo.getDefectCount()));
|
vo.getDuplicateGroupCount(), vo.getDefectCount());
|
||||||
|
if (vo.getDuplicateGroups().size() < vo.getDuplicateGroupCount()
|
||||||
|
|| vo.getDefects().size() < vo.getDefectCount()) {
|
||||||
|
summary += "。清单过长,页面只展示前 " + HINT_LIST_LIMIT + " 条";
|
||||||
|
}
|
||||||
|
job.setResultSummary(summary);
|
||||||
job.setStatus("SUCCESS");
|
job.setStatus("SUCCESS");
|
||||||
vo.setJob(job);
|
vo.setJob(job);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -428,6 +457,9 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
* 疑似错漏:必备要素缺失、摘要不足 100 字、年份/语种/页码/ISBN 格式不正确。
|
* 疑似错漏:必备要素缺失、摘要不足 100 字、年份/语种/页码/ISBN 格式不正确。
|
||||||
*/
|
*/
|
||||||
private GovernanceHintVO buildHints(boolean persistFlag) {
|
private GovernanceHintVO buildHints(boolean persistFlag) {
|
||||||
|
if (countActive() > FULL_SCAN_MAX) {
|
||||||
|
return buildHintsForLargeTable(persistFlag);
|
||||||
|
}
|
||||||
List<VersionResource> active = loadActive();
|
List<VersionResource> active = loadActive();
|
||||||
GovernanceHintVO vo = new GovernanceHintVO();
|
GovernanceHintVO vo = new GovernanceHintVO();
|
||||||
vo.setDuplicateGroups(findSuspectedDuplicates(active));
|
vo.setDuplicateGroups(findSuspectedDuplicates(active));
|
||||||
@@ -454,6 +486,103 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 大表不再整表读入。疑似重复只按 ISBN、或无 ISBN 时的书名+作者+出版社+出版年份在库里聚合;
|
||||||
|
* 题名互相包含这类细查只在 {@link #FULL_SCAN_MAX} 以内做。错漏用 {@link #DEFECT_SQL} 计数和打标,
|
||||||
|
* 页面只带回前 {@link #HINT_LIST_LIMIT} 条。
|
||||||
|
*/
|
||||||
|
private GovernanceHintVO buildHintsForLargeTable(boolean persistFlag) {
|
||||||
|
GovernanceHintVO vo = new GovernanceHintVO();
|
||||||
|
List<DuplicateGroupVO> groups = new ArrayList<>();
|
||||||
|
vo.setDuplicateGroupCount(appendExactDuplicateGroups(groups, HINT_LIST_LIMIT));
|
||||||
|
vo.setDuplicateGroups(groups);
|
||||||
|
|
||||||
|
long defectCount = countDefects();
|
||||||
|
vo.setDefectCount(defectCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) defectCount);
|
||||||
|
vo.setDefects(sampleDefects(HINT_LIST_LIMIT));
|
||||||
|
if (persistFlag) {
|
||||||
|
markDefectsBySql();
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int appendExactDuplicateGroups(List<DuplicateGroupVO> groups, int limit) {
|
||||||
|
int count = 0;
|
||||||
|
for (Map<String, Object> group : isbnDuplicateGroups()) {
|
||||||
|
count++;
|
||||||
|
if (groups.size() >= limit) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Object isbn = group.get("isbn");
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.eq(VersionResource::getIsbn, isbn)
|
||||||
|
.and(this::notMergedOut)
|
||||||
|
.orderByAsc(VersionResource::getId);
|
||||||
|
groups.add(toDuplicateGroup("ISBN 相同,疑似同一文献", String.valueOf(isbn), resourceMapper.selectList(query)));
|
||||||
|
}
|
||||||
|
for (Map<String, Object> group : fieldDuplicateGroups()) {
|
||||||
|
count++;
|
||||||
|
if (groups.size() >= limit) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.eq(VersionResource::getTitle, group.get("title"));
|
||||||
|
eqOrIsNull(query, VersionResource::getAuthor, group.get("author"));
|
||||||
|
eqOrIsNull(query, VersionResource::getPublisher, group.get("publisher"));
|
||||||
|
eqOrIsNull(query, VersionResource::getPublishYear, group.get("publish_year"));
|
||||||
|
query.and(x -> x.isNull(VersionResource::getIsbn).or().eq(VersionResource::getIsbn, ""))
|
||||||
|
.and(this::notMergedOut)
|
||||||
|
.orderByAsc(VersionResource::getId);
|
||||||
|
String key = text(group.get("title") == null ? null : String.valueOf(group.get("title")));
|
||||||
|
groups.add(toDuplicateGroup("书名、责任者、出版社、出版年份一致,疑似同一文献", key, resourceMapper.selectList(query)));
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long countDefects() {
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.and(this::notMergedOut).apply(DEFECT_SQL);
|
||||||
|
Long count = resourceMapper.selectCount(query);
|
||||||
|
return count == null ? 0 : count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<DefectItemVO> sampleDefects(int limit) {
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.and(this::notMergedOut)
|
||||||
|
.apply(DEFECT_SQL)
|
||||||
|
.orderByAsc(VersionResource::getId)
|
||||||
|
.last("LIMIT " + limit);
|
||||||
|
List<DefectItemVO> defects = new ArrayList<>();
|
||||||
|
for (VersionResource resource : resourceMapper.selectList(query)) {
|
||||||
|
List<String> issues = defectsOf(resource);
|
||||||
|
if (!issues.isEmpty()) {
|
||||||
|
defects.add(toDefect(resource, issues));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return defects;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markDefectsBySql() {
|
||||||
|
LambdaUpdateWrapper<VersionResource> mark = new LambdaUpdateWrapper<>();
|
||||||
|
mark.set(VersionResource::getAbnormalFlag, 1)
|
||||||
|
.and(this::notMergedOutUpdate)
|
||||||
|
.apply(DEFECT_SQL);
|
||||||
|
resourceMapper.update(null, mark);
|
||||||
|
|
||||||
|
LambdaUpdateWrapper<VersionResource> clear = new LambdaUpdateWrapper<>();
|
||||||
|
clear.set(VersionResource::getAbnormalFlag, 0)
|
||||||
|
.eq(VersionResource::getAbnormalFlag, 1)
|
||||||
|
.and(this::notMergedOutUpdate)
|
||||||
|
.apply("NOT (" + DEFECT_SQL + ")");
|
||||||
|
resourceMapper.update(null, clear);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notMergedOutUpdate(LambdaUpdateWrapper<VersionResource> query) {
|
||||||
|
query.isNull(VersionResource::getGovernStatus)
|
||||||
|
.or()
|
||||||
|
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
private List<DuplicateGroupVO> findSuspectedDuplicates(List<VersionResource> active) {
|
private List<DuplicateGroupVO> findSuspectedDuplicates(List<VersionResource> active) {
|
||||||
List<DuplicateGroupVO> groups = new ArrayList<>();
|
List<DuplicateGroupVO> groups = new ArrayList<>();
|
||||||
Set<Long> emitted = new HashSet<>();
|
Set<Long> emitted = new HashSet<>();
|
||||||
@@ -606,6 +735,10 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
* 尚未聚同的重复文献、已聚同但还没优化的主记录、仍有错漏的记录。
|
* 尚未聚同的重复文献、已聚同但还没优化的主记录、仍有错漏的记录。
|
||||||
*/
|
*/
|
||||||
private void runPurify(GovernanceJob job) {
|
private void runPurify(GovernanceJob job) {
|
||||||
|
if (countActive() > FULL_SCAN_MAX) {
|
||||||
|
runPurifyInBatches(job);
|
||||||
|
return;
|
||||||
|
}
|
||||||
List<VersionResource> active = loadActive();
|
List<VersionResource> active = loadActive();
|
||||||
Set<Long> unresolved = unresolvedDuplicateIds(active);
|
Set<Long> unresolved = unresolvedDuplicateIds(active);
|
||||||
|
|
||||||
@@ -691,6 +824,108 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
|||||||
|
|
||||||
// ==================== 公共方法 ====================
|
// ==================== 公共方法 ====================
|
||||||
|
|
||||||
|
private void runPurifyInBatches(GovernanceJob job) {
|
||||||
|
Set<Long> unresolved = duplicateIdsBySql();
|
||||||
|
int nonBook = 0;
|
||||||
|
int sensitive = 0;
|
||||||
|
int blocked = 0;
|
||||||
|
int duplicated = 0;
|
||||||
|
int waitOptimize = 0;
|
||||||
|
int defect = 0;
|
||||||
|
List<Long> accepted = new ArrayList<>();
|
||||||
|
long lastId = 0;
|
||||||
|
while (true) {
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.and(this::notMergedOut)
|
||||||
|
.gt(VersionResource::getId, lastId)
|
||||||
|
.orderByAsc(VersionResource::getId)
|
||||||
|
.last("LIMIT " + BATCH);
|
||||||
|
List<VersionResource> batch = resourceMapper.selectList(query);
|
||||||
|
if (batch.isEmpty()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
lastId = batch.get(batch.size() - 1).getId();
|
||||||
|
for (VersionResource resource : batch) {
|
||||||
|
if (GovernStatus.FINAL.getCode().equals(resource.getGovernStatus())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!paperElectronicBook(resource)) {
|
||||||
|
nonBook++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (resource.getSensitiveFlag() != null && resource.getSensitiveFlag() == 1) {
|
||||||
|
sensitive++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (resource.getManageStatus() != null && resource.getManageStatus() != 0) {
|
||||||
|
blocked++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (unresolved.contains(resource.getId())) {
|
||||||
|
duplicated++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (GovernStatus.MERGED.getCode().equals(resource.getGovernStatus())) {
|
||||||
|
waitOptimize++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!defectsOf(resource).isEmpty()) {
|
||||||
|
defect++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
accepted.add(resource.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updateStatus(accepted, GovernStatus.FINAL.getCode());
|
||||||
|
job.setAffectedCount(accepted.size());
|
||||||
|
job.setResultSummary(String.format(
|
||||||
|
"已将 %d 条纸电图书纳入版本资源数据集。"
|
||||||
|
+ "未纳入:非纸电图书 %d 条,敏感 %d 条,已屏蔽或下架 %d 条,"
|
||||||
|
+ "尚未聚同的重复文献 %d 条,已聚同但未优化 %d 条,仍有错漏 %d 条",
|
||||||
|
accepted.size(), nonBook, sensitive, blocked, duplicated, waitOptimize, defect));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<Long> duplicateIdsBySql() {
|
||||||
|
Set<Long> ids = new HashSet<>();
|
||||||
|
QueryWrapper<VersionResource> byIsbn = new QueryWrapper<>();
|
||||||
|
byIsbn.select("id")
|
||||||
|
.apply("btrim(coalesce(isbn, '')) <> ''")
|
||||||
|
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
|
||||||
|
.inSql("isbn", "SELECT isbn FROM version_resource WHERE deleted = 0 "
|
||||||
|
+ "AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
|
||||||
|
+ "AND btrim(coalesce(isbn, '')) <> '' "
|
||||||
|
+ "GROUP BY isbn HAVING COUNT(*) > 1");
|
||||||
|
collectIds(ids, resourceMapper.selectMaps(byIsbn));
|
||||||
|
|
||||||
|
QueryWrapper<VersionResource> byField = new QueryWrapper<>();
|
||||||
|
byField.select("id")
|
||||||
|
.apply("btrim(coalesce(isbn, '')) = ''")
|
||||||
|
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
|
||||||
|
.apply("(title, author, publisher, publish_year) IN ("
|
||||||
|
+ "SELECT title, author, publisher, publish_year FROM version_resource "
|
||||||
|
+ "WHERE deleted = 0 AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
|
||||||
|
+ "AND btrim(coalesce(isbn, '')) = '' AND title IS NOT NULL "
|
||||||
|
+ "GROUP BY title, author, publisher, publish_year HAVING COUNT(*) > 1)");
|
||||||
|
collectIds(ids, resourceMapper.selectMaps(byField));
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collectIds(Set<Long> ids, List<Map<String, Object>> rows) {
|
||||||
|
for (Map<String, Object> row : rows) {
|
||||||
|
Object id = row.get("id");
|
||||||
|
if (id instanceof Number number) {
|
||||||
|
ids.add(number.longValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long countActive() {
|
||||||
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
|
query.and(this::notMergedOut);
|
||||||
|
Long count = resourceMapper.selectCount(query);
|
||||||
|
return count == null ? 0 : count;
|
||||||
|
}
|
||||||
|
|
||||||
private List<VersionResource> loadActive() {
|
private List<VersionResource> loadActive() {
|
||||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||||
query.and(this::notMergedOut).orderByAsc(VersionResource::getId);
|
query.and(this::notMergedOut).orderByAsc(VersionResource::getId);
|
||||||
|
|||||||
+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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -2,14 +2,22 @@ package com.banben.modules.resource.controller;
|
|||||||
|
|
||||||
import com.banben.common.PageResult;
|
import com.banben.common.PageResult;
|
||||||
import com.banben.common.Result;
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.resource.dto.ImportResult;
|
||||||
import com.banben.modules.resource.dto.VersionResourceQuery;
|
import com.banben.modules.resource.dto.VersionResourceQuery;
|
||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
|
import com.banben.modules.resource.service.VersionResourceExcelService;
|
||||||
import com.banben.modules.resource.service.VersionResourceService;
|
import com.banben.modules.resource.service.VersionResourceService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 版本资源元数据管理接口。
|
* 版本资源元数据管理接口。
|
||||||
@@ -48,6 +56,24 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class VersionResourceController {
|
public class VersionResourceController {
|
||||||
|
|
||||||
private final VersionResourceService versionResourceService;
|
private final VersionResourceService versionResourceService;
|
||||||
|
private final VersionResourceExcelService excelService;
|
||||||
|
|
||||||
|
@Operation(summary = "下载 Excel 导入模板")
|
||||||
|
@GetMapping("/template")
|
||||||
|
public void downloadTemplate(HttpServletResponse response) throws IOException {
|
||||||
|
String fileName = URLEncoder.encode("版本资源导入模板.xlsx", StandardCharsets.UTF_8);
|
||||||
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
|
response.setCharacterEncoding("UTF-8");
|
||||||
|
response.setHeader("Content-Disposition",
|
||||||
|
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
|
||||||
|
excelService.writeTemplate(response.getOutputStream());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Excel 导入版本资源")
|
||||||
|
@PostMapping("/import")
|
||||||
|
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
|
||||||
|
return Result.success(excelService.importExcel(file));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "分页查询版本资源")
|
@Operation(summary = "分页查询版本资源")
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.banben.modules.resource.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Excel 导入结果。
|
||||||
|
*
|
||||||
|
* <p>导入不会因为个别行出错而整体失败:能入库的照常入库,
|
||||||
|
* 失败的行记录行号与原因,前端一次性提示给用户。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ImportResult {
|
||||||
|
|
||||||
|
/** 解析到的有效数据行数 */
|
||||||
|
private int total;
|
||||||
|
|
||||||
|
/** 新增成功条数 */
|
||||||
|
private int inserted;
|
||||||
|
|
||||||
|
/** 按加工编号匹配到已有记录并更新的条数 */
|
||||||
|
private int updated;
|
||||||
|
|
||||||
|
/** 失败条数 */
|
||||||
|
private int failed;
|
||||||
|
|
||||||
|
/** 跳过的模板示例行数 */
|
||||||
|
private int skipped;
|
||||||
|
|
||||||
|
/** 失败明细,格式如「第 5 行:正题名不能为空」 */
|
||||||
|
private List<String> errors = new ArrayList<>();
|
||||||
|
|
||||||
|
public void addError(int excelRowNum, String reason) {
|
||||||
|
if (errors.size() < 50) {
|
||||||
|
errors.add("第 " + excelRowNum + " 行:" + reason);
|
||||||
|
}
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.banben.modules.resource.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源多来源(一条文献可来自多个资源库 / 来源馆)。
|
||||||
|
*
|
||||||
|
* <p>对应招标文件检索结果概览页要求:「一条结果可有多个来源,按资源库图标+名称展示,点击可下载」。
|
||||||
|
* 主表 {@link VersionResource} 上的 source_library / source_repo / fulltext_url 等字段作为
|
||||||
|
* 「主来源」兜底;本表保存该文献的全部来源,概览页据此渲染多个可分别下载的来源。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("resource_source")
|
||||||
|
@Schema(description = "版本资源多来源")
|
||||||
|
public class ResourceSource implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "来源记录主键")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "关联版本资源主记录ID(version_resource.id)")
|
||||||
|
private Long resourceId;
|
||||||
|
|
||||||
|
@Schema(description = "来源资源库名")
|
||||||
|
private String sourceRepo;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆")
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆地址(IP:端口或域名)")
|
||||||
|
private String sourceLibraryAddr;
|
||||||
|
|
||||||
|
@Schema(description = "全文地址(下载地址)")
|
||||||
|
private String fulltextUrl;
|
||||||
|
|
||||||
|
@Schema(description = "加工编号(该来源库内的编号)")
|
||||||
|
private String processNo;
|
||||||
|
|
||||||
|
@Schema(description = "媒体类型(纸质/电子,可选,便于概览页区分)")
|
||||||
|
private String mediaType;
|
||||||
|
|
||||||
|
@Schema(description = "展示顺序,数值小的靠前")
|
||||||
|
private Integer sortNo;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
@Schema(description = "更新时间")
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableLogic
|
||||||
|
@Schema(description = "逻辑删除:0未删 1已删")
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -66,7 +66,8 @@ public class VersionResource implements Serializable {
|
|||||||
@Schema(description = "所属任务年份(必备)")
|
@Schema(description = "所属任务年份(必备)")
|
||||||
private String taskYear;
|
private String taskYear;
|
||||||
|
|
||||||
@Schema(description = "来源馆(必备)")
|
@TableField("source_library")
|
||||||
|
@Schema(description = "来源馆(必备),对应 version_resource.source_library")
|
||||||
private String sourceLibrary;
|
private String sourceLibrary;
|
||||||
|
|
||||||
@Schema(description = "来源馆地址(必备,IP:端口或域名)")
|
@Schema(description = "来源馆地址(必备,IP:端口或域名)")
|
||||||
@@ -149,6 +150,20 @@ public class VersionResource implements Serializable {
|
|||||||
@Schema(description = "管理状态:0正常 1屏蔽 2下架")
|
@Schema(description = "管理状态:0正常 1屏蔽 2下架")
|
||||||
private Integer manageStatus;
|
private Integer manageStatus;
|
||||||
|
|
||||||
|
@Schema(description = "作者单位(责任者所属机构)")
|
||||||
|
private String authorOrg;
|
||||||
|
|
||||||
|
@Schema(description = "来源资源库名(主来源兜底,多来源详见 sources)")
|
||||||
|
private String sourceRepo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多来源列表(一条文献可来自多个资源库)。
|
||||||
|
* 非数据库字段,由检索/细览接口按 resource_id 批量挂载,供概览页按来源展示并分别下载。
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
@Schema(description = "多来源列表:一条文献可来自多个资源库,概览页按来源图标+名称展示并可分别下载")
|
||||||
|
private java.util.List<ResourceSource> sources;
|
||||||
|
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@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> {
|
||||||
|
}
|
||||||
@@ -3,10 +3,26 @@ package com.banben.modules.resource.mapper;
|
|||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 版本资源 Mapper。
|
* 版本资源 Mapper。
|
||||||
*/
|
*/
|
||||||
@Mapper
|
@Mapper
|
||||||
public interface VersionResourceMapper extends BaseMapper<VersionResource> {
|
public interface VersionResourceMapper extends BaseMapper<VersionResource> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 元数据关键词热度:按分号/逗号/顿号/空白拆分 keywords 列后分组统计。
|
||||||
|
* 用于检索热词词云(与检索日志热词合并展示,均为库内真实数据)。
|
||||||
|
*/
|
||||||
|
@Select("SELECT k AS name, COUNT(*) AS cnt FROM ("
|
||||||
|
+ " SELECT regexp_split_to_table(keywords, '[;;,,、\\s]+') AS k"
|
||||||
|
+ " FROM version_resource"
|
||||||
|
+ " WHERE deleted = 0 AND keywords IS NOT NULL AND keywords <> ''"
|
||||||
|
+ ") t WHERE k <> '' GROUP BY k ORDER BY cnt DESC LIMIT #{limit}")
|
||||||
|
List<Map<String, Object>> splitKeywordCounts(@Param("limit") int limit);
|
||||||
}
|
}
|
||||||
|
|||||||
+428
@@ -0,0 +1,428 @@
|
|||||||
|
package com.banben.modules.resource.service;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.banben.modules.resource.dto.ImportResult;
|
||||||
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.poi.ss.usermodel.*;
|
||||||
|
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 版本资源 Excel 模板导出与导入。
|
||||||
|
*
|
||||||
|
* <p>模板结构:第 1 行表头(* 表示必填),第 2 行填写说明,第 3 行起为用户数据。
|
||||||
|
* 导入时按表头名称匹配列,因此用户调整列顺序也不影响。</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class VersionResourceExcelService {
|
||||||
|
|
||||||
|
private final VersionResourceService versionResourceService;
|
||||||
|
|
||||||
|
/** 下拉校验覆盖的行数;只影响模板中下拉框的作用范围,不限制导入行数 */
|
||||||
|
private static final int DROPDOWN_ROWS = 5000;
|
||||||
|
|
||||||
|
private record Column(String header, String field,
|
||||||
|
BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final List<Column> COLUMNS = List.of(
|
||||||
|
new Column("正题名*", "title", VersionResource::setTitle, 512, "必填;示例行可覆盖或直接删除"),
|
||||||
|
new Column("加工编号", "processNo", VersionResource::setProcessNo, 128, "选填;系统中已存在则更新该条"),
|
||||||
|
new Column("责任者", "author", VersionResource::setAuthor, 512, "选填;多人用 ; 分隔"),
|
||||||
|
new Column("责任方式", "responsibility", VersionResource::setResponsibility, 256, "选填;如 著、编、译"),
|
||||||
|
new Column("中图分类", "clcCode", VersionResource::setClcCode, 64, "选填;如 G250.7"),
|
||||||
|
new Column("主题词", "keywords", VersionResource::setKeywords, 512, "选填;多个用 ; 分隔"),
|
||||||
|
new Column("摘要", "summary", VersionResource::setSummary, 2000, "选填;建议不少于 100 字"),
|
||||||
|
new Column("出版年份", "publishYear", VersionResource::setPublishYear, 8, "选填;格式 yyyy"),
|
||||||
|
new Column("出版者", "publisher", VersionResource::setPublisher, 256, "选填"),
|
||||||
|
new Column("出版地", "publishPlace", VersionResource::setPublishPlace, 128, "选填"),
|
||||||
|
new Column("出版日期", "publishDate", VersionResource::setPublishDate, 32, "选填;如 2026-01-01"),
|
||||||
|
new Column("版本版次", "edition", VersionResource::setEdition, 128, "选填"),
|
||||||
|
new Column("ISBN", "isbn", VersionResource::setIsbn, 64, "选填"),
|
||||||
|
new Column("内容形式", "contentForm", VersionResource::setContentForm, 64, "选填;如 文本"),
|
||||||
|
new Column("媒体类型", "mediaType", VersionResource::setMediaType, 32, "选填;纸质 或 电子"),
|
||||||
|
new Column("格式", "format", VersionResource::setFormat, 64, "选填;如 PDF"),
|
||||||
|
new Column("页码", "pageCount", VersionResource::setPageCount, 64, "选填"),
|
||||||
|
new Column("语种", "language", VersionResource::setLanguage, 16, "选填;三位代码,如 chi"),
|
||||||
|
new Column("来源馆", "sourceLibrary", VersionResource::setSourceLibrary, 256, "选填"),
|
||||||
|
new Column("数据提交单位", "submitOrg", VersionResource::setSubmitOrg, 256, "选填"),
|
||||||
|
new Column("任务年份", "taskYear", VersionResource::setTaskYear, 8, "选填;格式 yyyy"),
|
||||||
|
new Column("全文地址", "fulltextUrl", VersionResource::setFulltextUrl, 1024, "选填"),
|
||||||
|
new Column("是否特藏", "isSpecial", (r, v) -> { }, 4, "选填;是 或 否")
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模板自带的 5 条示例数据,列顺序与 {@link #COLUMNS} 严格一致。
|
||||||
|
* 正题名统一以「示例:」开头,导入时会被自动跳过。
|
||||||
|
*/
|
||||||
|
private static final String[][] SAMPLES = {
|
||||||
|
{"示例:军事理论教程", "EX-2026-0001", "张明", "著", "E0-43", "军事理论;教程",
|
||||||
|
"系统介绍军事理论的基本概念、发展脉络与研究方法,适用于院校教学参考。",
|
||||||
|
"2026", "军事科学出版社", "北京", "2026-03-01", "第2版", "978-7-80137-001-1",
|
||||||
|
"文本", "纸质", "PDF", "286", "chi", "陆军步兵学院图书馆", "陆军步兵学院",
|
||||||
|
"2026", "", "否"},
|
||||||
|
{"示例:版本资源元数据著录规范", "EX-2026-0002", "李华", "编", "G254.3", "元数据;著录",
|
||||||
|
"依据国家与军队相关标准,规范版本资源元数据的著录字段、格式与质量控制要求。",
|
||||||
|
"2025", "国防大学出版社", "北京", "2025-09-15", "第1版", "978-7-5626-002-2",
|
||||||
|
"文本", "电子", "PDF", "210", "chi", "南京某院校图书馆", "陆军步兵学院",
|
||||||
|
"2026", "http://cdio.example.org/fulltext/EX-2026-0002", "否"},
|
||||||
|
{"示例:中国古代兵书辑要", "EX-2026-0003", "王强", "整理", "E892", "兵书;古籍",
|
||||||
|
"收录先秦至明清重要兵书,附版本源流考述与校勘记,供版本比对研究使用。",
|
||||||
|
"2024", "中华书局", "北京", "2024-06-20", "影印本", "978-7-101-0033-3",
|
||||||
|
"文本", "纸质", "PDF", "520", "chi", "陆军勤务学院图书馆", "陆军勤务学院",
|
||||||
|
"2025", "", "是"},
|
||||||
|
{"示例:数字图书馆建设实践", "EX-2026-0004", "赵敏", "著", "G250.76", "数字图书馆;建设",
|
||||||
|
"围绕数字图书馆的资源组织、平台架构与服务模式展开,含多个建设案例分析。",
|
||||||
|
"2023", "国家图书馆出版社", "北京", "2023-11-10", "第1版", "978-7-5013-0044-4",
|
||||||
|
"文本", "电子", "EPUB", "340", "chi", "陆军指挥学院图书馆", "陆军指挥学院",
|
||||||
|
"2025", "", "否"},
|
||||||
|
{"示例:外军装备发展研究", "EX-2026-0005", "陈刚", "主编", "E92", "装备;外军",
|
||||||
|
"分析外军主战装备的发展路径、技术特点与体系构成,供装备论证参考。",
|
||||||
|
"2025", "国防工业出版社", "北京", "2025-05-08", "", "978-7-118-0055-5",
|
||||||
|
"文本", "纸质", "PDF", "415", "chi", "陆军航空兵学院图书馆", "陆军航空兵学院",
|
||||||
|
"2026", "", "否"}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ==================== 模板导出 ====================
|
||||||
|
|
||||||
|
public void writeTemplate(OutputStream out) throws IOException {
|
||||||
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
|
Sheet sheet = wb.createSheet("版本资源");
|
||||||
|
|
||||||
|
CellStyle headStyle = buildHeadStyle(wb);
|
||||||
|
CellStyle hintStyle = buildHintStyle(wb);
|
||||||
|
|
||||||
|
Row head = sheet.createRow(0);
|
||||||
|
Row hint = sheet.createRow(1);
|
||||||
|
head.setHeightInPoints(24);
|
||||||
|
hint.setHeightInPoints(18);
|
||||||
|
|
||||||
|
for (int i = 0; i < COLUMNS.size(); i++) {
|
||||||
|
Column col = COLUMNS.get(i);
|
||||||
|
|
||||||
|
Cell h = head.createCell(i);
|
||||||
|
h.setCellValue(col.header());
|
||||||
|
h.setCellStyle(headStyle);
|
||||||
|
|
||||||
|
Cell t = hint.createCell(i);
|
||||||
|
t.setCellValue(col.hint());
|
||||||
|
t.setCellStyle(hintStyle);
|
||||||
|
|
||||||
|
int width = Math.max(12, Math.min(46, displayWidth(col.header()) + 4));
|
||||||
|
if ("summary".equals(col.field()) || "fulltextUrl".equals(col.field())) {
|
||||||
|
width = 46;
|
||||||
|
}
|
||||||
|
sheet.setColumnWidth(i, width * 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
sheet.createFreezePane(0, 2);
|
||||||
|
|
||||||
|
// 5 条示例数据:供对照填写,导入时自动跳过
|
||||||
|
CellStyle sampleStyle = buildSampleStyle(wb);
|
||||||
|
for (int r = 0; r < SAMPLES.length; r++) {
|
||||||
|
Row row = sheet.createRow(2 + r);
|
||||||
|
row.setHeightInPoints(20);
|
||||||
|
for (int c = 0; c < SAMPLES[r].length && c < COLUMNS.size(); c++) {
|
||||||
|
Cell cell = row.createCell(c);
|
||||||
|
cell.setCellValue(SAMPLES[r][c]);
|
||||||
|
cell.setCellStyle(sampleStyle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 媒体类型、是否特藏加下拉,避免填错
|
||||||
|
addDropdown(sheet, indexOf("mediaType"), new String[]{"纸质", "电子"});
|
||||||
|
addDropdown(sheet, indexOf("isSpecial"), new String[]{"是", "否"});
|
||||||
|
|
||||||
|
wb.write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private CellStyle buildHeadStyle(Workbook wb) {
|
||||||
|
CellStyle style = wb.createCellStyle();
|
||||||
|
Font font = wb.createFont();
|
||||||
|
font.setBold(true);
|
||||||
|
font.setFontHeightInPoints((short) 11);
|
||||||
|
font.setColor(IndexedColors.WHITE.getIndex());
|
||||||
|
style.setFont(font);
|
||||||
|
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||||
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
|
style.setAlignment(HorizontalAlignment.CENTER);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
border(style);
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CellStyle buildHintStyle(Workbook wb) {
|
||||||
|
CellStyle style = wb.createCellStyle();
|
||||||
|
Font font = wb.createFont();
|
||||||
|
font.setFontHeightInPoints((short) 9);
|
||||||
|
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||||
|
style.setFont(font);
|
||||||
|
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
|
||||||
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
style.setWrapText(true);
|
||||||
|
border(style);
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CellStyle buildSampleStyle(Workbook wb) {
|
||||||
|
CellStyle style = wb.createCellStyle();
|
||||||
|
Font font = wb.createFont();
|
||||||
|
font.setFontHeightInPoints((short) 10);
|
||||||
|
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||||
|
style.setFont(font);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
border(style);
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void border(CellStyle style) {
|
||||||
|
style.setBorderTop(BorderStyle.THIN);
|
||||||
|
style.setBorderBottom(BorderStyle.THIN);
|
||||||
|
style.setBorderLeft(BorderStyle.THIN);
|
||||||
|
style.setBorderRight(BorderStyle.THIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int displayWidth(String text) {
|
||||||
|
int w = 0;
|
||||||
|
for (char c : text.toCharArray()) {
|
||||||
|
w += c > 127 ? 2 : 1;
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int indexOf(String field) {
|
||||||
|
for (int i = 0; i < COLUMNS.size(); i++) {
|
||||||
|
if (COLUMNS.get(i).field().equals(field)) return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addDropdown(Sheet sheet, int colIndex, String[] options) {
|
||||||
|
if (colIndex < 0) return;
|
||||||
|
DataValidationHelper helper = sheet.getDataValidationHelper();
|
||||||
|
DataValidationConstraint constraint =
|
||||||
|
helper.createExplicitListConstraint(options);
|
||||||
|
CellRangeAddressList range = new CellRangeAddressList(2, DROPDOWN_ROWS, colIndex, colIndex);
|
||||||
|
DataValidation validation = helper.createValidation(constraint, range);
|
||||||
|
validation.setSuppressDropDownArrow(true);
|
||||||
|
validation.setShowErrorBox(true);
|
||||||
|
sheet.addValidationData(validation);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 导入 ====================
|
||||||
|
|
||||||
|
public ImportResult importExcel(MultipartFile file) throws IOException {
|
||||||
|
ImportResult result = new ImportResult();
|
||||||
|
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
result.addError(0, "请选择要导入的 Excel 文件");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
|
||||||
|
Sheet sheet = wb.getSheetAt(0);
|
||||||
|
if (sheet == null || sheet.getLastRowNum() < 1) {
|
||||||
|
result.addError(0, "表格为空,请使用系统导出的模板填写数据");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) 表头 → 列号
|
||||||
|
Row headRow = sheet.getRow(0);
|
||||||
|
Map<String, Integer> colIndex = new HashMap<>();
|
||||||
|
for (Cell cell : headRow) {
|
||||||
|
String name = normalizeHeader(cellText(cell));
|
||||||
|
if (StrUtil.isNotBlank(name)) {
|
||||||
|
colIndex.put(name, cell.getColumnIndex());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!colIndex.containsKey("正题名")) {
|
||||||
|
result.addError(1, "表头缺少「正题名」列,请使用系统导出的模板");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 判断第 2 行是否为说明行
|
||||||
|
int startRow = 1;
|
||||||
|
Row second = sheet.getRow(1);
|
||||||
|
if (second != null) {
|
||||||
|
String first = cellText(second.getCell(0));
|
||||||
|
if (first != null && (first.startsWith("必填") || first.startsWith("选填"))) {
|
||||||
|
startRow = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) 逐行解析
|
||||||
|
List<VersionResource> parsed = new ArrayList<>();
|
||||||
|
List<Integer> rowNums = new ArrayList<>();
|
||||||
|
|
||||||
|
int last = sheet.getLastRowNum();
|
||||||
|
for (int r = startRow; r <= last; r++) {
|
||||||
|
Row row = sheet.getRow(r);
|
||||||
|
if (row == null) continue;
|
||||||
|
|
||||||
|
VersionResource res = new VersionResource();
|
||||||
|
boolean empty = true;
|
||||||
|
|
||||||
|
for (Column col : COLUMNS) {
|
||||||
|
Integer idx = colIndex.get(normalizeHeader(col.header()));
|
||||||
|
if (idx == null) continue;
|
||||||
|
String value = cellText(row.getCell(idx));
|
||||||
|
if (StrUtil.isBlank(value)) continue;
|
||||||
|
empty = false;
|
||||||
|
|
||||||
|
if ("isSpecial".equals(col.field())) {
|
||||||
|
res.setIsSpecial(parseBool(value) ? 1 : 0);
|
||||||
|
} else {
|
||||||
|
col.setter().accept(res, truncate(value.trim(), col.maxLen()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty) continue;
|
||||||
|
|
||||||
|
int excelRowNum = r + 1;
|
||||||
|
if (StrUtil.isBlank(res.getTitle())) {
|
||||||
|
result.addError(excelRowNum, "正题名不能为空");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模板自带的示例行:跳过,不参与导入
|
||||||
|
if (res.getTitle().startsWith("示例:") || res.getTitle().startsWith("示例:")) {
|
||||||
|
result.setSkipped(result.getSkipped() + 1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StrUtil.isBlank(res.getGovernStatus())) {
|
||||||
|
res.setGovernStatus("RAW");
|
||||||
|
}
|
||||||
|
if (res.getDeleted() == null) {
|
||||||
|
res.setDeleted(0);
|
||||||
|
}
|
||||||
|
if (res.getIsSpecial() == null) {
|
||||||
|
res.setIsSpecial(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed.add(res);
|
||||||
|
rowNums.add(excelRowNum);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.setTotal(parsed.size());
|
||||||
|
if (parsed.isEmpty()) {
|
||||||
|
if (result.getFailed() == 0) {
|
||||||
|
result.addError(0, result.getSkipped() > 0
|
||||||
|
? "仅读取到模板示例数据,请填写实际数据后再导入"
|
||||||
|
: "未读取到有效数据行,请从第 3 行开始填写");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) 按加工编号匹配已有记录
|
||||||
|
Map<String, Long> existing = findExisting(parsed);
|
||||||
|
|
||||||
|
List<VersionResource> inserts = new ArrayList<>();
|
||||||
|
List<VersionResource> updates = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int i = 0; i < parsed.size(); i++) {
|
||||||
|
VersionResource res = parsed.get(i);
|
||||||
|
Long existId = StrUtil.isBlank(res.getProcessNo())
|
||||||
|
? null : existing.get(res.getProcessNo().trim());
|
||||||
|
if (existId != null) {
|
||||||
|
res.setId(existId);
|
||||||
|
updates.add(res);
|
||||||
|
} else {
|
||||||
|
inserts.add(res);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5) 分批写库
|
||||||
|
if (!inserts.isEmpty()) {
|
||||||
|
versionResourceService.saveBatch(inserts, 500);
|
||||||
|
}
|
||||||
|
if (!updates.isEmpty()) {
|
||||||
|
versionResourceService.updateBatchById(updates, 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.setInserted(inserts.size());
|
||||||
|
result.setUpdated(updates.size());
|
||||||
|
return result;
|
||||||
|
} catch (Exception e) {
|
||||||
|
result.addError(0, "文件解析失败:" + e.getMessage());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一次性查出所有已存在的加工编号,避免逐行查库 */
|
||||||
|
private Map<String, Long> findExisting(List<VersionResource> list) {
|
||||||
|
List<String> nos = list.stream()
|
||||||
|
.map(VersionResource::getProcessNo)
|
||||||
|
.filter(StrUtil::isNotBlank)
|
||||||
|
.map(String::trim)
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
if (nos.isEmpty()) return Collections.emptyMap();
|
||||||
|
|
||||||
|
LambdaQueryWrapper<VersionResource> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.in(VersionResource::getProcessNo, nos);
|
||||||
|
return versionResourceService.list(wrapper).stream()
|
||||||
|
.filter(r -> StrUtil.isNotBlank(r.getProcessNo()))
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
r -> r.getProcessNo().trim(),
|
||||||
|
VersionResource::getId,
|
||||||
|
(a, b) -> a));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeHeader(String s) {
|
||||||
|
if (s == null) return "";
|
||||||
|
return s.replace("*", "")
|
||||||
|
.replace("*", "")
|
||||||
|
.replace(" ", "")
|
||||||
|
.replace(" ", "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String cellText(Cell cell) {
|
||||||
|
if (cell == null) return null;
|
||||||
|
CellType type = cell.getCellType();
|
||||||
|
if (type == CellType.FORMULA) {
|
||||||
|
type = cell.getCachedFormulaResultType();
|
||||||
|
}
|
||||||
|
switch (type) {
|
||||||
|
case STRING:
|
||||||
|
return cell.getStringCellValue();
|
||||||
|
case NUMERIC:
|
||||||
|
if (DateUtil.isCellDateFormatted(cell)) {
|
||||||
|
return cell.getLocalDateTimeCellValue().toLocalDate().toString();
|
||||||
|
}
|
||||||
|
double d = cell.getNumericCellValue();
|
||||||
|
if (d == Math.floor(d) && !Double.isInfinite(d)) {
|
||||||
|
return String.valueOf((long) d);
|
||||||
|
}
|
||||||
|
return String.valueOf(d);
|
||||||
|
case BOOLEAN:
|
||||||
|
return String.valueOf(cell.getBooleanCellValue());
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean parseBool(String v) {
|
||||||
|
String s = v.trim();
|
||||||
|
return "是".equals(s) || "1".equals(s) || "true".equalsIgnoreCase(s) || "y".equalsIgnoreCase(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String truncate(String v, int max) {
|
||||||
|
if (v == null) return null;
|
||||||
|
return v.length() > max ? v.substring(0, max) : v;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import com.banben.common.Result;
|
|||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
import com.banben.modules.search.dto.SearchQuery;
|
import com.banben.modules.search.dto.SearchQuery;
|
||||||
import com.banben.modules.search.service.SearchService;
|
import com.banben.modules.search.service.SearchService;
|
||||||
|
import com.banben.modules.search.vo.ClcNodeVO;
|
||||||
import com.banben.modules.search.vo.SearchResultVO;
|
import com.banben.modules.search.vo.SearchResultVO;
|
||||||
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;
|
||||||
@@ -73,6 +74,12 @@ public class SearchController {
|
|||||||
return Result.success(searchService.similar(id, limit));
|
return Result.success(searchService.similar(id, limit));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "中图法分类树(部类/大类/类目,带命中数量,供左侧导航逐级展开)")
|
||||||
|
@GetMapping("/clc/tree")
|
||||||
|
public Result<List<ClcNodeVO>> clcTree(SearchQuery query) {
|
||||||
|
return Result.success(searchService.clcTree(query));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "检索结果列表(用于导出/批量处理,最多 10000 条)")
|
@Operation(summary = "检索结果列表(用于导出/批量处理,最多 10000 条)")
|
||||||
@PostMapping("/list")
|
@PostMapping("/list")
|
||||||
public Result<List<VersionResource>> list(@RequestBody SearchQuery query) {
|
public Result<List<VersionResource>> list(@RequestBody SearchQuery query) {
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ public class SearchQuery {
|
|||||||
@Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)")
|
@Schema(description = "综合关键词(题名/作者/关键词/摘要/出版者 模糊匹配)")
|
||||||
private String keyword;
|
private String keyword;
|
||||||
|
|
||||||
|
@Schema(description = "去除关键字(结果集排除,空格分隔可多个;含任一排除词的记录不返回)")
|
||||||
|
private String excludeKeyword;
|
||||||
|
|
||||||
@Schema(description = "题名")
|
@Schema(description = "题名")
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@@ -42,13 +45,28 @@ public class SearchQuery {
|
|||||||
@Schema(description = "中图分类号(前方一致)")
|
@Schema(description = "中图分类号(前方一致)")
|
||||||
private String clcCode;
|
private String clcCode;
|
||||||
|
|
||||||
|
@Schema(description = "中图分类号(多个,前方一致,任一命中即可;用于「中图法」树导航点选部类/大类)")
|
||||||
|
private List<String> clcCodes;
|
||||||
|
|
||||||
/** ---------------- 多类型/多来源 ---------------- */
|
/** ---------------- 多类型/多来源 ---------------- */
|
||||||
@Schema(description = "媒体类型:纸质/电子")
|
@Schema(description = "媒体类型:纸质/电子")
|
||||||
private String mediaType;
|
private String mediaType;
|
||||||
|
|
||||||
|
@Schema(description = "媒体类型(多选,in):纸质/电子")
|
||||||
|
private List<String> mediaTypes;
|
||||||
|
|
||||||
|
@Schema(description = "语种分组:chi 中文文献 / foreign 外文文献(首页前置筛选用)")
|
||||||
|
private String languageGroup;
|
||||||
|
|
||||||
@Schema(description = "来源馆(多选)")
|
@Schema(description = "来源馆(多选)")
|
||||||
private List<String> sourceLibraries;
|
private List<String> sourceLibraries;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆(单选,左侧「来源院校」分面点选用)")
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
|
@Schema(description = "来源资源库名(多选,in)")
|
||||||
|
private List<String> sourceRepos;
|
||||||
|
|
||||||
/** ---------------- 限定出版时段 ---------------- */
|
/** ---------------- 限定出版时段 ---------------- */
|
||||||
@Schema(description = "出版年份起(含)", example = "2000")
|
@Schema(description = "出版年份起(含)", example = "2000")
|
||||||
private String publishYearStart;
|
private String publishYearStart;
|
||||||
@@ -60,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";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.banben.modules.search.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 中图法分类字典(clc_category)。
|
||||||
|
*
|
||||||
|
* <p>层级:1 五大部类 / 2 二十二个基本大类 / 3 二级类目;
|
||||||
|
* 统一检索页左侧「中图法」分面导航使用 level=2 的大类节点。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("clc_category")
|
||||||
|
public class ClcCategory {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** 父级ID,顶级为 0 */
|
||||||
|
private Long parentId;
|
||||||
|
|
||||||
|
/** 中图法分类号(如 A / E / TB / E8) */
|
||||||
|
private String clcCode;
|
||||||
|
|
||||||
|
/** 分类名称 */
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** 层级(1-7) */
|
||||||
|
private Integer level;
|
||||||
|
|
||||||
|
/** 同级排序号 */
|
||||||
|
private Integer sortOrder;
|
||||||
|
|
||||||
|
/** 全路径(部类名/大类名/类目名) */
|
||||||
|
private String fullPath;
|
||||||
|
|
||||||
|
/** 是否最末级(0否 1是) */
|
||||||
|
private Integer isLeaf;
|
||||||
|
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
/** 逻辑删除标识 */
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.banben.modules.search.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.search.entity.ClcCategory;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/** 中图法分类字典 Mapper */
|
||||||
|
@Mapper
|
||||||
|
public interface ClcCategoryMapper extends BaseMapper<ClcCategory> {
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.banben.modules.search.service;
|
|||||||
|
|
||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
import com.banben.modules.search.dto.SearchQuery;
|
import com.banben.modules.search.dto.SearchQuery;
|
||||||
|
import com.banben.modules.search.vo.ClcNodeVO;
|
||||||
import com.banben.modules.search.vo.SearchResultVO;
|
import com.banben.modules.search.vo.SearchResultVO;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -35,4 +36,10 @@ public interface SearchService {
|
|||||||
* 导出检索结果(上限 {@code limit} 条)。
|
* 导出检索结果(上限 {@code limit} 条)。
|
||||||
*/
|
*/
|
||||||
List<VersionResource> exportList(SearchQuery query, int limit);
|
List<VersionResource> exportList(SearchQuery query, int limit);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 中图法分类树(部类 -> 大类 -> 类目),带当前检索条件下的命中数量,
|
||||||
|
* 供检索页左侧导航逐级展开后点选检索。
|
||||||
|
*/
|
||||||
|
List<ClcNodeVO> clcTree(SearchQuery query);
|
||||||
}
|
}
|
||||||
|
|||||||
+399
-12
@@ -5,12 +5,19 @@ import cn.hutool.core.util.StrUtil;
|
|||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
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.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.SearchLog;
|
import com.banben.modules.search.entity.SearchLog;
|
||||||
|
import com.banben.modules.search.mapper.ClcCategoryMapper;
|
||||||
import com.banben.modules.search.mapper.SearchLogMapper;
|
import com.banben.modules.search.mapper.SearchLogMapper;
|
||||||
import com.banben.modules.search.service.SearchService;
|
import com.banben.modules.search.service.SearchService;
|
||||||
|
import com.banben.modules.search.vo.ClcNodeVO;
|
||||||
import com.banben.modules.search.vo.FacetItem;
|
import com.banben.modules.search.vo.FacetItem;
|
||||||
import com.banben.modules.search.vo.SearchResultVO;
|
import com.banben.modules.search.vo.SearchResultVO;
|
||||||
import com.banben.modules.search.vo.YearStat;
|
import com.banben.modules.search.vo.YearStat;
|
||||||
@@ -21,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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检索发现服务实现。
|
* 检索发现服务实现。
|
||||||
@@ -40,12 +50,29 @@ 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 SensitiveWordMapper sensitiveWordMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SearchResultVO search(SearchQuery query, String userIp) {
|
public SearchResultVO search(SearchQuery query, String userIp) {
|
||||||
long start = System.currentTimeMillis();
|
long start = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// 敏感词拦截:检索词命中敏感词库时直接屏蔽结果(facets 一并置空)
|
||||||
|
if (hitsSensitive(query)) {
|
||||||
|
SearchResultVO vo = new SearchResultVO();
|
||||||
|
vo.setPage(PageResult.of(List.of(), 0, query.getCurrent(), query.getSize()));
|
||||||
|
vo.setMediaTypeFacets(List.of());
|
||||||
|
vo.setSourceLibraryFacets(List.of());
|
||||||
|
vo.setClcFacets(List.of());
|
||||||
|
vo.setYearStats(List.of());
|
||||||
|
vo.setSensitiveBlocked(true);
|
||||||
|
vo.setCostMs(System.currentTimeMillis() - start);
|
||||||
|
saveSearchLog(query, userIp, 0, vo.getCostMs().intValue());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
|
QueryWrapper<VersionResource> wrapper = buildWrapper(query);
|
||||||
applyOrder(wrapper, query);
|
applyOrder(wrapper, query);
|
||||||
|
|
||||||
@@ -53,10 +80,27 @@ 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()));
|
||||||
|
|
||||||
|
// 命中但被屏蔽/下架而不展示的记录数(含管理状态口径的总数 - 实际可见总数)。
|
||||||
|
// 仅在带检索条件时统计:空词全量浏览(刷新/首页进入)不提示
|
||||||
|
if (hasCondition(query)) {
|
||||||
|
try {
|
||||||
|
long withMasked = resourceMapper.selectCount(
|
||||||
|
buildWrapper(query, false, null, true));
|
||||||
|
if (withMasked > page.getTotal()) {
|
||||||
|
vo.setMaskedCount(withMasked - page.getTotal());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计被屏蔽命中数失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
vo.setMediaTypeFacets(facet(query, "media_type"));
|
vo.setMediaTypeFacets(facet(query, "media_type"));
|
||||||
vo.setSourceLibraryFacets(facet(query, "source_library"));
|
vo.setSourceLibraryFacets(facet(query, "source_library"));
|
||||||
vo.setClcFacets(facet(query, "clc_code"));
|
vo.setSourceRepoFacets(facet(query, "source_repo"));
|
||||||
|
vo.setClcFacets(clcFacet(query));
|
||||||
vo.setYearStats(yearStats(query));
|
vo.setYearStats(yearStats(query));
|
||||||
|
|
||||||
long cost = System.currentTimeMillis() - start;
|
long cost = System.currentTimeMillis() - start;
|
||||||
@@ -74,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
|
||||||
@@ -105,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
|
||||||
@@ -113,19 +163,119 @@ 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== 内部方法 ====================
|
// ==================== 内部方法 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 敏感词拦截:检索词(综合/题名/责任者/出版者/ISBN/CDOI 任一途径)命中敏感词库即屏蔽。
|
||||||
|
*
|
||||||
|
* <p>敏感词表不存在或查询异常时不拦截(降级为正常检索),避免影响可用性。</p>
|
||||||
|
*/
|
||||||
|
private boolean hitsSensitive(SearchQuery q) {
|
||||||
|
String text = StrUtil.nullToEmpty(q.getKeyword()) + "\n"
|
||||||
|
+ StrUtil.nullToEmpty(q.getTitle()) + "\n"
|
||||||
|
+ StrUtil.nullToEmpty(q.getAuthor()) + "\n"
|
||||||
|
+ StrUtil.nullToEmpty(q.getPublisher()) + "\n"
|
||||||
|
+ StrUtil.nullToEmpty(q.getIsbn()) + "\n"
|
||||||
|
+ StrUtil.nullToEmpty(q.getCdoi());
|
||||||
|
if (text.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
for (SensitiveWord sw : sensitiveWordMapper.selectList(null)) {
|
||||||
|
String word = sw.getWord();
|
||||||
|
if (StrUtil.isNotBlank(word) && text.contains(word)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("敏感词检查失败,本次不拦截:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否带有任意检索/筛选条件(区别于空词全量浏览)。
|
||||||
|
*/
|
||||||
|
private boolean hasCondition(SearchQuery q) {
|
||||||
|
return StrUtil.isNotBlank(q.getKeyword()) || StrUtil.isNotBlank(q.getTitle())
|
||||||
|
|| StrUtil.isNotBlank(q.getAuthor()) || StrUtil.isNotBlank(q.getPublisher())
|
||||||
|
|| StrUtil.isNotBlank(q.getIsbn()) || StrUtil.isNotBlank(q.getCdoi())
|
||||||
|
|| StrUtil.isNotBlank(q.getClcCode()) || CollectionUtil.isNotEmpty(q.getClcCodes())
|
||||||
|
|| StrUtil.isNotBlank(q.getMediaType()) || CollectionUtil.isNotEmpty(q.getMediaTypes())
|
||||||
|
|| StrUtil.isNotBlank(q.getLanguageGroup())
|
||||||
|
|| StrUtil.isNotBlank(q.getSourceLibrary()) || CollectionUtil.isNotEmpty(q.getSourceLibraries())
|
||||||
|
|| CollectionUtil.isNotEmpty(q.getSourceRepos())
|
||||||
|
|| StrUtil.isNotBlank(q.getWithinKeyword())
|
||||||
|
|| StrUtil.isNotBlank(q.getPublishYearStart()) || StrUtil.isNotBlank(q.getPublishYearEnd());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构造查询条件(多途径 / 多类型 / 多来源 / 多精度 / 限定出版时段)。
|
* 构造查询条件(多途径 / 多类型 / 多来源 / 多精度 / 限定出版时段)。
|
||||||
*/
|
*/
|
||||||
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) {
|
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q) {
|
||||||
|
return buildWrapper(q, false, null, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q, boolean excludeClc) {
|
||||||
|
return buildWrapper(q, excludeClc, null, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private QueryWrapper<VersionResource> buildWrapper(SearchQuery q, boolean excludeClc,
|
||||||
|
String excludeColumn, boolean includeMasked) {
|
||||||
QueryWrapper<VersionResource> w = new QueryWrapper<>();
|
QueryWrapper<VersionResource> w = new QueryWrapper<>();
|
||||||
w.eq("deleted", 0);
|
w.eq("deleted", 0);
|
||||||
// 后台处置过的记录不进检索(元数据与索引屏蔽/下架):0正常 1屏蔽 2下架
|
// 后台处置过的记录不进检索(元数据与索引屏蔽/下架):0正常 1屏蔽 2下架
|
||||||
w.and(x -> x.isNull("manage_status").or().eq("manage_status", 0));
|
// includeMasked=true 时忽略该过滤,用于统计「命中但被隐藏」的记录数
|
||||||
|
if (!includeMasked) {
|
||||||
|
w.and(x -> x.isNull("manage_status").or().eq("manage_status", 0));
|
||||||
|
}
|
||||||
|
|
||||||
// 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者
|
// 综合关键词:题名 / 责任者 / 关键词 / 摘要 / 出版者
|
||||||
// 多词检索:空格分词,词与词之间 OR(命中任一词即返回)
|
// 多词检索:空格分词,词与词之间 OR(命中任一词即返回)
|
||||||
@@ -144,20 +294,80 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 去除关键字:排除含任一排除词的记录(与综合关键词覆盖同样的文本字段)
|
||||||
|
// 字段为空(IS NULL)不计入排除,避免把缺字段的记录误删
|
||||||
|
if (StrUtil.isNotBlank(q.getExcludeKeyword())) {
|
||||||
|
List<String> exTerms = splitTerms(q.getExcludeKeyword());
|
||||||
|
for (String ex : exTerms) {
|
||||||
|
w.and(x -> x
|
||||||
|
.and(y -> y.notLike("title", ex).or().isNull("title"))
|
||||||
|
.and(y -> y.notLike("author", ex).or().isNull("author"))
|
||||||
|
.and(y -> y.notLike("keywords", ex).or().isNull("keywords"))
|
||||||
|
.and(y -> y.notLike("summary", ex).or().isNull("summary"))
|
||||||
|
.and(y -> y.notLike("publisher", ex).or().isNull("publisher"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 在结果中搜索:每个新增关键词都必须命中(AND 收窄当前结果集)
|
||||||
|
if (StrUtil.isNotBlank(q.getWithinKeyword())) {
|
||||||
|
for (String kw : splitTerms(q.getWithinKeyword())) {
|
||||||
|
w.and(x -> x.nested(y -> y.like("title", kw).or().like("author", kw).or()
|
||||||
|
.like("keywords", kw).or().like("summary", kw).or().like("publisher", kw)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
applyMatch(w, "title", q.getTitle(), q.getMatchType());
|
applyMatch(w, "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());
|
||||||
applyMatch(w, "isbn", q.getIsbn(), q.getMatchType());
|
applyMatch(w, "isbn", q.getIsbn(), q.getMatchType());
|
||||||
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
|
applyMatch(w, "cdoi", q.getCdoi(), q.getMatchType());
|
||||||
|
|
||||||
if (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 (StrUtil.isNotBlank(q.getMediaType())) {
|
// 中图法树导航:点部类时传入其下所有大类号,任一命中即可
|
||||||
w.eq("media_type", q.getMediaType());
|
if (!excludeClc && CollectionUtil.isNotEmpty(q.getClcCodes())) {
|
||||||
|
w.and(x -> {
|
||||||
|
boolean first = true;
|
||||||
|
for (String c : q.getClcCodes()) {
|
||||||
|
if (StrUtil.isBlank(c)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!first) {
|
||||||
|
x.or();
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
x.likeRight("clc_code", c.trim().toUpperCase());
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
|
// 资源类型:单选或罗列多选(分面排除时跳过本列过滤,便于切换)
|
||||||
w.in("source_library", q.getSourceLibraries());
|
if (!"media_type".equals(excludeColumn)) {
|
||||||
|
if (CollectionUtil.isNotEmpty(q.getMediaTypes())) {
|
||||||
|
w.in("media_type", q.getMediaTypes());
|
||||||
|
} else if (StrUtil.isNotBlank(q.getMediaType())) {
|
||||||
|
w.eq("media_type", q.getMediaType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 语种分组:中文文献含 chi/zh/中文(库内有少量中文写法的脏数据);
|
||||||
|
// 外文文献 = 不在中文集合内(NULL 语种视为未知,两侧都不计入外文组)
|
||||||
|
if ("chi".equalsIgnoreCase(q.getLanguageGroup())) {
|
||||||
|
w.in("language", List.of("chi", "zh", "中文"));
|
||||||
|
} else if ("foreign".equalsIgnoreCase(q.getLanguageGroup())) {
|
||||||
|
w.notIn("language", List.of("chi", "zh", "中文"));
|
||||||
|
}
|
||||||
|
// 来源院校:多选(IN)或单选(分面排除时跳过本列过滤)
|
||||||
|
if (!"source_library".equals(excludeColumn)) {
|
||||||
|
if (CollectionUtil.isNotEmpty(q.getSourceLibraries())) {
|
||||||
|
w.in("source_library", q.getSourceLibraries());
|
||||||
|
} else if (StrUtil.isNotBlank(q.getSourceLibrary())) {
|
||||||
|
w.eq("source_library", q.getSourceLibrary().trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 资源库名:多选(IN)
|
||||||
|
if (CollectionUtil.isNotEmpty(q.getSourceRepos()) && !"source_repo".equals(excludeColumn)) {
|
||||||
|
w.in("source_repo", q.getSourceRepos());
|
||||||
}
|
}
|
||||||
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
|
if (StrUtil.isNotBlank(q.getPublishYearStart())) {
|
||||||
w.ge("publish_year", q.getPublishYearStart().trim());
|
w.ge("publish_year", q.getPublishYearStart().trim());
|
||||||
@@ -240,7 +450,9 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
* @param column 参与分组的列(media_type / source_library / clc_code)
|
* @param column 参与分组的列(media_type / source_library / clc_code)
|
||||||
*/
|
*/
|
||||||
private List<FacetItem> facet(SearchQuery query, String column) {
|
private List<FacetItem> facet(SearchQuery query, String column) {
|
||||||
QueryWrapper<VersionResource> w = buildWrapper(query);
|
// 统计该列分面时排除列自身的过滤条件:选中「电子」后,
|
||||||
|
// 「资源类型」分组里纸质等其它选项仍应显示数量、可点击切换
|
||||||
|
QueryWrapper<VersionResource> w = buildWrapper(query, false, column, false);
|
||||||
w.select(column + " AS name", "COUNT(*) AS cnt")
|
w.select(column + " AS name", "COUNT(*) AS cnt")
|
||||||
.isNotNull(column)
|
.isNotNull(column)
|
||||||
.ne(column, "")
|
.ne(column, "")
|
||||||
@@ -260,6 +472,181 @@ public class SearchServiceImpl implements SearchService {
|
|||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 中图法分面:按分类号首字母聚合到 {@code clc_category} 的二十二个基本大类。
|
||||||
|
*
|
||||||
|
* <p>统计口径为「分类号前方一致」:E8、E9 都计入大类 E(军事),
|
||||||
|
* 再用 clc_category 的 level=2 节点把字母翻译成类名。
|
||||||
|
* 统计时忽略条件里已选的大类(excludeClc),保证导航间可切换。</p>
|
||||||
|
*/
|
||||||
|
private List<FacetItem> clcFacet(SearchQuery query) {
|
||||||
|
QueryWrapper<VersionResource> w = buildWrapper(query, true);
|
||||||
|
w.select("UPPER(SUBSTRING(clc_code, 1, 1)) AS name", "COUNT(*) AS cnt")
|
||||||
|
.isNotNull("clc_code")
|
||||||
|
.ne("clc_code", "")
|
||||||
|
.groupBy("UPPER(SUBSTRING(clc_code, 1, 1))")
|
||||||
|
.orderByDesc("cnt");
|
||||||
|
|
||||||
|
List<Map<String, Object>> maps = resourceMapper.selectMaps(w);
|
||||||
|
Map<String, String> names = clcTopClassNames();
|
||||||
|
List<FacetItem> items = new ArrayList<>();
|
||||||
|
for (Map<String, Object> m : maps) {
|
||||||
|
Object name = m.get("name");
|
||||||
|
if (name == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String code = String.valueOf(name);
|
||||||
|
items.add(new FacetItem(names.getOrDefault(code, code), toLong(m.get("cnt")), code));
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 中图法分类树:部类 -> 大类 -> 类目,逐级列出并带命中数量。
|
||||||
|
*
|
||||||
|
* <p>实现要点:
|
||||||
|
* <ol>
|
||||||
|
* <li>一次取出 {@code clc_category} 全部节点(deleted=0),按层级组装成树;</li>
|
||||||
|
* <li>一次按 {@code clc_code} 分组统计当前检索条件下的命中数(忽略已选分类,
|
||||||
|
* 保证切换到别的分支时数量依然可见);</li>
|
||||||
|
* <li>资源的分类号通常比三级类目更细(如 E83、TN97、G250.7),
|
||||||
|
* 按「最长前缀」归并到最具体的类目节点,再自底向上累加到父节点。</li>
|
||||||
|
* </ol>
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public List<ClcNodeVO> clcTree(SearchQuery query) {
|
||||||
|
List<ClcCategory> all = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
all = clcCategoryMapper.selectList(new QueryWrapper<ClcCategory>()
|
||||||
|
.eq("deleted", 0)
|
||||||
|
.orderByAsc("level", "sort_order", "id"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("读取中图法分类失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 命中数量:先落到最具体的类目节点上,再由子节点向上累加
|
||||||
|
Map<Long, Long> countByNodeId = new java.util.HashMap<>();
|
||||||
|
List<ClcCategory> byLevel = new ArrayList<>(all);
|
||||||
|
for (Map<String, Object> m : clcCodeCounts(query)) {
|
||||||
|
String resCode = String.valueOf(m.get("name"));
|
||||||
|
long cnt = toLong(m.get("cnt"));
|
||||||
|
if (StrUtil.isBlank(resCode)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ClcCategory node = matchDeepest(byLevel, resCode.trim().toUpperCase());
|
||||||
|
if (node != null) {
|
||||||
|
countByNodeId.merge(node.getId(), cnt, Long::sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildTree(all, countByNodeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前检索条件下的分类号分组统计(忽略条件里已选的中图分类) */
|
||||||
|
private List<Map<String, Object>> clcCodeCounts(SearchQuery query) {
|
||||||
|
QueryWrapper<VersionResource> w = buildWrapper(query, true);
|
||||||
|
w.select("clc_code AS name", "COUNT(*) AS cnt")
|
||||||
|
.isNotNull("clc_code")
|
||||||
|
.ne("clc_code", "")
|
||||||
|
.groupBy("clc_code");
|
||||||
|
try {
|
||||||
|
return resourceMapper.selectMaps(w);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计中图法命中数量失败:{}", e.getMessage());
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 找与资源分类号最匹配的类目:类目号是其前缀时命中,取最长的那个(类目越细越具体)。
|
||||||
|
* 区间号(D33-37 这类含短横线的)不参与前缀匹配。
|
||||||
|
*
|
||||||
|
* <p>level=1 的部类编号(1~5)是字典表的分组号、不是真实分类号,
|
||||||
|
* 若参与前缀匹配,会把 clc_code 恰好以数字开头的脏数据(如 11)误算进部类计数,
|
||||||
|
* 导致「树上有数量、点进去检索却是 0 条」——部类计数只能由子节点累加而来。</p>
|
||||||
|
*/
|
||||||
|
private ClcCategory matchDeepest(List<ClcCategory> nodes, String resCode) {
|
||||||
|
ClcCategory best = null;
|
||||||
|
for (ClcCategory n : nodes) {
|
||||||
|
String code = n.getClcCode();
|
||||||
|
if (StrUtil.isBlank(code) || code.contains("-") || code.contains("/")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n.getLevel() == null || n.getLevel() <= 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!resCode.startsWith(code.toUpperCase())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (best == null || code.length() > best.getClcCode().length()) {
|
||||||
|
best = n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 组装树并自底向上累加命中数量 */
|
||||||
|
private List<ClcNodeVO> buildTree(List<ClcCategory> all, Map<Long, Long> countByNodeId) {
|
||||||
|
Map<Long, List<ClcCategory>> childrenByParent = new java.util.HashMap<>();
|
||||||
|
for (ClcCategory c : all) {
|
||||||
|
childrenByParent.computeIfAbsent(c.getParentId() == null ? 0L : c.getParentId(), k -> new ArrayList<>()).add(c);
|
||||||
|
}
|
||||||
|
// 按层级从深到浅累加:子节点数量汇总到父节点
|
||||||
|
Map<Long, Long> total = new java.util.HashMap<>(countByNodeId);
|
||||||
|
for (int lv = 7; lv >= 2; lv--) {
|
||||||
|
int cur = lv;
|
||||||
|
for (ClcCategory c : all) {
|
||||||
|
if (c.getLevel() == null || c.getLevel() != cur) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
long self = total.getOrDefault(c.getId(), 0L);
|
||||||
|
if (self == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Long pid = c.getParentId() == null ? 0L : c.getParentId();
|
||||||
|
total.merge(pid, self, Long::sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ClcCategory> roots = childrenByParent.getOrDefault(0L, List.of());
|
||||||
|
List<ClcNodeVO> tree = new ArrayList<>();
|
||||||
|
for (ClcCategory r : roots) {
|
||||||
|
tree.add(toNode(r, childrenByParent, total));
|
||||||
|
}
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClcNodeVO toNode(ClcCategory c, Map<Long, List<ClcCategory>> childrenByParent, Map<Long, Long> total) {
|
||||||
|
ClcNodeVO vo = new ClcNodeVO();
|
||||||
|
vo.setCode(c.getClcCode());
|
||||||
|
vo.setName(c.getName());
|
||||||
|
vo.setLevel(c.getLevel());
|
||||||
|
vo.setCount(total.getOrDefault(c.getId(), 0L));
|
||||||
|
for (ClcCategory child : childrenByParent.getOrDefault(c.getId(), List.of())) {
|
||||||
|
vo.getChildren().add(toNode(child, childrenByParent, total));
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 中图法二十二个基本大类:分类号 -> 类名(查不到字典表时返回空映射,前端退化为显示字母) */
|
||||||
|
private Map<String, String> clcTopClassNames() {
|
||||||
|
try {
|
||||||
|
List<ClcCategory> list = clcCategoryMapper.selectList(
|
||||||
|
new QueryWrapper<ClcCategory>().eq("deleted", 0).eq("level", 2));
|
||||||
|
Map<String, String> map = new java.util.HashMap<>();
|
||||||
|
for (ClcCategory c : list) {
|
||||||
|
map.put(c.getClcCode(), c.getName());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("读取中图法大类失败:{}", e.getMessage());
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 命中文献各年份发文量。
|
* 命中文献各年份发文量。
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.banben.modules.search.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 中图法分类树节点(左侧逐级展开的导航)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "中图法分类树节点")
|
||||||
|
public class ClcNodeVO {
|
||||||
|
|
||||||
|
@Schema(description = "分类号,如 3 / E / E8")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
@Schema(description = "分类名称")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Schema(description = "层级:1部类 2大类 3类目")
|
||||||
|
private Integer level;
|
||||||
|
|
||||||
|
@Schema(description = "当前检索条件下的命中数量(含下级)")
|
||||||
|
private Long count;
|
||||||
|
|
||||||
|
@Schema(description = "下级节点")
|
||||||
|
private List<ClcNodeVO> children = new ArrayList<>();
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.banben.modules.search.vo;
|
package com.banben.modules.search.vo;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
@@ -10,7 +9,6 @@ import lombok.NoArgsConstructor;
|
|||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(description = "分面项")
|
@Schema(description = "分面项")
|
||||||
public class FacetItem {
|
public class FacetItem {
|
||||||
|
|
||||||
@@ -19,4 +17,18 @@ public class FacetItem {
|
|||||||
|
|
||||||
@Schema(description = "命中数量")
|
@Schema(description = "命中数量")
|
||||||
private Long value;
|
private Long value;
|
||||||
|
|
||||||
|
@Schema(description = "筛选值(中图法分面为分类号前缀,如 E;其余分面为空)")
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
public FacetItem(String name, Long value) {
|
||||||
|
this.name = name;
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FacetItem(String name, Long value, String code) {
|
||||||
|
this.name = name;
|
||||||
|
this.value = value;
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ public class SearchResultVO {
|
|||||||
@Schema(description = "来源院校分面")
|
@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;
|
||||||
|
|
||||||
@@ -33,4 +36,10 @@ public class SearchResultVO {
|
|||||||
|
|
||||||
@Schema(description = "检索耗时(ms)")
|
@Schema(description = "检索耗时(ms)")
|
||||||
private Long costMs;
|
private Long costMs;
|
||||||
|
|
||||||
|
@Schema(description = "检索词命中敏感词库,结果已被屏蔽")
|
||||||
|
private Boolean sensitiveBlocked;
|
||||||
|
|
||||||
|
@Schema(description = "命中但被屏蔽/下架而不展示的记录数")
|
||||||
|
private Long maskedCount;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.banben.modules.special.controller;
|
package com.banben.modules.special.controller;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
import com.banben.common.Result;
|
import com.banben.common.Result;
|
||||||
import com.banben.modules.special.dto.SpecialRecommendVO;
|
import com.banben.modules.special.dto.SpecialRecommendVO;
|
||||||
import com.banben.modules.special.entity.SpecialResource;
|
import com.banben.modules.special.entity.SpecialResource;
|
||||||
@@ -31,6 +32,14 @@ public class SpecialController {
|
|||||||
return Result.success(specialService.recommend(limit));
|
return Result.success(specialService.recommend(limit));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "特藏推荐分页列表")
|
||||||
|
@GetMapping("/recommend/page")
|
||||||
|
public Result<PageResult<SpecialRecommendVO>> recommendPage(
|
||||||
|
@RequestParam(defaultValue = "1") long current,
|
||||||
|
@RequestParam(defaultValue = "10") long size) {
|
||||||
|
return Result.success(specialService.recommendPage(current, size));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "特藏细览")
|
@Operation(summary = "特藏细览")
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public Result<SpecialResource> detail(@PathVariable Long id) {
|
public Result<SpecialResource> detail(@PathVariable Long id) {
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ public class SpecialRecommendVO implements Serializable {
|
|||||||
@Schema(description = "下载/电子版地址(special_resource.ebook_url,version_resource 场景取全文地址)")
|
@Schema(description = "下载/电子版地址(special_resource.ebook_url,version_resource 场景取全文地址)")
|
||||||
private String ebookUrl;
|
private String ebookUrl;
|
||||||
|
|
||||||
|
@Schema(description = "来源馆(version_resource.source_library)")
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
@Schema(description = "数据来源:VERSION=version_resource特藏标记 / MANUAL=special_resource手工维护")
|
@Schema(description = "数据来源:VERSION=version_resource特藏标记 / MANUAL=special_resource手工维护")
|
||||||
private String source;
|
private String source;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ public class SpecialResource implements Serializable {
|
|||||||
@Schema(description = "电子版下载地址")
|
@Schema(description = "电子版下载地址")
|
||||||
private String ebookUrl;
|
private String ebookUrl;
|
||||||
|
|
||||||
|
@TableField("source_library")
|
||||||
|
@Schema(description = "来源馆,对应 special_resource.source_library")
|
||||||
|
private String sourceLibrary;
|
||||||
|
|
||||||
@Schema(description = "排序号")
|
@Schema(description = "排序号")
|
||||||
private Integer sortNo;
|
private Integer sortNo;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.banben.modules.special.service;
|
package com.banben.modules.special.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.banben.common.PageResult;
|
||||||
import com.banben.modules.special.dto.SpecialRecommendVO;
|
import com.banben.modules.special.dto.SpecialRecommendVO;
|
||||||
import com.banben.modules.special.entity.SpecialResource;
|
import com.banben.modules.special.entity.SpecialResource;
|
||||||
|
|
||||||
@@ -16,6 +17,12 @@ public interface SpecialService extends IService<SpecialResource> {
|
|||||||
*/
|
*/
|
||||||
List<SpecialRecommendVO> recommend(int limit);
|
List<SpecialRecommendVO> recommend(int limit);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 特藏推荐分页:先 version_resource(is_special=1,update_time 倒序),
|
||||||
|
* 后 special_resource(status=1,sort_no 正序),跨两段按同一顺序分页。
|
||||||
|
*/
|
||||||
|
PageResult<SpecialRecommendVO> recommendPage(long current, long size);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理端列表(special_resource 手工维护数据)。
|
* 管理端列表(special_resource 手工维护数据)。
|
||||||
*/
|
*/
|
||||||
|
|||||||
+89
-29
@@ -2,6 +2,7 @@ package com.banben.modules.special.service.impl;
|
|||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.banben.common.PageResult;
|
||||||
import com.banben.modules.resource.entity.VersionResource;
|
import com.banben.modules.resource.entity.VersionResource;
|
||||||
import com.banben.modules.resource.mapper.VersionResourceMapper;
|
import com.banben.modules.resource.mapper.VersionResourceMapper;
|
||||||
import com.banben.modules.special.dto.SpecialRecommendVO;
|
import com.banben.modules.special.dto.SpecialRecommendVO;
|
||||||
@@ -47,19 +48,7 @@ public class SpecialServiceImpl extends ServiceImpl<SpecialResourceMapper, Speci
|
|||||||
.orderByDesc(VersionResource::getUpdateTime)
|
.orderByDesc(VersionResource::getUpdateTime)
|
||||||
.last("limit " + size);
|
.last("limit " + size);
|
||||||
|
|
||||||
versionResourceMapper.selectList(wrapper).forEach(r -> {
|
versionResourceMapper.selectList(wrapper).forEach(r -> result.add(toVersionVO(r)));
|
||||||
SpecialRecommendVO vo = new SpecialRecommendVO();
|
|
||||||
vo.setId(r.getId());
|
|
||||||
vo.setTitle(r.getTitle());
|
|
||||||
vo.setNote(r.getNote());
|
|
||||||
vo.setAuthor(r.getAuthor());
|
|
||||||
vo.setPublishYear(r.getPublishYear());
|
|
||||||
vo.setFulltextUrl(r.getFulltextUrl());
|
|
||||||
// version_resource 无封面与电子版字段,下载地址用全文地址兜底
|
|
||||||
vo.setEbookUrl(r.getFulltextUrl());
|
|
||||||
vo.setSource("VERSION");
|
|
||||||
result.add(vo);
|
|
||||||
});
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// is_special 字段未迁移时查询会失败,此处降级为只展示手工维护的特藏
|
// is_special 字段未迁移时查询会失败,此处降级为只展示手工维护的特藏
|
||||||
log.warn("查询 version_resource 特藏记录失败,仅展示 special_resource:{}", e.getMessage());
|
log.warn("查询 version_resource 特藏记录失败,仅展示 special_resource:{}", e.getMessage());
|
||||||
@@ -68,27 +57,98 @@ public class SpecialServiceImpl extends ServiceImpl<SpecialResourceMapper, Speci
|
|||||||
// 2) special_resource 手工维护的特藏(补齐剩余条数)
|
// 2) special_resource 手工维护的特藏(补齐剩余条数)
|
||||||
int remain = size - result.size();
|
int remain = size - result.size();
|
||||||
if (remain > 0) {
|
if (remain > 0) {
|
||||||
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
|
result.addAll(listManual(0, remain));
|
||||||
wrapper.eq(SpecialResource::getStatus, 1)
|
|
||||||
.orderByAsc(SpecialResource::getSortNo)
|
|
||||||
.orderByDesc(SpecialResource::getCreateTime)
|
|
||||||
.last("limit " + remain);
|
|
||||||
|
|
||||||
this.list(wrapper).forEach(s -> {
|
|
||||||
SpecialRecommendVO vo = new SpecialRecommendVO();
|
|
||||||
vo.setId(s.getId());
|
|
||||||
vo.setTitle(s.getName());
|
|
||||||
vo.setNote(s.getSummary());
|
|
||||||
vo.setCoverUrl(s.getCoverUrl());
|
|
||||||
vo.setEbookUrl(s.getEbookUrl());
|
|
||||||
vo.setSource("MANUAL");
|
|
||||||
result.add(vo);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<SpecialRecommendVO> recommendPage(long current, long size) {
|
||||||
|
long pageNo = Math.max(1, current);
|
||||||
|
long pageSize = Math.max(1, size);
|
||||||
|
long offset = (pageNo - 1) * pageSize;
|
||||||
|
|
||||||
|
// 各段总数(version_resource 段查询失败时按 0 处理,降级为纯手工特藏)
|
||||||
|
long countA = 0;
|
||||||
|
try {
|
||||||
|
countA = versionResourceMapper.selectCount(
|
||||||
|
new LambdaQueryWrapper<VersionResource>().eq(VersionResource::getIsSpecial, 1));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计 version_resource 特藏记录失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
long countB = this.count(new LambdaQueryWrapper<SpecialResource>()
|
||||||
|
.eq(SpecialResource::getStatus, 1));
|
||||||
|
long total = countA + countB;
|
||||||
|
|
||||||
|
List<SpecialRecommendVO> records = new ArrayList<>();
|
||||||
|
long remain = pageSize;
|
||||||
|
if (offset < countA) {
|
||||||
|
// 当前页从 version_resource 段开始,取完不够再从 special_resource 段补
|
||||||
|
long takeA = Math.min(remain, countA - offset);
|
||||||
|
try {
|
||||||
|
LambdaQueryWrapper<VersionResource> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(VersionResource::getIsSpecial, 1)
|
||||||
|
.orderByDesc(VersionResource::getUpdateTime)
|
||||||
|
.last("limit " + takeA + " offset " + offset);
|
||||||
|
versionResourceMapper.selectList(wrapper).forEach(r -> records.add(toVersionVO(r)));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("查询 version_resource 特藏分页失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
remain -= records.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remain > 0) {
|
||||||
|
// 页首已越过 version_resource 段时,需跳过 (offset - countA) 条手工特藏
|
||||||
|
long skipB = Math.max(0, offset - countA);
|
||||||
|
records.addAll(listManual(skipB, remain));
|
||||||
|
}
|
||||||
|
|
||||||
|
return PageResult.of(records, total, pageNo, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询手工特藏(special_resource):跳过 skip 条、取 n 条,sort_no 正序。
|
||||||
|
*/
|
||||||
|
private List<SpecialRecommendVO> listManual(long skip, long n) {
|
||||||
|
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(SpecialResource::getStatus, 1)
|
||||||
|
.orderByAsc(SpecialResource::getSortNo)
|
||||||
|
.orderByDesc(SpecialResource::getCreateTime)
|
||||||
|
.last("limit " + n + " offset " + skip);
|
||||||
|
|
||||||
|
List<SpecialRecommendVO> result = new ArrayList<>();
|
||||||
|
this.list(wrapper).forEach(s -> result.add(toManualVO(s)));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SpecialRecommendVO toVersionVO(VersionResource r) {
|
||||||
|
SpecialRecommendVO vo = new SpecialRecommendVO();
|
||||||
|
vo.setId(r.getId());
|
||||||
|
vo.setTitle(r.getTitle());
|
||||||
|
vo.setNote(r.getNote());
|
||||||
|
vo.setAuthor(r.getAuthor());
|
||||||
|
vo.setPublishYear(r.getPublishYear());
|
||||||
|
vo.setSourceLibrary(r.getSourceLibrary());
|
||||||
|
vo.setFulltextUrl(r.getFulltextUrl());
|
||||||
|
// version_resource 无封面与电子版字段,下载地址用全文地址兜底
|
||||||
|
vo.setEbookUrl(r.getFulltextUrl());
|
||||||
|
vo.setSource("VERSION");
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SpecialRecommendVO toManualVO(SpecialResource s) {
|
||||||
|
SpecialRecommendVO vo = new SpecialRecommendVO();
|
||||||
|
vo.setId(s.getId());
|
||||||
|
vo.setTitle(s.getName());
|
||||||
|
vo.setNote(s.getSummary());
|
||||||
|
vo.setCoverUrl(s.getCoverUrl());
|
||||||
|
vo.setEbookUrl(s.getEbookUrl());
|
||||||
|
vo.setSourceLibrary(s.getSourceLibrary());
|
||||||
|
vo.setSource("MANUAL");
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<SpecialResource> adminList() {
|
public List<SpecialResource> adminList() {
|
||||||
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<SpecialResource> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user