初始化

This commit is contained in:
Weiming committed 2026-09-11 13:54:37 +08:00
commit 0a83dfb7be
186 files changed
+16214

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
target/
.idea/
*.iml
out/
*.class
*.log
.env
application-local.yml
application-local.yaml
application-local.properties
logs/
uploads/
tmp/
.DS_Store
Thumbs.db
+6
View File
@@ -0,0 +1,6 @@
# Backend deployment notes
Before saving any `secret=true` value in `sys_integration_config`, configure
`APP_INTEGRATION_ENCRYPTION_KEY` (preferably a randomly generated 32-byte or
longer secret) in the backend runtime environment. Do not commit the key or
place a real value in `src/main/resources/application.yml`.
+173
View File
@@ -0,0 +1,173 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.finance.system</groupId>
<artifactId>finance-system</artifactId>
<version>1.0.0</version>
<name>finance-system</name>
<description>统一费用支付平台 - 员工报销管理系统</description>
<properties>
<java.version>8</java.version>
<jjwt.version>0.11.5</jjwt.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<springdoc.version>1.6.15</springdoc.version>
<lombok.version>1.18.30</lombok.version>
</properties>
<dependencies>
<!-- Spring Boot Starters -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Database -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<!-- MapStruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>
<!-- OpenAPI / Swagger -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
+21
View File
@@ -0,0 +1,21 @@
@echo off
set JAVA_HOME=C:\PROGRA~1\Java\OPENJD~1
set MAVEN_HOME=C:\Users\it\.m2
set PROJECT_DIR=D:\code\Java\financial_system\finance-system\backend
cd /d "%PROJECT_DIR%"
REM Find the classworlds jar
set CLASSWORLDS_JAR=
for %%i in ("%MAVEN_HOME%\boot\plexus-classworlds-*.jar") do set CLASSWORLDS_JAR=%%i
REM Run Maven directly
"%JAVA_HOME%\bin\java.exe" ^
-classpath "%CLASSWORLDS_JAR%" ^
"-Dclassworlds.conf=%MAVEN_HOME%\bin\m2.conf" ^
"-Dmaven.home=%MAVEN_HOME%" ^
"-Dmaven.multiModuleProjectDirectory=%PROJECT_DIR%" ^
"-Dspring-boot.run.profiles=local" ^
"-Dmaven.test.skip=true" ^
org.codehaus.plexus.classworlds.launcher.Launcher ^
spring-boot:run
@@ -0,0 +1,14 @@
package com.finance.system;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties
public class FinanceSystemApplication {
public static void main(String[] args) {
SpringApplication.run(FinanceSystemApplication.class, args);
}
}
@@ -0,0 +1,82 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.ReimApplication;
import com.finance.system.entity.ReimExpenseItem;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysDepartment;
import com.finance.system.entity.SysExpenseType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 飞书审批表单构建器
* 将系统报销数据转换为飞书审批实例的表单数据
*/
public class FeishuApprovalFormBuilder {
/**
* 构建审批表单数据
*/
public static Map<String, String> buildForm(ReimApplication app, SysUser applicant,
SysDepartment department, SysExpenseType expenseType,
List<ReimExpenseItem> items) {
Map<String, String> form = new HashMap<>();
// 基本字段
form.put("application_no", app.getApplicationNo());
form.put("title", app.getTitle());
form.put("applicant_name", applicant != null ? applicant.getRealName() : "");
form.put("department", department != null ? department.getDeptName() : "");
form.put("expense_type", expenseType != null ? expenseType.getTypeName() : "");
form.put("total_amount", app.getTotalAmount() != null ? app.getTotalAmount().toString() : "0");
form.put("description", app.getDescription() != null ? app.getDescription() : "");
form.put("source_doc_no", app.getSourceDocNo() != null ? app.getSourceDocNo() : "");
// 费用明细(多行文本展示)
if (items != null && !items.isEmpty()) {
String itemDetail = items.stream()
.map(item -> String.format("%s | %s | ¥%.2f",
item.getExpenseDate() != null ? item.getExpenseDate().toString() : "",
item.getDescription() != null ? item.getDescription() : "",
item.getAmount() != null ? item.getAmount() : BigDecimal.ZERO))
.collect(Collectors.joining("\n"));
form.put("expense_items", itemDetail);
}
return form;
}
/**
* 构建飞书审批表单(用于创建审批实例的API请求)
*/
public static String buildFormJson(Map<String, String> formData) {
StringBuilder json = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, String> entry : formData.entrySet()) {
if (!first) {
json.append(",");
}
json.append("\"")
.append(escapeJson(entry.getKey()))
.append("\":\"")
.append(escapeJson(entry.getValue() != null ? entry.getValue() : ""))
.append("\"");
first = false;
}
json.append("}");
return json.toString();
}
private static String escapeJson(String value) {
if (value == null) return "";
return value.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
}
}
@@ -0,0 +1,129 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* 飞书审批API响应DTO
*/
@Data
@NoArgsConstructor
public class FeishuApprovalResponse {
private int code;
private String msg;
private Data data;
@lombok.Data
@NoArgsConstructor
public static class Data {
/** 审批实例编码 */
@JsonProperty("instance_code")
private String instanceCode;
/** 审批定义编码 */
@JsonProperty("approval_code")
private String approvalCode;
/** 审批状态 PENDING/APPROVED/REJECTED/CANCELED/TERMINATED */
private String status;
/** 审批实例链接 */
private String url;
/** 审批节点列表 */
@JsonProperty("node_list")
private List<ApprovalNode> nodeList;
/** 审批时间线 */
private List<TimelineNode> timeline;
/** 审批定义名称 */
@JsonProperty("approval_name")
private String approvalName;
/** 审批表单 */
private Object form;
}
/**
* 审批节点定义
*/
@lombok.Data
@NoArgsConstructor
public static class ApprovalNode {
private String id;
private String name;
/** AND/OR */
private String type;
/** 审批人列表 */
private List<Approver> approver;
/** 超时时间(分钟) */
private int timeout;
/** 节点层级 */
private int level;
}
/**
* 审批人
*/
@lombok.Data
@NoArgsConstructor
public static class Approver {
/** user/role/free */
private String type;
/** 用户ID或角色ID */
@JsonProperty("user_id")
private String userId;
/** 角色ID */
@JsonProperty("role_id")
private String roleId;
/** 角色名称 */
@JsonProperty("role_name")
private String roleName;
/** 用户姓名 */
private String name;
}
/**
* 审批时间线节点(审批进度)
*/
@lombok.Data
@NoArgsConstructor
public static class TimelineNode {
/** approval/cc/comment */
private String type;
/** 节点名称 */
@JsonProperty("node_name")
private String nodeName;
/** 审批状态 */
private String status;
/** 审批人姓名 */
private String approver;
/** 审批人头像 */
@JsonProperty("approver_avatar")
private String approverAvatar;
/** 审批意见 */
private String comment;
/** 审批时间 */
@JsonProperty("action_time")
private String actionTime;
}
}
@@ -0,0 +1,449 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.*;
import com.finance.system.enums.ApplicationStatus;
import com.finance.system.enums.ApprovalStatus;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.*;
import com.finance.system.service.IntegrationConfigReader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
/**
* 飞书审批服务
* 负责:创建审批实例、查询审批定义(节点信息)、同步审批结果
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class FeishuApprovalService {
private final FeishuConfig feishuConfig;
private final FeishuAuthService feishuAuthService;
private final SysUserRepository sysUserRepository;
private final SysDepartmentRepository sysDepartmentRepository;
private final SysExpenseTypeRepository sysExpenseTypeRepository;
private final ReimExpenseItemRepository reimExpenseItemRepository;
private final IntFeishuApprovalRepository intFeishuApprovalRepository;
private final ReimApplicationRepository reimApplicationRepository;
private final RestTemplate restTemplate;
private IntegrationConfigReader integrationConfigReader;
@Autowired(required = false)
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
this.integrationConfigReader = integrationConfigReader;
}
private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis";
/**
* Whether submission should be delegated to Feishu rather than the local
* approval-node workflow. A missing approval definition is not a usable
* integration even when the app credentials are present.
*/
public boolean isApprovalEnabledAndConfigured() {
String appId = configValue("appId", feishuConfig.getAppId());
String appSecret = configValue("appSecret", feishuConfig.getAppSecret());
String code = approvalCode();
boolean configured = StringUtils.hasText(appId)
&& StringUtils.hasText(appSecret)
&& StringUtils.hasText(code);
return configured && (integrationConfigReader == null || integrationConfigReader.isEnabled("FEISHU"));
}
// ==================== 1. 获取审批定义(审批节点信息) ====================
/**
* 获取飞书审批定义详情
* 包括审批流程的所有节点、审批人配置、表单定义
*/
public FeishuApprovalResponse getApprovalDefinition() {
String token = feishuAuthService.getTenantAccessToken();
String url = FEISHU_OPEN_API + "/approval/openapi/v2/approval/get";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("approval_code", approvalCode());
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
url, HttpMethod.POST, request, FeishuApprovalResponse.class);
FeishuApprovalResponse resp = response.getBody();
if (resp != null && resp.getCode() != 0) {
throw new BusinessException("获取飞书审批定义失败: " + resp.getMsg());
}
return resp;
} catch (Exception e) {
log.error("获取飞书审批定义失败", e);
throw new BusinessException("获取审批节点信息失败,请检查飞书权限配置");
}
}
/**
* 获取审批节点列表(用于前端展示审批流程)
*/
public List<FeishuApprovalResponse.ApprovalNode> getApprovalNodes() {
FeishuApprovalResponse response = getApprovalDefinition();
if (response != null && response.getData() != null) {
return response.getData().getNodeList();
}
return Collections.emptyList();
}
// ==================== 2. 创建审批实例 ====================
/**
* 创建飞书审批实例
*
* @param application 报销申请
* @return 飞书审批实例编码
*/
@Transactional
public String createApprovalInstance(ReimApplication application) {
if (application == null || application.getId() == null) {
throw new BusinessException("报销申请不存在,无法创建飞书审批", 400);
}
Optional<IntFeishuApproval> existing = intFeishuApprovalRepository
.findByApplicationId(application.getId());
IntFeishuApproval reusableRecord = existing.orElse(null);
if (existing.isPresent()) {
String existingStatus = normalizeApprovalStatus(existing.get().getStatus());
if (!isRetryableTerminal(existingStatus) && StringUtils.hasText(existing.get().getFeishuInstanceCode())) {
log.info("飞书审批实例已存在,跳过重复创建: applicationNo={}, instanceCode={}",
application.getApplicationNo(), existing.get().getFeishuInstanceCode());
return existing.get().getFeishuInstanceCode();
}
if (!isRetryableTerminal(existingStatus)) {
throw new BusinessException("该申请已有未完成的飞书同步记录,请稍后重试");
}
}
if (application.getApplicantId() == null) {
throw new BusinessException("申请人不存在,无法创建飞书审批", 400);
}
SysUser applicant = sysUserRepository.findById(application.getApplicantId())
.orElseThrow(() -> new BusinessException("申请人不存在,无法创建飞书审批", 400));
if (!StringUtils.hasText(applicant.getFeishuUserId())
&& !StringUtils.hasText(applicant.getFeishuOpenId())) {
throw new BusinessException("申请人未绑定飞书用户身份,无法创建飞书审批", 400);
}
String token = feishuAuthService.getTenantAccessToken();
String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/create";
// 获取关联数据
SysDepartment department = application.getDepartmentId() != null
? sysDepartmentRepository.findById(application.getDepartmentId()).orElse(null) : null;
SysExpenseType expenseType = application.getExpenseTypeId() != null
? sysExpenseTypeRepository.findById(application.getExpenseTypeId()).orElse(null) : null;
List<ReimExpenseItem> items = reimExpenseItemRepository.findByApplicationId(application.getId());
// 构建表单数据
Map<String, String> formData = FeishuApprovalFormBuilder.buildForm(
application, applicant, department, expenseType, items);
String formJson = FeishuApprovalFormBuilder.buildFormJson(formData);
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("approval_code", approvalCode());
requestBody.put("user_id", applicant != null ? applicant.getFeishuUserId() : "");
requestBody.put("open_id", applicant != null ? applicant.getFeishuOpenId() : "");
requestBody.put("form", formJson);
String requestId = createRequestId(application, reusableRecord);
requestBody.put("uuid", requestId);
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-Request-ID", requestId);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
url, HttpMethod.POST, request, FeishuApprovalResponse.class);
FeishuApprovalResponse resp = response.getBody();
if (resp != null && resp.getCode() != 0) {
throw new BusinessException("创建飞书审批实例失败: " + resp.getMsg());
}
if (resp == null || resp.getData() == null
|| !StringUtils.hasText(resp.getData().getInstanceCode())) {
throw new BusinessException("飞书未返回审批实例编码");
}
String instanceCode = resp.getData().getInstanceCode();
// 保存审批同步记录
IntFeishuApproval syncRecord = reusableRecord == null ? new IntFeishuApproval() : reusableRecord;
syncRecord.setApplicationId(application.getId());
syncRecord.setFeishuInstanceCode(instanceCode);
syncRecord.setFeishuApprovalCode(approvalCode());
syncRecord.setStatus("PENDING");
syncRecord.setCallbackData(null);
syncRecord.setSyncedAt(null);
syncRecord.setCreatedAt(LocalDateTime.now());
intFeishuApprovalRepository.save(syncRecord);
log.info("飞书审批实例创建成功: applicationNo={}, instanceCode={}",
application.getApplicationNo(), instanceCode);
return instanceCode;
} catch (BusinessException e) {
log.error("创建飞书审批失败: applicationNo={}, status={}",
application.getApplicationNo(), e.getStatusCode(), e);
throw e;
} catch (Exception e) {
log.error("创建飞书审批实例失败: applicationNo={}", application.getApplicationNo(), e);
throw new BusinessException("创建飞书审批失败,请稍后重试");
}
}
// ==================== 3. 查询审批实例详情(含进度) ====================
/**
* 获取审批实例详情
* 包含审批进度、各节点状态、审批意见
*/
public FeishuApprovalResponse getApprovalInstanceDetail(String instanceCode) {
String token = feishuAuthService.getTenantAccessToken();
String url = FEISHU_OPEN_API + "/approval/openapi/v2/instance/get";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("instance_code", instanceCode);
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<FeishuApprovalResponse> response = restTemplate.exchange(
url, HttpMethod.POST, request, FeishuApprovalResponse.class);
FeishuApprovalResponse resp = response.getBody();
if (resp != null && resp.getCode() != 0) {
throw new BusinessException("获取审批实例详情失败: " + resp.getMsg());
}
return resp;
} catch (Exception e) {
log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e);
throw new BusinessException("获取审批进度失败");
}
}
/**
* 获取审批时间线(各节点审批进度)
*/
public List<FeishuApprovalResponse.TimelineNode> getApprovalTimeline(String instanceCode) {
FeishuApprovalResponse detail = getApprovalInstanceDetail(instanceCode);
if (detail != null && detail.getData() != null) {
return detail.getData().getTimeline();
}
return Collections.emptyList();
}
// ==================== 4. 同步审批结果 ====================
/**
* 同步审批结果到系统
* 由Webhook回调触发,或定时任务调用
*
* @param instanceCode 飞书审批实例编码
* @param status 审批状态
* @param comment 审批意见
*/
@Transactional
public void syncApprovalResult(String instanceCode, String status, String comment) {
IntFeishuApproval syncRecord = intFeishuApprovalRepository
.findByFeishuInstanceCodeForUpdate(instanceCode)
.orElseThrow(() -> new BusinessException("未找到对应的审批同步记录"));
String normalizedStatus = normalizeApprovalStatus(status);
if (normalizedStatus == null) {
log.warn("忽略未知飞书审批状态: instanceCode={}, status={}", instanceCode, status);
return;
}
// Terminal records are monotonic. This prevents a delayed PENDING
// callback from reopening an already approved/rejected application.
String previousStatus = normalizeApprovalStatus(syncRecord.getStatus());
if (isTerminal(previousStatus)) {
log.info("忽略终态后的旧飞书审批事件: instanceCode={}, oldStatus={}, status={}",
instanceCode, previousStatus, normalizedStatus);
return;
}
ReimApplication application = reimApplicationRepository.findById(syncRecord.getApplicationId())
.orElseThrow(() -> new BusinessException("未找到对应的报销申请"));
// 更新同步记录
syncRecord.setStatus(normalizedStatus);
syncRecord.setSyncedAt(LocalDateTime.now());
intFeishuApprovalRepository.save(syncRecord);
application.setApprovalStatus(normalizedStatus);
if (ApprovalStatus.PENDING.name().equals(normalizedStatus)) {
application.setApplicationStatus(ApplicationStatus.SUBMITTED.name());
application.setCurrentApprovalNode("飞书审批");
application.setCurrentApproverId(null);
application.setApproveTime(null);
} else {
application.setCurrentApproverId(null);
application.setCurrentApprovalNode(null);
if (ApprovalStatus.APPROVED.name().equals(normalizedStatus)) {
application.setApplicationStatus(ApplicationStatus.SUBMITTED.name());
application.setApproveTime(LocalDateTime.now());
} else {
// Rejected/cancelled applications follow the existing local
// returned-draft behavior and can be corrected and resubmitted.
application.setApplicationStatus(ApplicationStatus.DRAFT.name());
application.setApproveTime(null);
}
}
reimApplicationRepository.save(application);
log.info("飞书审批同步成功: instanceCode={}, status={}, comment={}",
instanceCode, normalizedStatus, comment);
}
/**
* 根据报销单ID查询审批进度
*/
public List<FeishuApprovalResponse.TimelineNode> getApprovalTimelineByApplication(Long applicationId) {
IntFeishuApproval syncRecord = intFeishuApprovalRepository
.findByApplicationId(applicationId)
.orElse(null);
if (syncRecord == null || syncRecord.getFeishuInstanceCode() == null) {
return Collections.emptyList();
}
return getApprovalTimeline(syncRecord.getFeishuInstanceCode());
}
// ==================== 5. Webhook 处理 ====================
/**
* 处理飞书审批事件回调
*
* 支持的事件类型:
* - approval_instance: 审批实例状态变更
* - approval_task: 审批任务变更
*/
@Transactional
public void handleApprovalEvent(Map<String, Object> eventData) {
String eventType = (String) eventData.get("event_type");
if (eventType == null) {
log.warn("飞书事件回调缺少event_type");
return;
}
switch (eventType) {
case "approval_instance":
handleInstanceStatusChange(eventData);
break;
case "approval_task":
handleTaskChange(eventData);
break;
default:
log.info("未处理的事件类型: {}", eventType);
}
}
/**
* 处理审批实例状态变更事件
*/
private void handleInstanceStatusChange(Map<String, Object> eventData) {
Map<String, Object> instance = nestedMap(eventData.get("instance"));
// Feishu v2 approval_instance events put instance_code/status directly
// under event. FeishuAuthController flattens that event map, while
// older payloads still use the nested instance object.
if (instance == null && eventData.containsKey("instance_code")) {
instance = eventData;
}
if (instance == null) return;
String instanceCode = (String) instance.get("instance_code");
String status = (String) instance.get("status");
String comment = (String) instance.get("comment");
if (instanceCode != null && status != null) {
syncApprovalResult(instanceCode, status, comment);
}
}
/**
* 处理审批任务变更事件
*/
private void handleTaskChange(Map<String, Object> eventData) {
@SuppressWarnings("unchecked")
Map<String, Object> task = (Map<String, Object>) eventData.get("task");
if (task == null) return;
String instanceCode = (String) task.get("instance_code");
log.info("审批任务变更: instanceCode={}", instanceCode);
}
private String approvalCode() {
String fallback = feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getApprovalCode();
return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", "approvalCode");
}
private String configValue(String key, String fallback) {
if (integrationConfigReader == null) return fallback;
String value = integrationConfigReader.get("FEISHU", key);
return StringUtils.hasText(value) ? value : fallback;
}
private String createRequestId(ReimApplication application, IntFeishuApproval reusableRecord) {
String seed = "finance-system:feishu:approval:" + application.getId();
if (reusableRecord != null && isRetryableTerminal(normalizeApprovalStatus(reusableRecord.getStatus()))) {
String originalInstance = StringUtils.hasText(reusableRecord.getFeishuInstanceCode())
? reusableRecord.getFeishuInstanceCode() : "none";
seed += ":retry:" + originalInstance;
}
return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString();
}
@SuppressWarnings("unchecked")
private Map<String, Object> nestedMap(Object value) {
return value instanceof Map ? (Map<String, Object>) value : null;
}
private String normalizeApprovalStatus(String status) {
if (!StringUtils.hasText(status)) return null;
String normalized = status.trim().toUpperCase(Locale.ROOT);
if ("CANCELED".equals(normalized)) normalized = ApprovalStatus.CANCELLED.name();
for (ApprovalStatus known : ApprovalStatus.values()) {
if (known.name().equals(normalized)) return normalized;
}
return null;
}
private boolean isTerminal(String status) {
return ApprovalStatus.APPROVED.name().equals(status)
|| ApprovalStatus.REJECTED.name().equals(status)
|| ApprovalStatus.CANCELLED.name().equals(status);
}
private boolean isRetryableTerminal(String status) {
return ApprovalStatus.REJECTED.name().equals(status)
|| ApprovalStatus.CANCELLED.name().equals(status);
}
}
@@ -0,0 +1,355 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysOauthState;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysOauthStateRepository;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.service.IntegrationConfigReader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Base64;
@Slf4j
@Service
@RequiredArgsConstructor
public class FeishuAuthService {
private final FeishuConfig feishuConfig;
private final SysUserRepository sysUserRepository;
private final SysOauthStateRepository sysOauthStateRepository;
private final RestTemplate restTemplate;
private IntegrationConfigReader integrationConfigReader;
@Autowired
private FeishuTenantTokenService tenantTokens;
@Autowired
private FeishuLoginPersistenceService loginPersistence;
@Autowired(required = false)
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
this.integrationConfigReader = integrationConfigReader;
}
private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis";
private static final String FEISHU_AUTH_URL = "https://open.feishu.cn/open-apis/authen/v1/authorize";
private static final long OAUTH_STATE_TTL_MILLIS = 5 * 60 * 1000L;
private final SecureRandom secureRandom = new SecureRandom();
/**
* 构建飞书授权URL
*/
@Transactional
public AuthUrl buildAuthUrlWithState() {
requireConfigured();
long now = System.currentTimeMillis();
// Cleanup is deliberately limited to expired rows. There is no fixed
// capacity or random eviction, so one unauthenticated caller cannot
// invalidate another browser's state.
sysOauthStateRepository.deleteExpired(now);
byte[] randomState = new byte[32];
secureRandom.nextBytes(randomState);
String state = Base64.getUrlEncoder().withoutPadding().encodeToString(randomState);
long expiresAt = now + OAUTH_STATE_TTL_MILLIS;
sysOauthStateRepository.save(new SysOauthState(state, expiresAt));
String authUrl = FEISHU_AUTH_URL
+ "?app_id=" + encode(appId())
+ "&redirect_uri=" + encode(redirectUri())
+ "&response_type=code"
+ "&state=" + state;
return new AuthUrl(authUrl, state);
}
/** Builds the URL while retaining the original service method contract. */
@Transactional
public String buildAuthUrl() {
return buildAuthUrlWithState().getAuthUrl();
}
@Transactional
public void validateCallbackState(String state) {
validateCallbackState(state, null, false);
}
/**
* Validate the one-time state against the shared database. The callback
* only checks state existence; the code exchange consumes it so the
* authorization code and state are both single-use.
*/
@Transactional
public void validateCallbackState(String state, String browserState, boolean consume) {
if (!StringUtils.hasText(state)) {
throw new BusinessException("飞书登录状态缺失,请重新发起授权", 400);
}
if (consume && (!StringUtils.hasText(browserState)
|| !java.security.MessageDigest.isEqual(
state.getBytes(StandardCharsets.UTF_8), browserState.getBytes(StandardCharsets.UTF_8)))) {
throw new BusinessException("飞书登录状态与当前浏览器不匹配,请重新发起授权", 400);
}
long now = System.currentTimeMillis();
if (consume) {
if (sysOauthStateRepository.consumeIfValid(state, now) != 1) {
throw new BusinessException("飞书登录状态无效或已过期", 400);
}
} else if (!sysOauthStateRepository.findByStateAndExpiresAtGreaterThan(state, now).isPresent()) {
throw new BusinessException("飞书登录状态无效或已过期", 400);
}
}
private void requireConfigured() {
if (integrationConfigReader != null && !integrationConfigReader.isEnabled("FEISHU")) {
throw new BusinessException("飞书集成未启用,请先完成配置");
}
if (!StringUtils.hasText(appId()) || !StringUtils.hasText(appSecret())) {
throw new BusinessException("飞书登录未配置,请在后端运行配置中设置 FEISHU_APP_ID 和 FEISHU_APP_SECRET");
}
}
private String encode(String value) {
try { return URLEncoder.encode(value == null ? "" : value, "UTF-8"); }
catch (Exception e) { return ""; }
}
/** Validates the token supplied by Feishu, or its documented SHA-256 signature. */
public boolean isWebhookAuthorized(Map<String, Object> body, String signature,
String timestamp, String nonce, String rawBody) {
String configuredToken = verificationToken();
Object requestToken = body == null ? null : body.get("token");
if (configuredToken != null && !configuredToken.trim().isEmpty()
&& configuredToken.equals(requestToken)) return true;
if (signature == null || signature.trim().isEmpty()
|| !StringUtils.hasText(encryptKey())) return false;
try {
String signed = (timestamp == null ? "" : timestamp) + (nonce == null ? "" : nonce)
+ encryptKey() + (rawBody == null ? "" : rawBody);
byte[] digest = java.security.MessageDigest.getInstance("SHA-256")
.digest(signed.getBytes(StandardCharsets.UTF_8));
StringBuilder hex = new StringBuilder();
for (byte b : digest) hex.append(String.format("%02x", b & 0xff));
return secureEquals(hex.toString(), signature);
} catch (Exception e) {
return false;
}
}
private boolean secureEquals(String expected, String actual) {
return java.security.MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
actual.getBytes(StandardCharsets.UTF_8));
}
/**
* 通过授权码获取access_token
*/
public FeishuTokenResponse getAccessToken(String code) {
requireConfigured();
String url = FEISHU_OPEN_API + "/authen/v1/access_token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestBody = new java.util.HashMap<>();
requestBody.put("grant_type", "authorization_code");
requestBody.put("code", code);
requestBody.put("app_id", appId());
requestBody.put("app_secret", appSecret());
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<FeishuTokenResponse> response = restTemplate.postForEntity(
url, request, FeishuTokenResponse.class);
FeishuTokenResponse tokenResponse = response.getBody();
if (tokenResponse == null) throw new BusinessException("飞书授权未返回令牌");
if (tokenResponse.getCode() != 0) throw new BusinessException("飞书授权失败: " + tokenResponse.getMsg());
if (tokenResponse.getData() == null || !StringUtils.hasText(tokenResponse.getData().getAccessToken()))
throw new BusinessException("飞书授权未返回有效令牌");
return tokenResponse;
} catch (Exception e) {
log.error("飞书获取access_token失败", e);
throw new BusinessException("飞书授权失败,请稍后重试");
}
}
/**
* 获取用户信息
*/
public FeishuUserInfo getUserInfo(String accessToken) {
String url = FEISHU_OPEN_API + "/authen/v1/user_info";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
HttpEntity<Void> request = new HttpEntity<>(headers);
try {
ResponseEntity<FeishuUserResponse> response = restTemplate.exchange(
url, HttpMethod.GET, request, FeishuUserResponse.class);
FeishuUserResponse userResponse = response.getBody();
if (userResponse != null && userResponse.getCode() != 0) {
throw new BusinessException("获取飞书用户信息失败: " + userResponse.getMsg());
}
FeishuUserInfo userInfo = new FeishuUserInfo();
userInfo.setOpenId(userResponse.getData().getOpenId());
userInfo.setUserId(userResponse.getData().getUserId());
userInfo.setName(userResponse.getData().getName());
userInfo.setAvatarUrl(userResponse.getData().getAvatarUrl());
userInfo.setEmail(userResponse.getData().getEmail());
userInfo.setMobile(userResponse.getData().getMobile());
return userInfo;
} catch (Exception e) {
log.error("获取飞书用户信息失败", e);
throw new BusinessException("获取用户信息失败");
}
}
/**
* 获取tenant_access_token
*/
public String getTenantAccessToken() {
return tenantTokens.getTenantAccessToken();
}
/**
* Resolve the local account from the exact Feishu open_id and finalize the
* identity/profile binding. Directory synchronization is operational data,
* not an OAuth login admission check.
*/
public SysUser findOrCreateUser(FeishuUserInfo feishuUserInfo) {
if (feishuUserInfo == null || !StringUtils.hasText(feishuUserInfo.getOpenId())) {
throw invalidFeishuIdentity();
}
String openId = feishuUserInfo.getOpenId().trim();
String userId = StringUtils.hasText(feishuUserInfo.getUserId())
? feishuUserInfo.getUserId().trim() : null;
validateOAuthProfile(openId, userId, feishuUserInfo);
// open_id is mandatory for account matching. Never query with null or
// bind a record based on an incomplete Feishu response.
SysUser user = sysUserRepository.findByFeishuOpenId(openId);
// Check ownership before provisioning. user_id is only a duplicate-
// ownership guard; it is never used to discover or adopt an account.
SysUser otherOwner = userId == null ? null : sysUserRepository.findByFeishuUserId(userId);
if (otherOwner != null && (user == null || !java.util.Objects.equals(user.getId(), otherOwner.getId()))) {
throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403);
}
if (user == null) {
try {
user = provisionEmployee(feishuUserInfo);
} catch (DataIntegrityViolationException race) {
// A concurrent first login may have won the unique open_id
// insert. Reuse that committed account instead of exposing
// a database 500 to the OAuth callback.
user = sysUserRepository.findByFeishuOpenId(openId);
if (user == null) throw new BusinessException("飞书账号绑定冲突,请联系管理员", 403);
}
}
// Reject dual ownership even when both identifiers on the selected record are populated.
if (otherOwner != null && !java.util.Objects.equals(user.getId(), otherOwner.getId()))
throw new BusinessException("飞书账号绑定不一致,请联系管理员", 403);
// The finalizer rechecks the exact open_id and current ACTIVE status
// under a row lock, then performs only the safe profile/binding update.
return loginPersistence.completeOAuth(user.getId(), feishuUserInfo);
}
/** Provision an ordinary employee; OAuth can never create a privileged account. */
@Transactional
protected SysUser provisionEmployee(FeishuUserInfo feishuUserInfo) {
String openId = feishuUserInfo.getOpenId().trim();
SysUser existing = sysUserRepository.findByFeishuOpenId(openId);
if (existing != null) return existing;
String userId = feishuUserInfo.getUserId() == null ? null : feishuUserInfo.getUserId().trim();
String number = uniqueEmployeeNo();
SysUser user = SysUser.builder()
.feishuOpenId(openId)
.feishuUserId(StringUtils.hasText(userId) ? userId : null)
.employeeNo(number)
.realName(StringUtils.hasText(feishuUserInfo.getName()) ? feishuUserInfo.getName() : "Feishu User")
.avatarUrl(feishuUserInfo.getAvatarUrl())
.email(feishuUserInfo.getEmail())
.mobile(feishuUserInfo.getMobile())
.userType("EMPLOYEE")
.status("ACTIVE")
.directoryStatus("UNKNOWN")
.build();
SysUser saved = sysUserRepository.save(user);
if (saved != null) user = saved;
log.info("自动创建 Feishu EMPLOYEE 用户: openId={}, employeeNo={}, name={}", openId, number, user.getRealName());
// Flush so the subsequent lookup sees the new record
sysUserRepository.flush();
return user;
}
private void validateOAuthProfile(String openId, String userId, FeishuUserInfo info) {
validateLength(openId, 100);
validateLength(userId, 100);
validateLength(info.getName(), 100);
validateLength(info.getAvatarUrl(), 500);
validateLength(info.getEmail(), 200);
validateLength(info.getMobile(), 20);
}
private void validateLength(String value, int max) {
if (value != null && value.length() > max) {
throw new BusinessException("飞书用户资料无效,请重新授权", 403);
}
}
private String uniqueEmployeeNo() {
for (int attempt = 0; attempt < 5; attempt++) {
String number = "FS-" + java.util.UUID.randomUUID();
if (sysUserRepository.findByEmployeeNo(number) == null) return number;
}
throw new BusinessException("员工编号生成失败,请稍后重试", 503);
}
private BusinessException invalidFeishuIdentity() {
return new BusinessException("飞书身份无效,请重新授权", 403);
}
private String appId() { return configured("appId", feishuConfig.getAppId()); }
private String appSecret() { return configured("appSecret", feishuConfig.getAppSecret()); }
private String redirectUri() { return configured("redirectUri", feishuConfig.getRedirectUri()); }
private String approvalCode() { return configured("approvalCode", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getApprovalCode()); }
private String verificationToken() { return configured("verificationToken", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getVerificationToken()); }
private String encryptKey() { return configured("encryptKey", feishuConfig.getApproval() == null ? null : feishuConfig.getApproval().getEncryptKey()); }
private String configured(String key, String fallback) { return integrationConfigReader == null ? fallback : integrationConfigReader.get("FEISHU", key); }
public static final class AuthUrl {
private final String authUrl;
private final String state;
public AuthUrl(String authUrl, String state) {
this.authUrl = authUrl;
this.state = state;
}
public String getAuthUrl() {
return authUrl;
}
public String getState() {
return state;
}
}
}
@@ -0,0 +1,35 @@
package com.finance.system.adapter.feishu;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "feishu")
public class FeishuConfig {
private String appId;
private String appSecret;
private String redirectUri;
/**
* Legacy setting retained for configuration compatibility. OAuth no
* longer has a local bootstrap exception and always provisions an
* ordinary employee.
*/
@Deprecated
private boolean localBootstrapEnabled = false;
/** @deprecated No longer used for OAuth identity provisioning. */
@Deprecated
private String localBootstrapOpenId;
private Approval approval = new Approval();
@Data
public static class Approval {
/** 飞书审批定义编码,如 EXPENSE_REIMBURSEMENT_001 */
private String approvalCode;
/** 事件回调验证Token */
private String verificationToken;
/** 事件回调加密Key(可选) */
private String encryptKey;
}
}
@@ -0,0 +1,62 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.Map;
@Service
public class FeishuDirectoryAccessService {
private final FeishuTenantTokenService tokens;
private final FeishuDirectorySettings settings;
private final Environment environment;
private final JdbcTemplate jdbc;
public FeishuDirectoryAccessService(FeishuTenantTokenService tokens, FeishuDirectoryClient client,
FeishuDirectorySettings settings, Environment environment, JdbcTemplate jdbc,
org.springframework.transaction.PlatformTransactionManager manager) {
this.tokens = tokens; this.settings = settings; this.environment = environment; this.jdbc = jdbc;
}
public boolean allowed(SysUser user) {
if (user == null || !"ACTIVE".equalsIgnoreCase(user.getStatus())) return false;
if (Arrays.stream(environment.getActiveProfiles()).anyMatch("local"::equalsIgnoreCase)
&& blank(user.getFeishuOpenId()) && blank(user.getFeishuUserId())) return true;
return directoryAllowed(user);
}
public boolean directoryAllowed(SysUser user) {
try {
return user != null && !blank(user.getFeishuOpenId()) && "ACTIVE".equalsIgnoreCase(user.getStatus()) && "ELIGIBLE".equals(user.getDirectoryStatus())
&& tokens.capture().fingerprint.equals(user.getDirectoryContext()) && user.getDirectoryVerifiedAt() != null
&& !user.getDirectoryVerifiedAt().isAfter(Instant.now())
&& user.getDirectoryVerifiedAt().plusSeconds(settings.statusAge()).isAfter(Instant.now())
&& !blank(user.getDirectoryLastSeenRunId()) && !blank(user.getFeishuUserId())
&& currentSnapshotMatches(user);
} catch (Exception e) { return false; }
}
public void requireAllowed(SysUser user) { if (!allowed(user)) throw denied(); }
public void requireSynced(SysUser user) {
if (!directoryAllowed(user) || user.getDirectoryLastSeenRunId() == null) throw denied();
}
private boolean currentSnapshotMatches(SysUser user) {
if (jdbc == null) return false;
try {
Map<String,Object> state = jdbc.queryForMap("SELECT last_successful_run_id,last_successful_at,successful_context FROM feishu_directory_state WHERE id=1");
Object runId = state.get("last_successful_run_id");
Object successfulContext = state.get("successful_context");
Timestamp successfulAt = (Timestamp) state.get("last_successful_at");
Instant now = Instant.now();
return runId != null && successfulContext != null && successfulAt != null
&& runId.toString().equals(user.getDirectoryLastSeenRunId())
&& successfulContext.toString().equals(user.getDirectoryContext())
&& !successfulAt.toInstant().isAfter(now)
&& successfulAt.toInstant().plusSeconds(settings.statusAge()).isAfter(now);
} catch (Exception e) { return false; }
}
private static boolean blank(String value) { return value == null || value.trim().isEmpty(); }
private static BusinessException denied() { return new BusinessException("Current eligible Feishu employee verification required", 403); }
}
@@ -0,0 +1,21 @@
package com.finance.system.adapter.feishu;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
@Slf4j
public class FeishuDirectoryBootstrap {
private final FeishuDirectorySettings settings;
private final FeishuDirectoryService directory;
@EventListener(ApplicationReadyEvent.class)
public void start() {
if (!settings.isBootstrapSyncOnStartup()) return;
try { directory.sync("STARTUP"); }
catch (Exception e) { log.warn("Startup directory sync unavailable; employee access remains fail-closed"); }
}
}
@@ -0,0 +1,809 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.concurrent.locks.LockSupport;
/** Contact v3 only. No caller-controlled host, URL or identifier type. */
@Component
@Slf4j
public class FeishuDirectoryClient {
private static final BigInteger SUCCESS_CODE = BigInteger.ZERO;
private static final BigInteger RATE_LIMIT_CODE = BigInteger.valueOf(99991400L);
private static final BigInteger DEFINITIVE_CODE_41012 = BigInteger.valueOf(41012L);
private static final BigInteger DEFINITIVE_CODE_41050 = BigInteger.valueOf(41050L);
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
private static final String DEPARTMENT_STATUS_INVALID = "DIRECTORY_DEPARTMENT_STATUS_INVALID";
private static final String IDENTITY_INVALID = "DIRECTORY_IDENTITY_INVALID";
private static final String LIMIT_EXCEEDED = "DIRECTORY_LIMIT_EXCEEDED";
private enum PageKind {
DEPARTMENT("DIRECTORY_DEPARTMENT_PAGE_INVALID", "DIRECTORY_DEPARTMENT_ITEM_INVALID",
"DIRECTORY_DEPARTMENT_PAGE_TOKEN_INVALID", "DIRECTORY_DEPARTMENT_ITEMS_INVALID",
"DIRECTORY_DEPARTMENT_HAS_MORE_INVALID"),
USER("DIRECTORY_USER_PAGE_INVALID", "DIRECTORY_USER_ITEM_INVALID",
"DIRECTORY_USER_PAGE_TOKEN_INVALID", "DIRECTORY_USER_ITEMS_INVALID",
"DIRECTORY_USER_HAS_MORE_INVALID");
private final String pageInvalid;
private final String itemInvalid;
private final String pageTokenInvalid;
private final String itemsInvalid;
private final String hasMoreInvalid;
PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid) {
this(pageInvalid, itemInvalid, pageTokenInvalid, pageInvalid, pageInvalid);
}
PageKind(String pageInvalid, String itemInvalid, String pageTokenInvalid,
String itemsInvalid, String hasMoreInvalid) {
this.pageInvalid = pageInvalid;
this.itemInvalid = itemInvalid;
this.pageTokenInvalid = pageTokenInvalid;
this.itemsInvalid = itemsInvalid;
this.hasMoreInvalid = hasMoreInvalid;
}
}
private final FeishuTenantTokenService tokens;
private final FeishuDirectorySettings settings;
private final RestTemplate http;
private final RateGate rateGate;
// A hard wall-clock deadline also covers slow/trickling HTTP bodies. No unbounded work queue.
private final ExecutorService workers = new ThreadPoolExecutor(0, 2, 30,
TimeUnit.SECONDS, new SynchronousQueue<>(), task -> {
Thread thread = new Thread(task, "feishu-directory-http"); thread.setDaemon(true); return thread;
});
// Department and user pages are fetched in bounded batches. The queue is
// bounded as well so concurrent snapshots cannot turn a large department
// tree into thousands of pending tasks.
private final ExecutorService directoryWorkers;
@Autowired
public FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings) {
this(tokens, settings, httpClient());
}
FeishuDirectoryClient(FeishuTenantTokenService tokens, FeishuDirectorySettings settings, RestTemplate http) {
this.tokens = tokens; this.settings = settings; this.http = http;
this.rateGate = new RateGate(settings);
int concurrency = settings.getDirectoryConcurrency();
this.directoryWorkers = new ThreadPoolExecutor(concurrency, concurrency, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(concurrency), task -> {
Thread thread = new Thread(task, "feishu-directory-user-http"); thread.setDaemon(true); return thread;
});
}
@javax.annotation.PreDestroy
public void close() {
shutdownGracefully(workers);
shutdownGracefully(directoryWorkers);
}
private static void shutdownGracefully(ExecutorService executor) {
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) executor.shutdownNow();
} catch (InterruptedException e) {
executor.shutdownNow(); Thread.currentThread().interrupt();
}
}
private static RestTemplate httpClient() {
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(3000); f.setReadTimeout(5000);
return new RestTemplate(f);
}
public Snapshot fetch(FeishuTenantTokenService.Context context) {
final Budget budget = new Budget();
return bounded(() -> fetchSnapshot(context, budget), settings.elapsed());
}
private Snapshot fetchSnapshot(FeishuTenantTokenService.Context context, Budget budget) {
budget.check();
String token = tokens.token(context);
budget.check();
Snapshot snapshot = new Snapshot();
snapshot.departments.add("0");
snapshot.departmentDetails.put("0", Department.root());
discoverDepartments(snapshot, token, budget);
fetchUsers(snapshot, token, budget);
budget.check(); return snapshot;
}
private void discoverDepartments(Snapshot snapshot, String token, Budget budget) {
ArrayDeque<String> pending = new ArrayDeque<>();
pending.add("0");
int concurrency = settings.getDirectoryConcurrency();
while (!pending.isEmpty()) {
int end = Math.min(concurrency, pending.size());
List<String> wave = new ArrayList<>(end);
for (int i = 0; i < end; i++) wave.add(pending.remove());
List<Future<DepartmentFetchResult>> outstanding = new ArrayList<>(end);
Map<Integer, List<JsonNode>> completed = new HashMap<>();
try {
BlockingQueue<Future<DepartmentFetchResult>> completionQueue = new ArrayBlockingQueue<>(end);
CompletionService<DepartmentFetchResult> completion =
new ExecutorCompletionService<>(directoryWorkers, completionQueue);
for (int i = 0; i < wave.size(); i++) {
final int departmentIndex = i;
final String department = wave.get(i);
outstanding.add(completion.submit(() -> new DepartmentFetchResult(departmentIndex,
fetchDepartmentChildren(department, token, budget))));
}
// A completed result is retained only for this bounded wave. All
// directory mutations happen here, in discovery order.
for (int completedCount = 0; completedCount < wave.size(); completedCount++) {
Future<DepartmentFetchResult> future = completion.take();
outstanding.remove(future);
DepartmentFetchResult result;
try { result = future.get(); }
catch (ExecutionException e) { throw workerFailure(e.getCause()); }
catch (CancellationException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED");
}
completed.put(result.departmentIndex, result.children);
}
for (int i = 0; i < wave.size(); i++)
mergeDepartments(snapshot, pending, wave.get(i), completed.get(i));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED");
} catch (RejectedExecutionException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE");
} finally {
cancelOutstanding(outstanding);
}
}
}
private List<JsonNode> fetchDepartmentChildren(String department, String token, Budget budget) {
List<JsonNode> children = new ArrayList<>();
pages("/contact/v3/departments/" + segment(department) + "/children", null,
PageKind.DEPARTMENT, token, budget, children::add);
return children;
}
private void mergeDepartments(Snapshot snapshot, ArrayDeque<String> pending, String parent,
List<JsonNode> children) {
for (JsonNode node : children) {
JsonNode status = node.path("status");
if (!status.isObject() || !status.path("is_deleted").isBoolean())
throw FeishuTenantTokenService.diagnostic(DEPARTMENT_STATUS_INVALID);
// Deleted departments are a normal part of a directory response. Do not
// enqueue them, but keep failing closed for a malformed status object.
if (status.path("is_deleted").booleanValue()) continue;
// Default traversal must use the open identifier returned by the
// official endpoint. A legacy/custom field must not silently be
// used for the next request.
// The snapshot contract is always open-id based. Even if an
// installation requests a legacy department_id query mode, never
// reinterpret that custom identifier as open_department_id.
String child = requiredDepartmentIdentity(node, "open_department_id");
if (snapshot.departments.add(child)) {
pending.add(child);
snapshot.departmentDetails.put(child, Department.from(node, child, parent));
}
if (snapshot.departments.size() > Math.min(5000, settings.getMaxDepartments()))
throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED);
}
}
private void fetchUsers(Snapshot snapshot, String token, Budget budget) {
List<String> departmentIds = new ArrayList<>(snapshot.departments);
int concurrency = settings.getDirectoryConcurrency();
for (int offset = 0; offset < departmentIds.size(); offset += concurrency) {
List<Future<UserFetchResult>> outstanding = new ArrayList<>(concurrency);
Map<Integer, List<JsonNode>> completed = new HashMap<>();
int end = Math.min(departmentIds.size(), offset + concurrency);
try {
BlockingQueue<Future<UserFetchResult>> completionQueue = new ArrayBlockingQueue<>(concurrency);
CompletionService<UserFetchResult> completion = new ExecutorCompletionService<>(directoryWorkers, completionQueue);
for (int i = offset; i < end; i++) {
final int departmentIndex = i;
final String department = departmentIds.get(i);
outstanding.add(completion.submit(() -> new UserFetchResult(departmentIndex,
fetchDepartmentUsers(department, token, budget))));
}
// Observe completion order so a failed worker is propagated
// immediately, but retain results only for this bounded window.
for (int completedCount = 0; completedCount < end - offset; completedCount++) {
Future<UserFetchResult> future = completion.take();
outstanding.remove(future);
UserFetchResult result;
try { result = future.get(); }
catch (ExecutionException e) { throw workerFailure(e.getCause()); }
catch (CancellationException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED");
}
completed.put(result.departmentIndex, result.users);
}
// Merge on this caller/collector thread in department discovery
// order, never in completion order.
for (int i = offset; i < end; i++)
mergeUsers(snapshot, departmentIds.get(i), completed.get(i));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED");
} catch (RejectedExecutionException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE");
} finally {
cancelOutstanding(outstanding);
}
}
}
private List<JsonNode> fetchDepartmentUsers(String department, String token, Budget budget) {
List<JsonNode> users = new ArrayList<>();
Set<String> identities = new HashSet<>();
pages("/contact/v3/users/find_by_department", department, PageKind.USER, token, budget, node -> {
String open = requiredIdentity(node, "open_id");
requiredIdentity(node, "user_id");
users.add(node);
if (identities.add(open)
&& identities.size() > Math.min(50000, settings.getMaxUsers()))
throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED);
});
return users;
}
private void mergeUsers(Snapshot snapshot, String department, List<JsonNode> users) {
for (JsonNode node : users) {
String open = requiredIdentity(node, "open_id");
String userId = requiredIdentity(node, "user_id");
JsonNode previous = snapshot.users.putIfAbsent(open, node);
if (previous != null && (!requiredIdentity(previous, "user_id").equals(userId)
|| eligible(previous) != eligible(node)))
throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
UserSummary summary = snapshot.userSummaries.get(open);
if (summary == null) {
summary = UserSummary.from(node, department);
summary.departmentIds.removeIf(id -> !snapshot.departments.contains(id));
summary.addDepartment(department);
snapshot.userSummaries.put(open, summary);
} else {
summary.departmentIds.removeIf(id -> !snapshot.departments.contains(id));
summary.merge(node, snapshot.departments);
summary.addDepartment(department);
}
if (snapshot.users.size() > Math.min(50000, settings.getMaxUsers()))
throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED);
}
}
private static final class UserFetchResult {
private final int departmentIndex;
private final List<JsonNode> users;
private UserFetchResult(int departmentIndex, List<JsonNode> users) {
this.departmentIndex = departmentIndex;
this.users = users;
}
}
private static final class DepartmentFetchResult {
private final int departmentIndex;
private final List<JsonNode> children;
private DepartmentFetchResult(int departmentIndex, List<JsonNode> children) {
this.departmentIndex = departmentIndex;
this.children = children;
}
}
private static FeishuTenantTokenService.DiagnosticFailure workerFailure(Throwable cause) {
if (cause instanceof FeishuTenantTokenService.DiagnosticFailure)
return (FeishuTenantTokenService.DiagnosticFailure) cause;
return FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED");
}
private static void cancelOutstanding(List<? extends Future<?>> futures) {
for (Future<?> future : futures) if (!future.isDone()) future.cancel(true);
}
public JsonNode verify(String openId, FeishuTenantTokenService.Context context) {
final Budget budget = new Budget();
return bounded(() -> verifyUser(openId, context, budget), Math.min(15, settings.elapsed()));
}
private JsonNode verifyUser(String openId, FeishuTenantTokenService.Context context, Budget budget) {
budget.check();
String token = tokens.token(context);
budget.check();
JsonNode data;
try { data = get(UriComponentsBuilder.fromHttpUrl(FeishuTenantTokenService.API + "/contact/v3/users/" + segment(openId))
.queryParam("user_id_type", "open_id").queryParam("department_id_type", settings.departmentIdType()).build().encode().toUri(), token, budget, true); }
catch (DefinitiveDenial e) { return null; }
JsonNode user = data.path("user");
if (!openId.equals(requiredIdentity(user, "open_id")))
throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
requiredIdentity(user, "user_id"); return user;
}
private void pages(String path, String department, PageKind kind, String token, Budget budget, Consumer<JsonNode> accept) {
String page = null; Set<String> seen = new HashSet<>();
do {
UriComponentsBuilder uri = UriComponentsBuilder.fromHttpUrl(FeishuTenantTokenService.API + path)
.queryParam("department_id_type", settings.departmentIdType())
.queryParam("user_id_type", "open_id").queryParam("page_size", 50);
if (department != null) uri.queryParam("department_id", department);
else uri.queryParam("fetch_child", false);
if (page != null) uri.queryParam("page_token", "{pageToken}");
// Tokens are opaque: strict URI-variable encoding escapes '+' as %2B,
// '/' as %2F, '=' as %3D, and literal '%' exactly once.
java.net.URI target = page == null ? uri.build().encode().toUri()
: uri.encode().buildAndExpand(java.util.Collections.singletonMap("pageToken", page)).toUri();
// Contact v3's pagination object is body.data, not the response body.
// Keep the operation kind here so a malformed envelope or page can be
// diagnosed without retaining or exposing Feishu response content.
JsonNode data = get(target, token, budget, false, kind);
if (!data.path("has_more").isBoolean())
throw FeishuTenantTokenService.diagnostic(kind.hasMoreInvalid);
JsonNode items = data.path("items");
// Feishu may omit items for an empty terminal page. Treat only that
// unambiguous case as an empty list; a missing list on a paginated
// response remains fail-closed because it could hide directory data.
if (!data.has("items") && !data.path("has_more").booleanValue()) {
items = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.arrayNode();
} else if (!data.has("items")) {
log.warn("Feishu directory page shape invalid: kind={}, itemsType=MISSING", kind);
throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_MISSING");
}
if (!items.isArray()) {
log.warn("Feishu directory page shape invalid: kind={}, itemsType={}", kind, items.getNodeType());
throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_TYPE_INVALID");
}
if (items.size() > 50) {
log.warn("Feishu directory page exceeds contract: kind={}, itemCount={}", kind, items.size());
throw FeishuTenantTokenService.diagnostic(kind.itemsInvalid + "_PAGE_TOO_LARGE");
}
// Contact v3 documents a maximum page size of 50 for both endpoints.
// Keep this separate from the aggregate snapshot limits below.
int maxItems = kind == PageKind.DEPARTMENT
? Math.min(5000, settings.getMaxDepartments())
: Math.min(50000, settings.getMaxUsers());
if (items.size() > maxItems)
throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED);
for (JsonNode item : items) {
if (item == null || !item.isObject()) throw FeishuTenantTokenService.diagnostic(kind.itemInvalid);
accept.accept(item);
}
if (!data.path("has_more").booleanValue()) return;
page = requiredPageToken(data, kind);
if (!seen.add(page)) throw FeishuTenantTokenService.diagnostic(kind.pageTokenInvalid);
} while (true);
}
private JsonNode get(java.net.URI uri, String token, Budget budget, boolean live) {
return get(uri, token, budget, live, null);
}
private JsonNode get(java.net.URI uri, String token, Budget budget, boolean live, PageKind pageKind) {
int retries = 0;
while (true) {
budget.page();
HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(token);
try {
rateGate.acquire(budget);
ResponseEntity<JsonNode> response = http.exchange(uri, HttpMethod.GET,
new HttpEntity<Void>(headers), JsonNode.class);
JsonNode body = response.getBody();
budget.check();
if (live && definitive(body)) throw new DefinitiveDenial();
if (isRateLimited(body, null)) throw new RateLimited(parseResetSeconds(
response.getHeaders().getFirst("x-ogw-ratelimit-reset")));
BigInteger code = responseCode(body);
if (code == null || !SUCCESS_CODE.equals(code) || !body.path("data").isObject()) {
RemoteFailure failure = remoteFailure(body, null);
if (failure != null) throw failure;
throw FeishuTenantTokenService.diagnostic(pageKind == null
? "DIRECTORY_RESPONSE_INVALID" : pageKind.pageInvalid);
}
return body.path("data");
} catch (DefinitiveDenial e) { throw e; }
catch (FeishuTenantTokenService.DiagnosticFailure e) { throw e; }
catch (RateLimited e) {
if (retries++ >= settings.maxRetries())
throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED");
rateGate.block(e.resetSeconds);
budget.awaitRateLimit(e.resetSeconds, retries);
} catch (org.springframework.web.client.HttpStatusCodeException e) {
JsonNode body = null;
try { body = readErrorBody(e.getResponseBodyAsString()); } catch (Exception ignored) { }
if (live && definitive(body)) throw new DefinitiveDenial();
if (isRateLimited(body, e.getStatusCode().value())) {
if (retries++ >= settings.maxRetries())
throw FeishuTenantTokenService.diagnostic("DIRECTORY_RATE_LIMIT_EXHAUSTED");
String reset = e.getResponseHeaders() == null ? null
: e.getResponseHeaders().getFirst("x-ogw-ratelimit-reset");
Long resetSeconds = parseResetSeconds(reset);
rateGate.block(resetSeconds);
budget.awaitRateLimit(resetSeconds, retries);
continue;
}
RemoteFailure failure = remoteFailure(body, e.getStatusCode().value());
if (failure != null) throw failure;
throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED");
} catch (Exception e) { throw FeishuTenantTokenService.diagnostic("DIRECTORY_REQUEST_FAILED"); }
}
}
private static boolean isRateLimited(JsonNode body, Integer status) {
return (status != null && status == 429) || (body != null && body.path("code").isIntegralNumber()
&& RATE_LIMIT_CODE.equals(responseCode(body)));
}
private static Long parseResetSeconds(String value) {
if (value == null || !value.trim().matches("[0-9]{1,10}")) return null;
try { return Long.valueOf(value.trim()); } catch (NumberFormatException ignored) { return null; }
}
private static JsonNode readErrorBody(String responseBody) throws java.io.IOException {
// Error text is deliberately never retained or included in an exception. Avoid
// parsing an unexpectedly large response while looking for its numeric code.
if (responseBody == null || responseBody.length() > 16384) return null;
return new com.fasterxml.jackson.databind.ObjectMapper().readTree(responseBody);
}
private static RemoteFailure remoteFailure(JsonNode body, Integer httpStatus) {
Long code = safeCode(body);
if (code != null) return new RemoteFailure("FEISHU_CODE_" + code);
if (httpStatus != null && httpStatus >= 100 && httpStatus <= 599)
return new RemoteFailure("HTTP_STATUS_" + httpStatus);
return null;
}
private static Long safeCode(JsonNode body) {
BigInteger code = responseCode(body);
if (code == null || code.signum() <= 0 || code.compareTo(MAX_DIAGNOSTIC_CODE) > 0) return null;
return code.longValueExact();
}
private static boolean definitive(JsonNode body) {
BigInteger code = responseCode(body);
return DEFINITIVE_CODE_41050.equals(code) || DEFINITIVE_CODE_41012.equals(code);
}
private static BigInteger responseCode(JsonNode body) {
if (body == null) return null;
JsonNode value = body.path("code");
if (!value.isIntegralNumber()) return null;
try { return value.bigIntegerValue(); }
catch (RuntimeException ignored) { return null; }
}
private static class DefinitiveDenial extends RuntimeException { }
/** Numeric-only diagnostic that is safe to cross the bounded worker boundary. */
public static final class RemoteFailure extends FeishuTenantTokenService.DiagnosticFailure {
private RemoteFailure(String diagnosticCode) {
super(diagnosticCode);
}
}
private <T> T bounded(java.util.concurrent.Callable<T> task, long seconds) {
java.util.concurrent.Future<T> future = null;
try { future = workers.submit(task); return future.get(seconds, java.util.concurrent.TimeUnit.SECONDS); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED"); }
catch (java.util.concurrent.ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof FeishuTenantTokenService.DiagnosticFailure)
throw (FeishuTenantTokenService.DiagnosticFailure) cause;
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED");
} catch (java.util.concurrent.TimeoutException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE");
} catch (java.util.concurrent.RejectedExecutionException e) {
throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_UNAVAILABLE");
}
catch (Exception e) { throw FeishuTenantTokenService.diagnostic("DIRECTORY_WORKER_FAILED"); }
finally { if (future != null && !future.isDone()) future.cancel(true); }
}
public static boolean eligible(JsonNode user) {
JsonNode status = user.path("status");
return status.path("is_activated").isBoolean() && status.path("is_activated").booleanValue()
&& status.path("is_resigned").isBoolean() && !status.path("is_resigned").booleanValue()
&& status.path("is_frozen").isBoolean() && !status.path("is_frozen").booleanValue()
&& status.path("is_exited").isBoolean() && !status.path("is_exited").booleanValue()
&& status.path("is_unjoin").isBoolean() && !status.path("is_unjoin").booleanValue()
&& user.path("employee_type").isIntegralNumber()
&& BigInteger.ONE.equals(user.path("employee_type").bigIntegerValue());
}
static String required(JsonNode node, String key) {
return required(node, key, 100);
}
static String requiredIdentity(JsonNode node, String key) {
JsonNode value = node == null ? null : node.path(key);
if (!validText(value, 100)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
return value.asText().trim();
}
private static String requiredDepartmentIdentity(JsonNode node, String key) {
JsonNode value = node == null ? null : node.path(key);
if (!validText(value, 64)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
return value.asText().trim();
}
private static String required(JsonNode node, String key, int maxLength) {
JsonNode value = node == null ? null : node.path(key);
if (!validText(value, maxLength)) throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
return value.asText();
}
private static String requiredPageToken(JsonNode node, PageKind kind) {
JsonNode value = node == null ? null : node.path("page_token");
if (!validText(value, 4096)) throw FeishuTenantTokenService.diagnostic(kind.pageTokenInvalid);
return value.asText();
}
private static boolean validText(JsonNode value, int maxLength) {
return value != null && value.isTextual() && !value.asText().trim().isEmpty()
&& value.asText().length() <= maxLength;
}
private static boolean validText(String value, int maxLength) {
return value != null && !value.trim().isEmpty() && value.length() <= maxLength;
}
private static String segment(String id) {
if (id == null || !id.matches("[A-Za-z0-9][A-Za-z0-9_@.\\-]{0,63}"))
throw FeishuTenantTokenService.diagnostic(IDENTITY_INVALID);
return id;
}
public static class Snapshot {
public final Set<String> departments = new LinkedHashSet<>();
public final Map<String, JsonNode> users = new LinkedHashMap<>();
/** Safe, presentation-independent department records from the same snapshot. */
public final Map<String, Department> departmentDetails = new LinkedHashMap<>();
/** Safe user summaries; raw users above are retained only for account application. */
public final Map<String, UserSummary> userSummaries = new LinkedHashMap<>();
}
public static class Department {
public String openDepartmentId;
public String name;
public String parentOpenDepartmentId;
public long order;
public String status;
public int memberCount;
public static Department root() {
Department root = new Department();
root.openDepartmentId = "0";
root.name = "根部门";
root.parentOpenDepartmentId = "0";
root.status = "ACTIVE";
return root;
}
static Department from(JsonNode node, String id, String traversalParent) {
Department department = new Department();
department.openDepartmentId = id;
department.name = optionalText(node, "name", "");
// parent_department_id is deliberately not used here: with an
// open-id request it may still be a legacy/custom identifier.
// The traversal request already establishes the parent with an
// open id. Prefer it over any legacy parent_department_id-shaped
// value returned in the payload.
department.parentOpenDepartmentId = traversalParent;
department.order = optionalLong(node, "order", 0L);
department.status = "ACTIVE";
return department;
}
public String getOpenDepartmentId() { return openDepartmentId; }
public String getName() { return name; }
public String getParentOpenDepartmentId() { return parentOpenDepartmentId; }
public long getOrder() { return order; }
public String getStatus() { return status; }
public int getMemberCount() { return memberCount; }
}
public static class UserSummary {
public String openId;
public String userId;
public String name;
public String employeeNo;
public String email;
public String mobile;
public String jobTitle;
public Integer employeeType;
public String avatarUrl;
public String employmentStatus;
public final List<String> departmentIds = new ArrayList<>();
public boolean eligible;
static UserSummary from(JsonNode node, String fallbackDepartment) {
UserSummary summary = new UserSummary();
summary.openId = optionalText(node, "open_id", "");
summary.userId = optionalText(node, "user_id", "");
summary.name = optionalText(node, "name", "");
summary.employeeNo = optionalText(node, "employee_no", "");
// Keep this allow-list deliberately explicit. Contact v3 user nodes
// contain more data than the directory API is allowed to retain.
summary.email = optionalText(node, "email", "", 320);
summary.mobile = optionalText(node, "mobile", "", 50);
summary.jobTitle = optionalText(node, "job_title", "", 200);
if (summary.jobTitle.isEmpty()) summary.jobTitle = optionalText(node, "position", "", 200);
summary.employeeType = optionalInteger(node, "employee_type");
summary.avatarUrl = optionalAvatarUrl(node);
summary.employmentStatus = employmentStatus(node);
JsonNode ids = node == null ? null : node.path("department_ids");
if (ids != null && ids.isArray()) {
for (JsonNode id : ids) {
if (id.isTextual() && validText(id, 64) && !summary.departmentIds.contains(id.asText().trim()))
summary.departmentIds.add(id.asText().trim());
}
}
// A missing department_ids field is common on reduced contact
// responses. The requested department is already an open id and
// is therefore a safe fallback; department_id is never consulted.
if (summary.departmentIds.isEmpty() && validText(fallbackDepartment, 64))
summary.departmentIds.add(fallbackDepartment.trim());
summary.eligible = eligible(node);
return summary;
}
void addDepartment(String department) {
if (validText(department, 64) && !departmentIds.contains(department.trim()))
departmentIds.add(department.trim());
}
void merge(JsonNode node, Set<String> knownDepartments) {
if (name == null || name.isEmpty()) name = optionalText(node, "name", "");
if (employeeNo == null || employeeNo.isEmpty()) employeeNo = optionalText(node, "employee_no", "");
if (email == null || email.isEmpty()) email = optionalText(node, "email", "", 320);
if (mobile == null || mobile.isEmpty()) mobile = optionalText(node, "mobile", "", 50);
if (jobTitle == null || jobTitle.isEmpty()) {
jobTitle = optionalText(node, "job_title", "", 200);
if (jobTitle.isEmpty()) jobTitle = optionalText(node, "position", "", 200);
}
if (employeeType == null) employeeType = optionalInteger(node, "employee_type");
if (avatarUrl == null || avatarUrl.isEmpty()) avatarUrl = optionalAvatarUrl(node);
if (employmentStatus == null || employmentStatus.isEmpty() || "UNKNOWN".equals(employmentStatus))
employmentStatus = employmentStatus(node);
JsonNode ids = node == null ? null : node.path("department_ids");
if (ids != null && ids.isArray()) for (JsonNode id : ids)
if (id.isTextual() && validText(id, 64) && knownDepartments.contains(id.asText().trim()))
addDepartment(id.asText());
}
public String getOpenId() { return openId; }
public String getUserId() { return userId; }
public String getName() { return name; }
public String getEmployeeNo() { return employeeNo; }
public String getEmail() { return email; }
public String getMobile() { return mobile; }
public String getJobTitle() { return jobTitle; }
public Integer getEmployeeType() { return employeeType; }
public String getAvatarUrl() { return avatarUrl; }
public String getEmploymentStatus() { return employmentStatus; }
public List<String> getDepartmentIds() { return departmentIds; }
public boolean isEligible() { return eligible; }
}
private static String optionalText(JsonNode node, String key, String fallback) {
return optionalText(node, key, fallback, 100);
}
private static String optionalText(JsonNode node, String key, String fallback, int maxLength) {
JsonNode value = node == null ? null : node.path(key);
return value != null && value.isTextual() && value.asText().length() <= maxLength
? value.asText().trim() : fallback;
}
private static Integer optionalInteger(JsonNode node, String key) {
JsonNode value = node == null ? null : node.path(key);
if (value == null || !value.isIntegralNumber()) return null;
try {
BigInteger integer = value.bigIntegerValue();
if (integer.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0
|| integer.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0)
return null;
return integer.intValueExact();
} catch (RuntimeException ignored) {
return null;
}
}
private static String optionalAvatarUrl(JsonNode node) {
String value = optionalText(node, "avatar_url", "", 500);
if (!value.isEmpty()) return value;
value = optionalText(node, "avatar", "", 500);
if (!value.isEmpty()) return value;
// Some Contact v3 responses represent avatar as an object. Select only
// documented URL variants; never serialize the object itself.
JsonNode avatar = node == null ? null : node.path("avatar");
if (avatar != null && avatar.isObject()) {
for (String key : new String[]{"avatar_url", "avatar_origin", "avatar_640", "avatar_240", "avatar_72"}) {
value = optionalText(avatar, key, "", 500);
if (!value.isEmpty()) return value;
}
}
return "";
}
/** Safe summary derived from the official status booleans, not a raw status object. */
private static String employmentStatus(JsonNode node) {
JsonNode status = node == null ? null : node.path("status");
if (status == null || !status.isObject()) return "UNKNOWN";
if (status.path("is_exited").isBoolean() && status.path("is_exited").booleanValue()) return "EXITED";
if (status.path("is_resigned").isBoolean() && status.path("is_resigned").booleanValue()) return "RESIGNED";
if (status.path("is_frozen").isBoolean() && status.path("is_frozen").booleanValue()) return "FROZEN";
if (status.path("is_unjoin").isBoolean() && status.path("is_unjoin").booleanValue()) return "UNJOINED";
if (status.path("is_activated").isBoolean())
return status.path("is_activated").booleanValue() ? "ACTIVE" : "INACTIVE";
return "UNKNOWN";
}
private static long optionalLong(JsonNode node, String key, long fallback) {
JsonNode value = node == null ? null : node.path(key);
if (value == null) return fallback;
if (value.isIntegralNumber()) {
try { return value.bigIntegerValue().longValueExact(); }
catch (ArithmeticException ignored) { return fallback; }
}
if (!value.isTextual()) return fallback;
String text = value.asText().trim();
// Contact v3 has returned order both as a JSON number and as a
// numeric string. Bound the text before parsing so malformed provider
// data cannot trigger unbounded numeric work.
if (text.length() == 0 || text.length() > 20 || !text.matches("[+-]?[0-9]+")) return fallback;
try { return new BigInteger(text).longValueExact(); }
catch (NumberFormatException | ArithmeticException ignored) { return fallback; }
}
private static final class RateLimited extends RuntimeException {
private final Long resetSeconds;
private RateLimited(Long resetSeconds) { this.resetSeconds = resetSeconds; }
}
/** One gate is shared by department discovery, user paging and verification. */
private final class RateGate {
private final FeishuDirectorySettings settings;
private final Deque<Long> requests = new ArrayDeque<>();
private long lastRequest = Long.MIN_VALUE;
private long blockedUntil = Long.MIN_VALUE;
private RateGate(FeishuDirectorySettings settings) { this.settings = settings; }
private void acquire(Budget budget) {
while (true) {
budget.check();
long now = System.nanoTime();
long waitUntil;
synchronized (this) {
long minuteAgo = now - TimeUnit.SECONDS.toNanos(60);
while (!requests.isEmpty() && requests.peekFirst() < minuteAgo) requests.removeFirst();
waitUntil = now;
if (lastRequest != Long.MIN_VALUE) {
long spacing = (TimeUnit.SECONDS.toNanos(1) + settings.requestsPerSecond() - 1L)
/ settings.requestsPerSecond();
waitUntil = Math.max(waitUntil, lastRequest + spacing);
}
if (requests.size() >= settings.requestsPerMinute() && !requests.isEmpty())
waitUntil = Math.max(waitUntil, requests.peekFirst() + TimeUnit.SECONDS.toNanos(60));
waitUntil = Math.max(waitUntil, blockedUntil);
if (waitUntil <= now) {
requests.addLast(now);
lastRequest = now;
return;
}
}
budget.awaitNanos(waitUntil - now);
}
}
private void block(Long resetSeconds) {
if (resetSeconds == null || resetSeconds <= 0) return;
long now = System.nanoTime();
long duration = resetSeconds > Long.MAX_VALUE / 1000000000L
? Long.MAX_VALUE : resetSeconds * 1000000000L;
long until = Long.MAX_VALUE - now < duration ? Long.MAX_VALUE : now + duration;
synchronized (this) { blockedUntil = Math.max(blockedUntil, until); }
}
}
private class Budget {
final long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(settings.elapsed());
final AtomicInteger pages = new AtomicInteger();
void check() {
if (Thread.currentThread().isInterrupted()) throw FeishuTenantTokenService.diagnostic("DIRECTORY_INTERRUPTED");
if (System.nanoTime() >= deadlineNanos)
throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE");
}
void page() {
check();
if (pages.incrementAndGet() > Math.min(2000, settings.getMaxPages()))
throw FeishuTenantTokenService.diagnostic(LIMIT_EXCEEDED);
check();
}
void awaitRateLimit(Long resetSeconds, int retry) {
long nanos;
if (resetSeconds != null) {
nanos = resetSeconds > Long.MAX_VALUE / 1000000000L
? Long.MAX_VALUE : resetSeconds * 1000000000L;
} else {
long backoffMillis = Math.min(2000L, 100L << Math.min(4, Math.max(0, retry - 1)));
nanos = TimeUnit.MILLISECONDS.toNanos(backoffMillis);
}
awaitNanos(nanos);
}
void awaitNanos(long requested) {
check();
long remaining = deadlineNanos - System.nanoTime();
if (remaining <= 0) throw FeishuTenantTokenService.diagnostic("DIRECTORY_DEADLINE");
LockSupport.parkNanos(Math.min(Math.max(0L, requested), remaining));
check();
}
}
}
@@ -0,0 +1,811 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysUserRepository;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
@Service
@Slf4j
public class FeishuDirectoryService {
private final JdbcTemplate jdbc;
private final TransactionTemplate tx;
private final SysUserRepository users;
private final FeishuTenantTokenService tokens;
private final FeishuDirectoryClient client;
private final FeishuDirectorySettings settings;
private final ObjectMapper mapper;
public FeishuDirectoryService(JdbcTemplate jdbc, PlatformTransactionManager manager, SysUserRepository users,
FeishuTenantTokenService tokens, FeishuDirectoryClient client,
FeishuDirectorySettings settings, ObjectMapper mapper) {
this.jdbc = jdbc; this.tx = new TransactionTemplate(manager); this.tx.setTimeout(30); this.users = users; this.tokens = tokens;
this.tx.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
this.tx.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
this.client = client; this.settings = settings; this.mapper = mapper;
}
public Run sync(String trigger) {
if (!Arrays.asList("MANUAL", "STARTUP").contains(trigger)) throw new IllegalArgumentException("Invalid trigger");
Run run = new Run(); run.runId = UUID.randomUUID().toString(); run.trigger = trigger; run.startedAt = Instant.now().toString();
FeishuTenantTokenService.Context context;
String runContext = null;
// Even configuration failures retain an operator-visible failed run.
acquire(run);
insertSyncRun(run);
try {
context = tx.execute(s -> {
lock();
// Capture first so a disabled/missing integration is not mistaken for
// the separate directory-sync switch being disabled.
FeishuTenantTokenService.Context captured = tokens.capture();
if (!tokens.syncEnabled()) throw FeishuTenantTokenService.syncDisabled();
return captured;
});
final String fingerprint = context.fingerprint;
runContext = fingerprint;
updateSyncRunContext(run.runId, fingerprint);
jdbc.update("UPDATE feishu_directory_state SET context=? WHERE id=1 AND owner=?", fingerprint, run.runId);
FeishuDirectoryClient.Snapshot snapshot = client.fetch(context);
// This probe must not be allowed to fail on the publication
// connection. It is deliberately performed between transactions;
// the metadata implementation also avoids a missing-table SQL
// statement. A migration racing this probe is handled atomically by
// the publication transaction below.
final boolean normalizedAvailable = normalizedSchemaAvailable();
tx.execute(s -> {
requireOwner(run, fingerprint);
if (!fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged();
if (!tokens.syncEnabled()) throw FeishuTenantTokenService.syncDisabled();
apply(snapshot, run, fingerprint);
replaceNormalizedSnapshot(snapshot, run, fingerprint, normalizedAvailable);
requireOwner(run, fingerprint);
if (!fingerprint.equals(tokens.capture().fingerprint)) throw FeishuTenantTokenService.contextChanged();
run.state = "SUCCEEDED"; run.complete = true; run.applied = true; run.finishedAt = Instant.now().toString();
// Encode only the allow-listed snapshot DTOs. Raw Feishu nodes
// are used above for account application, but are never persisted.
String snapshotJson = snapshotJson(snapshot);
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,last_run=?,last_successful_run_id=?,last_successful_at=?,successful_context=?,last_snapshot=? WHERE id=1",
json(run), run.runId, Timestamp.from(Instant.parse(run.finishedAt)), fingerprint, snapshotJson);
return null;
});
// Run history is auxiliary telemetry. Keep its optional table
// update outside the publication transaction so a V9-only
// deployment cannot mark that transaction rollback-only.
updateSyncRun(run, fingerprint);
} catch (Exception ex) {
run.state = "FAILED"; run.complete = false; run.applied = false; run.finishedAt = Instant.now().toString();
run.counts = new Counts();
String diagnostic = safeDiagnostic(ex);
run.errorCode = diagnostic == null ? "DIRECTORY_SYNC_FAILED" : diagnostic;
run.errorMessage = failureMessage(diagnostic);
// Never log the exception: its cause may contain a connector detail or a
// response body. The diagnostic is constructed from numeric values only.
log.warn("Feishu directory sync failed: runId={}, errorCode={}", run.runId, run.errorCode);
updateSyncRun(run, runContext);
jdbc.update("UPDATE feishu_directory_state SET owner=NULL,lease_until=NULL,last_run=? WHERE id=1 AND owner=?", json(run), run.runId);
}
return run;
}
private void insertSyncRun(Run run) {
try {
jdbc.update("INSERT INTO feishu_directory_sync_run(run_id,trigger,state,started_at,complete,applied,departments,users_seen,eligible,excluded,created,updated,ineligible,out_of_scope,error_code,error_message,context) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
run.runId, run.trigger, run.state, Timestamp.from(Instant.parse(run.startedAt)),
run.complete, run.applied, 0, 0, 0, 0, 0, 0, 0, 0, null, null, null);
} catch (Exception ignored) {
// Run history is auxiliary observability. A transient history-table
// failure must not prevent the fenced directory sync itself.
log.warn("Feishu directory sync run could not be recorded");
}
}
private void updateSyncRunContext(String runId, String context) {
try {
jdbc.update("UPDATE feishu_directory_sync_run SET context=? WHERE run_id=?", context, runId);
} catch (Exception ignored) {
log.warn("Feishu directory sync run context could not be recorded");
}
}
private void updateSyncRun(Run run, String context) {
try {
Counts counts = run.counts == null ? new Counts() : run.counts;
jdbc.update("UPDATE feishu_directory_sync_run SET state=?,finished_at=?,complete=?,applied=?,departments=?,users_seen=?,eligible=?,excluded=?,created=?,updated=?,ineligible=?,out_of_scope=?,error_code=?,error_message=?,context=? WHERE run_id=?",
run.state, run.finishedAt == null ? null : Timestamp.from(Instant.parse(run.finishedAt)),
run.complete, run.applied, counts.departments, counts.usersSeen, counts.eligible,
counts.excluded, counts.created, counts.updated, counts.ineligible, counts.outOfScope,
run.errorCode, run.errorMessage, context, run.runId);
} catch (Exception ignored) {
log.warn("Feishu directory sync run result could not be recorded: state={}", run.state);
}
}
private void replaceNormalizedSnapshot(FeishuDirectoryClient.Snapshot snapshot, Run run, String context,
boolean normalizedAvailable) {
// Keep V9 deployments operational during a rolling migration. Once
// V10 exists, any write failure below is allowed to abort publication.
if (!normalizedAvailable) return;
Timestamp observedAt = Timestamp.from(Instant.now());
Map<String,List<String>> relationships = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> entry : snapshot.users.entrySet()) {
FeishuDirectoryClient.UserSummary summary = snapshot.userSummaries.get(entry.getKey());
if (summary == null) summary = FeishuDirectoryClient.UserSummary.from(entry.getValue(), "0");
List<String> departmentIds = normalizedDepartmentIds(snapshot, summary);
relationships.put(entry.getKey(), departmentIds);
}
Map<String,Integer> memberCounts = normalizedMemberCounts(snapshot, relationships);
// Delete children first even though the V10 foreign keys cascade. This
// keeps cleanup portable across PostgreSQL/H2 and prevents an old
// relation from blocking replacement.
jdbc.update("DELETE FROM feishu_directory_user_department");
jdbc.update("DELETE FROM feishu_directory_user");
jdbc.update("DELETE FROM feishu_directory_department");
String departmentInsert = "INSERT INTO feishu_directory_department(open_department_id,name,parent_open_department_id,sort_order,status,member_count,snapshot_run_id,context,observed_at) VALUES (?,?,?,?,?,?,?,?,?)";
List<Object[]> departmentArgs = new ArrayList<>(snapshot.departments.size());
for (String id : snapshot.departments) {
FeishuDirectoryClient.Department department = snapshot.departmentDetails.get(id);
if (department == null) {
department = new FeishuDirectoryClient.Department();
department.openDepartmentId = id;
department.name = "0".equals(id) ? "根部门" : "";
department.parentOpenDepartmentId = "0".equals(id) ? "0" : "0";
department.status = "ACTIVE";
}
departmentArgs.add(new Object[]{
bounded(department.openDepartmentId, 64, id), bounded(department.name, 200, ""),
bounded(department.parentOpenDepartmentId, 64, "0"), department.order,
bounded(department.status, 30, "ACTIVE"), memberCounts.containsKey(id) ? memberCounts.get(id) : 0,
run.runId, context, observedAt});
}
if (!departmentArgs.isEmpty()) jdbc.batchUpdate(departmentInsert, departmentArgs);
String userInsert = "INSERT INTO feishu_directory_user(open_id,user_id,name,employee_no,email,mobile,job_title,employee_type,avatar_url,employment_status,eligible,snapshot_run_id,context,observed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
List<Object[]> userArgs = new ArrayList<>(snapshot.users.size());
for (Map.Entry<String, JsonNode> entry : snapshot.users.entrySet()) {
JsonNode node = entry.getValue();
String openId = FeishuDirectoryClient.requiredIdentity(node, "open_id");
String userId = FeishuDirectoryClient.requiredIdentity(node, "user_id");
FeishuDirectoryClient.UserSummary summary = snapshot.userSummaries.get(entry.getKey());
if (summary == null) summary = FeishuDirectoryClient.UserSummary.from(node, "0");
String name = bounded(summary.name, 100, "");
if (name.isEmpty()) name = bounded(openId, 100, "");
String employeeNo = bounded(summary.employeeNo, 50, "");
userArgs.add(new Object[]{
bounded(openId, 100, openId), bounded(userId, 100, userId), name, employeeNo,
bounded(summary.email, 320, ""), bounded(summary.mobile, 50, ""),
bounded(summary.jobTitle, 200, ""), summary.employeeType,
bounded(summary.avatarUrl, 500, ""), bounded(summary.employmentStatus, 32, "UNKNOWN"),
FeishuDirectoryClient.eligible(node), run.runId, context, observedAt});
}
if (!userArgs.isEmpty()) jdbc.batchUpdate(userInsert, userArgs);
String relationshipInsert = "INSERT INTO feishu_directory_user_department(open_id,open_department_id) VALUES (?,?)";
List<Object[]> relationshipArgs = new ArrayList<>();
for (Map.Entry<String,List<String>> relationship : relationships.entrySet()) {
String openId = FeishuDirectoryClient.requiredIdentity(snapshot.users.get(relationship.getKey()), "open_id");
for (String departmentId : relationship.getValue())
relationshipArgs.add(new Object[]{openId, departmentId});
}
if (!relationshipArgs.isEmpty()) jdbc.batchUpdate(relationshipInsert, relationshipArgs);
}
private boolean normalizedSchemaAvailable() {
try {
Set<String> columns = new HashSet<>();
// INFORMATION_SCHEMA is present on PostgreSQL and H2. This is a
// metadata read, not a probe against an optional table/column, so a
// V10/V11 absence cannot put a PostgreSQL connection in the failed
// transaction state. The caller invokes it outside publication.
jdbc.query("SELECT LOWER(table_name),LOWER(column_name) FROM information_schema.columns "
+ "WHERE LOWER(table_name) IN ('feishu_directory_department','feishu_directory_user',"
+ "'feishu_directory_user_department')",
(org.springframework.jdbc.core.RowCallbackHandler) result ->
columns.add(result.getString(1) + ":" + result.getString(2)));
return hasColumns(columns, "feishu_directory_department",
"open_department_id", "name", "parent_open_department_id", "sort_order",
"status", "member_count", "snapshot_run_id", "context", "observed_at")
&& hasColumns(columns, "feishu_directory_user",
"open_id", "user_id", "name", "employee_no", "eligible", "snapshot_run_id",
"context", "observed_at", "email", "mobile", "job_title", "employee_type",
"avatar_url", "employment_status")
&& hasColumns(columns, "feishu_directory_user_department", "open_id", "open_department_id");
} catch (Exception ignored) {
return false;
}
}
private static boolean hasColumns(Set<String> columns, String table, String... required) {
Set<String> missing = new HashSet<>();
for (String column : required) missing.add(column.toLowerCase(Locale.ROOT));
for (String value : columns)
if (value.startsWith(table.toLowerCase(Locale.ROOT) + ":"))
missing.remove(value.substring(value.indexOf(':') + 1));
return missing.isEmpty();
}
private List<String> normalizedDepartmentIds(FeishuDirectoryClient.Snapshot snapshot,
FeishuDirectoryClient.UserSummary summary) {
LinkedHashSet<String> ids = new LinkedHashSet<>();
for (String id : summary.departmentIds)
if (id != null && snapshot.departments.contains(id.trim())) ids.add(id.trim());
if (ids.isEmpty() && snapshot.departments.contains("0")) ids.add("0");
return new ArrayList<>(ids);
}
private static String bounded(String value, int maxLength, String fallback) {
String result = value == null ? fallback : value.trim();
return result.length() <= maxLength ? result : result.substring(0, maxLength);
}
private static String safeDiagnostic(Throwable ex) {
Throwable current = ex;
for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) {
if (current instanceof FeishuTenantTokenService.DiagnosticFailure) {
String value = ((FeishuTenantTokenService.DiagnosticFailure) current).getDiagnosticCode();
if (value != null && value.matches("CONFIGURATION_MISSING|CONFIGURATION_UNAVAILABLE"
+ "|SYNC_DISABLED|DIRECTORY_UNAVAILABLE|DIRECTORY_CONTEXT_CHANGED|DIRECTORY_OWNERSHIP_LOST"
+ "|DIRECTORY_(?:DEPARTMENT_STATUS_INVALID|IDENTITY_INVALID|DEPARTMENT_PAGE_INVALID"
+ "|USER_PAGE_INVALID|DEPARTMENT_ITEM_INVALID|USER_ITEM_INVALID"
+ "|DEPARTMENT_ITEMS_INVALID|USER_ITEMS_INVALID"
+ "|DEPARTMENT_ITEMS_INVALID_MISSING|USER_ITEMS_INVALID_MISSING"
+ "|DEPARTMENT_ITEMS_INVALID_TYPE_INVALID|USER_ITEMS_INVALID_TYPE_INVALID"
+ "|DEPARTMENT_ITEMS_INVALID_PAGE_TOO_LARGE|USER_ITEMS_INVALID_PAGE_TOO_LARGE"
+ "|DEPARTMENT_HAS_MORE_INVALID|USER_HAS_MORE_INVALID"
+ "|DEPARTMENT_PAGE_TOKEN_INVALID|USER_PAGE_TOKEN_INVALID|LIMIT_EXCEEDED|RESPONSE_INVALID|REQUEST_FAILED|INTERRUPTED"
+ "|RATE_LIMIT_EXHAUSTED"
+ "|DEADLINE|WORKER_FAILED|WORKER_UNAVAILABLE)"
+ "|TOKEN_(?:CONTEXT_MISSING|RESPONSE_INVALID|REQUEST_FAILED)"
+ "|FEISHU_CODE_43010|FEISHU_CODE_[1-9][0-9]{0,8}|HTTP_STATUS_[1-5][0-9]{2}")) return value;
}
}
return null;
}
private static String failureMessage(String diagnostic) {
String suffix = diagnostic == null ? "" : " Remote Feishu diagnostic: " + diagnostic + ".";
return "Directory sync failed; previous snapshot retained. Check Feishu contact permissions, app visibility and configuration. "
+ "目录同步失败,已保留上一次快照;请检查飞书通讯录权限、应用可见范围和配置。" + suffix;
}
@javax.annotation.PostConstruct
public void initializeState() {
try { jdbc.update("INSERT INTO feishu_directory_state(id) SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM feishu_directory_state WHERE id=1)"); }
catch (org.springframework.dao.DuplicateKeyException ignored) { /* Another instance initialized the singleton. */ }
}
private void acquire(Run run) {
tx.execute(s -> {
Map<String,Object> state = lock();
Timestamp lease = (Timestamp) state.get("lease_until");
if (state.get("owner") != null && lease != null && lease.toInstant().isAfter(Instant.now()))
throw new BusinessException("Directory sync already running", 409);
jdbc.update("UPDATE feishu_directory_state SET owner=?,lease_until=?,context=NULL,last_run=? WHERE id=1", run.runId,
Timestamp.from(Instant.now().plusSeconds(settings.elapsed() + 30)), json(run));
return null;
});
}
private void requireOwner(Run run, String context) {
Map<String,Object> state = lock(); Timestamp lease = (Timestamp) state.get("lease_until");
if (!run.runId.equals(state.get("owner")) || !context.equals(state.get("context")) || lease == null || !lease.toInstant().isAfter(Instant.now()))
throw FeishuTenantTokenService.ownershipLost();
}
private Map<String,Object> lock() { return com.finance.system.service.FeishuDirectoryLock.acquire(jdbc); }
private void apply(FeishuDirectoryClient.Snapshot snapshot, Run run, String context) {
Counts counts = run.counts; counts.departments = snapshot.departments.size(); counts.usersSeen = snapshot.users.size();
// The publication transaction is also the fencing boundary. Load the
// account view once while that boundary is held, then resolve every
// directory identity from these exact-value maps. In particular, do
// not use a user_id-only row as an account match: user_id is tenant
// scoped and its provenance is unknown on legacy rows.
List<SysUser> existingUsers = users.findAll();
Map<String, SysUser> byOpenId = new HashMap<>();
Map<String, SysUser> byUserId = new HashMap<>();
Map<String, SysUser> byEmployeeNo = new HashMap<>();
for (SysUser existing : existingUsers) {
if (existing.getFeishuOpenId() != null) byOpenId.put(existing.getFeishuOpenId(), existing);
if (existing.getFeishuUserId() != null) byUserId.put(existing.getFeishuUserId(), existing);
if (existing.getEmployeeNo() != null) byEmployeeNo.put(existing.getEmployeeNo(), existing);
}
List<SysUser> newUsers = new ArrayList<>();
List<Object[]> statusUpdates = new ArrayList<>();
List<SysUser> statusUsers = new ArrayList<>();
Set<String> userIds = new HashSet<>();
Instant started = Instant.parse(run.startedAt);
for (JsonNode node : snapshot.users.values()) {
String open = FeishuDirectoryClient.requiredIdentity(node, "open_id"), id = FeishuDirectoryClient.requiredIdentity(node, "user_id");
if (!userIds.add(id)) throw new BusinessException("Conflicting directory identities", 409);
SysUser a = byOpenId.get(open), b = byUserId.get(id);
if (a != null && b != null && !a.getId().equals(b.getId())) throw new BusinessException("Conflicting account binding", 409);
// user_id is tenant-scoped. A userId-only legacy row has unknown provenance.
if (a == null && b != null) throw new BusinessException("Operator-verified open_id binding required", 409);
SysUser user = a;
boolean existingUserId = user != null && user.getFeishuUserId() != null
&& !user.getFeishuUserId().trim().isEmpty();
if (user != null && ((user.getFeishuOpenId() != null && !open.equals(user.getFeishuOpenId()))
|| (existingUserId && !id.equals(user.getFeishuUserId())))) throw new BusinessException("Conflicting account binding", 409);
boolean eligible = FeishuDirectoryClient.eligible(node);
if (eligible) counts.eligible++; else counts.excluded++;
if (user == null && !eligible) continue;
if (user == null) {
user = new SysUser(); user.setStatus("ACTIVE"); user.setUserType("EMPLOYEE");
String number = node.path("employee_no").asText("");
if (number.trim().isEmpty() || number.length() > 50 || byEmployeeNo.containsKey(number)) {
do { number = "FS-" + UUID.randomUUID(); }
while (byEmployeeNo.containsKey(number));
}
String name = node.path("name").isTextual() ? node.path("name").asText().trim() : "";
if (name.isEmpty()) name = id;
if (name.length() > 100) name = name.substring(0, 100);
user.setEmployeeNo(number); user.setRealName(name); counts.created++;
byEmployeeNo.put(number, user);
newUsers.add(user);
} else counts.updated++;
if (user.getId() == null) {
user.setFeishuOpenId(open); user.setFeishuUserId(id);
// Keep the in-memory account view in sync while building the
// batch. The old per-user persistence path made a newly
// created identity visible to the next lookup; without these
// entries, duplicate identities in one snapshot are deferred
// to the database unique constraint.
byOpenId.put(open, user);
byUserId.put(id, user);
}
// A definitive live denial observed after traversal began must not be undone by an older page.
boolean newerDenial = context.equals(user.getDirectoryContext()) && "INELIGIBLE".equals(user.getDirectoryStatus())
&& user.getDirectoryVerifiedAt() != null && user.getDirectoryVerifiedAt().isAfter(started);
String status = eligible && !newerDenial ? "ELIGIBLE" : "INELIGIBLE";
if (!"ELIGIBLE".equals(status)) counts.ineligible++;
// Manual status, roles, groups, department/financial identifiers and existing profile are untouched.
statusUpdates.add(new Object[]{open, id, status, context, Timestamp.from(Instant.now()), run.runId,
null, open, id});
statusUsers.add(user);
}
// IDENTITY rows need to be inserted before the status batch so their
// generated IDs are available. This is one repository flush rather
// than one flush per directory user.
if (!newUsers.isEmpty()) {
users.saveAll(newUsers);
users.flush();
}
for (int i = 0; i < statusUpdates.size(); i++) statusUpdates.get(i)[6] = statusUsers.get(i).getId();
String statusSql = "UPDATE sys_user SET feishu_open_id=?,feishu_user_id=?,directory_status=?,directory_context=?,directory_verified_at=?,directory_last_seen_run_id=? WHERE id=? AND feishu_open_id=? AND (feishu_user_id IS NULL OR TRIM(feishu_user_id)='' OR feishu_user_id=?)";
if (!statusUpdates.isEmpty()) {
int[] changed = jdbc.batchUpdate(statusSql, statusUpdates);
for (int count : changed)
if (count != 1) throw new BusinessException("Conflicting account binding", 409);
}
counts.outOfScope = jdbc.update("UPDATE sys_user SET directory_status='OUT_OF_SCOPE',directory_verified_at=? WHERE directory_context=? AND directory_last_seen_run_id IS NOT NULL AND directory_last_seen_run_id<>?",
Timestamp.from(Instant.now()), context, run.runId);
}
public Map<String,Object> status() {
Map<String,Object> state = jdbc.queryForMap("SELECT * FROM feishu_directory_state WHERE id=1");
String context = null; try { context = tokens.capture().fingerprint; } catch (Exception ignored) { }
Timestamp success = (Timestamp) state.get("last_successful_at"), lease = (Timestamp) state.get("lease_until");
Instant expires = success == null ? null : success.toInstant().plusSeconds(settings.statusAge());
String snapshot = context == null ? "UNAVAILABLE" : success == null ? "NEVER_SYNCED"
: !context.equals(state.get("successful_context")) ? "CONTEXT_CHANGED" : expires.isAfter(Instant.now()) ? "FRESH" : "STALE";
Map<String,Object> result = new LinkedHashMap<>(); result.put("configured", context != null);
result.put("running", state.get("owner") != null && lease != null && lease.toInstant().isAfter(Instant.now()));
result.put("snapshotState", snapshot); result.put("maxStatusAgeSeconds", settings.statusAge());
result.put("lastSuccessfulRunId", state.get("last_successful_run_id")); result.put("lastSuccessfulAt", success == null ? null : success.toInstant().toString());
result.put("snapshotExpiresAt", expires == null ? null : expires.toString());
Run last = parse((String) state.get("last_run"));
if (last != null && "RUNNING".equals(last.state) && !Boolean.TRUE.equals(result.get("running"))) {
last.state = "FAILED"; last.finishedAt = lease == null ? Instant.now().toString() : lease.toInstant().toString();
last.errorCode = "LEASE_EXPIRED"; last.errorMessage = "Directory sync lease expired; previous snapshot retained.";
}
result.put("lastRun", last); return result;
}
/**
* Returns the last atomically published organization snapshot. This method
* deliberately does not call Feishu and does not return stored raw payloads.
*/
public Map<String,Object> organization() {
Map<String,Object> result = emptyOrganization("UNAVAILABLE", null);
try {
// Configuration writes and snapshot publication take the same
// singleton lock and keep it until commit. Capture the context and
// read the complete published snapshot under that lock so this
// request cannot combine one tenant's context with another
// tenant's rows. This transaction never calls Feishu.
Map<String,Object> captured = tx.execute(s -> {
Map<String,Object> state = lock();
Timestamp success = (Timestamp) state.get("last_successful_at");
String currentContext = null;
try { currentContext = tokens.capture().fingerprint; } catch (Exception ignored) { }
String stateName = snapshotState(success, state.get("successful_context"), currentContext);
Map<String,Object> organization = emptyOrganization(stateName,
success == null ? null : success.toInstant().toString());
// Only a fresh snapshot is safe to expose. In particular,
// context changes and expiry must not fall through to either
// normalized rows or the legacy JSON fallback.
if (!"FRESH".equals(stateName)) return organization;
Map<String,Object> normalized = normalizedOrganization(String.valueOf(state.get("last_successful_run_id")));
if (normalized != null && !((List<?>) normalized.get("departments")).isEmpty()) {
organization.put("departments", normalized.get("departments"));
organization.put("users", normalized.get("users"));
return organization;
}
if (state.get("last_snapshot") == null) return organization;
JsonNode snapshot = safeReadSnapshot((String) state.get("last_snapshot"));
if (snapshot == null || !snapshot.isObject()) return organization;
organization.put("departments", safeDepartments(snapshot.path("departments")));
organization.put("users", safeUsers(snapshot.path("users")));
updateMemberCounts((List<Map<String,Object>>) organization.get("departments"),
(List<Map<String,Object>>) organization.get("users"));
return organization;
});
return captured == null ? result : captured;
} catch (Exception ex) {
// Do not expose SQL/parser details: old installations and corrupt
// snapshots must degrade to an empty, safe response.
log.warn("Feishu organization snapshot could not be read");
result.put("departments", new ArrayList<Map<String,Object>>());
result.put("users", new ArrayList<Map<String,Object>>());
return result;
}
}
private JsonNode safeReadSnapshot(String value) {
try { return value == null ? null : mapper.readTree(value); }
catch (Exception ignored) { return null; }
}
private Map<String,Object> normalizedOrganization(String runId) {
try {
// Do not issue a SELECT against optional V10/V11 objects until the
// metadata check says all of them exist. In PostgreSQL a caught
// undefined-table/column error still aborts the transaction, which
// would otherwise prevent the V9 snapshot fallback below from
// being read on the same connection.
if (!normalizedSchemaAvailable()) return null;
List<Map<String,Object>> departments = new ArrayList<>();
List<Map<String,Object>> departmentRows = jdbc.queryForList(
"SELECT open_department_id,name,parent_open_department_id,sort_order,member_count "
+ "FROM feishu_directory_department WHERE snapshot_run_id=? "
+ "ORDER BY sort_order,open_department_id", runId);
for (Map<String,Object> row : departmentRows) {
Map<String,Object> department = new LinkedHashMap<>();
department.put("id", stringValue(row.get("open_department_id")));
department.put("name", stringValue(row.get("name")));
department.put("parentId", stringValue(row.get("parent_open_department_id")));
// BIGINT values must cross the public JSON boundary as decimal
// text. JavaScript numbers cannot represent every long exactly.
department.put("order", Long.toString(longValue(row.get("sort_order"))));
department.put("memberCount", Math.max(0, integerValue(row.get("member_count"))));
departments.add(department);
}
Map<String,List<String>> userDepartments = new HashMap<>();
List<Map<String,Object>> relationRows = jdbc.queryForList(
"SELECT open_id,open_department_id FROM feishu_directory_user_department "
+ "WHERE open_id IN (SELECT open_id FROM feishu_directory_user WHERE snapshot_run_id=?) "
+ "ORDER BY open_id,open_department_id", runId);
for (Map<String,Object> row : relationRows) {
String openId = stringValue(row.get("open_id"));
List<String> ids = userDepartments.get(openId);
if (ids == null) { ids = new ArrayList<>(); userDepartments.put(openId, ids); }
String departmentId = stringValue(row.get("open_department_id"));
if (!ids.contains(departmentId)) ids.add(departmentId);
}
List<Map<String,Object>> users = new ArrayList<>();
List<Map<String,Object>> userRows = jdbc.queryForList(
"SELECT open_id,user_id,name,email,mobile,job_title,employee_type,avatar_url,employment_status "
+ "FROM feishu_directory_user "
+ "WHERE snapshot_run_id=? ORDER BY open_id", runId);
for (Map<String,Object> row : userRows) {
Map<String,Object> user = new LinkedHashMap<>();
String openId = stringValue(row.get("open_id"));
user.put("openId", openId);
user.put("userId", stringValue(row.get("user_id")));
user.put("name", stringValue(row.get("name")));
user.put("email", stringValue(row.get("email")));
user.put("mobile", stringValue(row.get("mobile")));
user.put("jobTitle", stringValue(row.get("job_title")));
user.put("employeeType", nullableIntegerValue(row.get("employee_type")));
user.put("avatarUrl", stringValue(row.get("avatar_url")));
user.put("employmentStatus", stringValue(row.get("employment_status")));
List<String> ids = userDepartments.get(openId);
user.put("departmentIds", ids == null ? new ArrayList<String>() : ids);
users.add(user);
}
// Recalculate from the published tree and relations rather than
// trusting a direct-membership count left by an older publisher.
updateMemberCounts(departments, users);
Map<String,Object> normalized = new LinkedHashMap<>();
normalized.put("departments", departments);
normalized.put("users", users);
return normalized;
} catch (Exception ignored) {
// V10 may not have been applied yet, or a partial historical
// installation may not have normalized rows. The caller falls
// back to the V9 allow-listed JSON snapshot.
return null;
}
}
private static String stringValue(Object value) {
return value == null ? "" : String.valueOf(value);
}
private static int integerValue(Object value) {
return value instanceof Number ? ((Number) value).intValue() : 0;
}
private static long longValue(Object value) {
if (value == null) return 0L;
try { return Long.parseLong(String.valueOf(value).trim()); }
catch (NumberFormatException ignored) { return 0L; }
}
private static Integer nullableIntegerValue(Object value) {
return value instanceof Number ? ((Number) value).intValue() : null;
}
private Map<String,Object> emptyOrganization(String state, String at) {
Map<String,Object> result = new LinkedHashMap<>();
result.put("snapshotState", state);
result.put("lastSuccessfulAt", at);
result.put("departments", new ArrayList<Map<String,Object>>());
result.put("users", new ArrayList<Map<String,Object>>());
return result;
}
private String snapshotState(Timestamp success, Object successfulContext, String currentContext) {
if (currentContext == null) return "UNAVAILABLE";
if (success == null) return "NEVER_SYNCED";
if (!currentContext.equals(successfulContext)) return "CONTEXT_CHANGED";
return success.toInstant().plusSeconds(settings.statusAge()).isAfter(Instant.now()) ? "FRESH" : "STALE";
}
private List<Map<String,Object>> safeDepartments(JsonNode nodes) {
List<Map<String,Object>> departments = new ArrayList<>();
if (!nodes.isArray()) return departments;
for (JsonNode node : nodes) {
if (!node.isObject()) continue;
Map<String,Object> department = new LinkedHashMap<>();
department.put("id", text(node, "id"));
department.put("name", text(node, "name"));
department.put("parentId", text(node, "parentId"));
// Accept both the current persisted string form and older numeric
// snapshots, but always expose the bounded long as decimal text.
department.put("order", Long.toString(longNumber(node, "order")));
department.put("memberCount", Math.max(0, integerNumber(node, "memberCount")));
departments.add(department);
}
return departments;
}
private List<Map<String,Object>> safeUsers(JsonNode nodes) {
List<Map<String,Object>> users = new ArrayList<>();
if (!nodes.isArray()) return users;
for (JsonNode node : nodes) {
if (!node.isObject()) continue;
Map<String,Object> user = new LinkedHashMap<>();
user.put("openId", text(node, "openId"));
user.put("userId", text(node, "userId"));
user.put("name", text(node, "name"));
user.put("email", text(node, "email", 320));
user.put("mobile", text(node, "mobile", 50));
user.put("jobTitle", text(node, "jobTitle", 200));
user.put("employeeType", nullableNumber(node, "employeeType"));
user.put("avatarUrl", text(node, "avatarUrl", 500));
user.put("employmentStatus", text(node, "employmentStatus", 32));
List<String> ids = new ArrayList<>();
JsonNode departmentIds = node.path("departmentIds");
if (departmentIds.isArray()) for (JsonNode id : departmentIds)
if (id.isTextual() && !id.asText().trim().isEmpty()) ids.add(id.asText());
user.put("departmentIds", ids);
users.add(user);
}
return users;
}
private void updateMemberCounts(List<Map<String,Object>> departments, List<Map<String,Object>> users) {
Map<String,String> parents = new HashMap<>();
for (Map<String,Object> department : departments)
parents.put(stringValue(department.get("id")), stringValue(department.get("parentId")));
Map<String,Set<String>> members = new HashMap<>();
int row = 0;
for (Map<String,Object> user : users) {
String employee = stringValue(user.get("openId"));
if (employee.isEmpty()) employee = "\u0000" + row;
Object ids = user.get("departmentIds");
if (ids instanceof Iterable) {
LinkedHashSet<String> selected = new LinkedHashSet<>();
for (Object id : (Iterable<?>) ids) if (id != null) selected.add(String.valueOf(id));
for (String id : selected) addMemberAndAncestors(id, employee, parents, members);
}
row++;
}
for (Map<String,Object> department : departments) {
Set<String> departmentMembers = members.get(stringValue(department.get("id")));
department.put("memberCount", departmentMembers == null ? 0 : departmentMembers.size());
}
}
private static String text(JsonNode node, String key) {
JsonNode value = node.path(key);
return value.isTextual() ? value.asText() : "";
}
private static String text(JsonNode node, String key, int maxLength) {
return bounded(text(node, key), maxLength, "");
}
private static int integerNumber(JsonNode node, String key) {
JsonNode value = node.path(key);
return value.isIntegralNumber() ? value.asInt() : 0;
}
private static long longNumber(JsonNode node, String key) {
JsonNode value = node.path(key);
if (value.isIntegralNumber()) {
try { return value.bigIntegerValue().longValueExact(); }
catch (ArithmeticException ignored) { return 0L; }
}
if (!value.isTextual()) return 0L;
String text = value.asText().trim();
// A long has at most 20 decimal characters including its sign. Reject
// longer values before parsing so untrusted snapshot data is bounded.
if (text.length() == 0 || text.length() > 20) return 0L;
try { return Long.parseLong(text); }
catch (NumberFormatException ignored) { return 0L; }
}
private static Integer nullableNumber(JsonNode node, String key) {
JsonNode value = node.path(key);
return value.isIntegralNumber() ? value.asInt() : null;
}
private Map<String,Integer> normalizedMemberCounts(FeishuDirectoryClient.Snapshot snapshot,
Map<String,List<String>> relationships) {
Map<String,String> parents = new HashMap<>();
for (String id : snapshot.departments) {
FeishuDirectoryClient.Department department = snapshot.departmentDetails.get(id);
String parent = department == null ? ("0".equals(id) ? "0" : "0")
: department.parentOpenDepartmentId;
parents.put(id, parent);
}
Map<String,Set<String>> members = new HashMap<>();
for (Map.Entry<String,List<String>> relationship : relationships.entrySet()) {
JsonNode node = snapshot.users.get(relationship.getKey());
String employee = FeishuDirectoryClient.requiredIdentity(node, "open_id");
for (String departmentId : new LinkedHashSet<>(relationship.getValue()))
addMemberAndAncestors(departmentId, employee, parents, members);
}
Map<String,Integer> counts = new HashMap<>();
for (Map.Entry<String,Set<String>> entry : members.entrySet())
counts.put(entry.getKey(), entry.getValue().size());
return counts;
}
/** Walk only known tree nodes; visited breaks malformed parent cycles safely. */
private static void addMemberAndAncestors(String departmentId, String employee,
Map<String,String> parents,
Map<String,Set<String>> members) {
Set<String> visited = new HashSet<>();
String current = departmentId;
while (current != null && parents.containsKey(current) && visited.add(current)) {
Set<String> departmentMembers = members.get(current);
if (departmentMembers == null) {
departmentMembers = new LinkedHashSet<>();
members.put(current, departmentMembers);
}
departmentMembers.add(employee);
String parent = parents.get(current);
if (parent == null || parent.equals(current)) break;
current = parent;
}
}
private String snapshotJson(FeishuDirectoryClient.Snapshot snapshot) {
ObjectNode root = mapper.createObjectNode();
ArrayNode departments = root.putArray("departments");
for (String id : snapshot.departments) {
FeishuDirectoryClient.Department source = snapshot.departmentDetails.get(id);
if (source == null) {
source = new FeishuDirectoryClient.Department();
source.openDepartmentId = id;
source.name = "0".equals(id) ? "根部门" : "";
source.parentOpenDepartmentId = "0".equals(id) ? "0" : "0";
source.status = "ACTIVE";
}
ObjectNode department = departments.addObject();
department.put("id", nonNull(source.openDepartmentId, id));
department.put("name", nonNull(source.name, ""));
department.put("parentId", nonNull(source.parentOpenDepartmentId, "0"));
department.put("order", Long.toString(source.order));
department.put("status", nonNull(source.status, "ACTIVE"));
department.put("memberCount", 0);
}
ArrayNode users = root.putArray("users");
for (Map.Entry<String, JsonNode> entry : snapshot.users.entrySet()) {
FeishuDirectoryClient.UserSummary source = snapshot.userSummaries.get(entry.getKey());
if (source == null) source = FeishuDirectoryClient.UserSummary.from(entry.getValue(), "0");
ObjectNode user = users.addObject();
user.put("openId", nonNull(source.openId, entry.getKey()));
user.put("userId", nonNull(source.userId, ""));
user.put("name", nonNull(source.name, ""));
user.put("email", bounded(source.email, 320, ""));
user.put("mobile", bounded(source.mobile, 50, ""));
user.put("jobTitle", bounded(source.jobTitle, 200, ""));
if (source.employeeType == null) user.putNull("employeeType");
else user.put("employeeType", source.employeeType);
user.put("avatarUrl", bounded(source.avatarUrl, 500, ""));
user.put("employmentStatus", bounded(source.employmentStatus, 32, "UNKNOWN"));
ArrayNode ids = user.putArray("departmentIds");
for (String id : source.departmentIds)
if (id != null && snapshot.departments.contains(id.trim())) ids.add(id.trim());
if (ids.size() == 0 && snapshot.departments.contains("0")) ids.add("0");
}
fillSnapshotMemberCounts(departments, users);
return root.toString();
}
private static void fillSnapshotMemberCounts(ArrayNode departments, ArrayNode users) {
Map<String,String> parents = new HashMap<>();
for (JsonNode department : departments)
parents.put(department.path("id").asText(), department.path("parentId").asText());
Map<String,Set<String>> members = new HashMap<>();
int row = 0;
for (JsonNode user : users) {
String employee = user.path("openId").asText();
if (employee.isEmpty()) employee = "\u0000" + row;
LinkedHashSet<String> selected = new LinkedHashSet<>();
for (JsonNode id : user.path("departmentIds")) selected.add(id.asText());
for (String id : selected) addMemberAndAncestors(id, employee, parents, members);
row++;
}
for (JsonNode department : departments) {
ObjectNode value = (ObjectNode) department;
String id = value.path("id").asText();
Set<String> departmentMembers = members.get(id);
value.put("memberCount", departmentMembers == null ? 0 : departmentMembers.size());
}
}
private static String nonNull(String value, String fallback) {
return value == null ? fallback : value;
}
private String json(Run run) { try { return mapper.writeValueAsString(run); } catch (Exception e) { throw new IllegalStateException("Cannot encode directory run"); } }
private Run parse(String value) { try { return value == null ? null : mapper.readValue(value, Run.class); } catch (Exception e) { throw new IllegalStateException("Cannot decode directory run"); } }
@Data public static class Run {
private String runId, trigger, state = "RUNNING", startedAt, finishedAt;
private boolean complete, applied;
private Counts counts = new Counts();
private String errorCode, errorMessage;
}
@Data public static class Counts {
private int departments, usersSeen, excluded, created, updated, outOfScope;
@JsonIgnore private int eligible;
@JsonIgnore private int ineligible;
// Qualification counters are database/operator telemetry only. They
// must never be part of the public sync/status payload.
@JsonIgnore
public int getEligible() { return eligible; }
@JsonIgnore
public int getIneligible() { return ineligible; }
}
}
@@ -0,0 +1,41 @@
package com.finance.system.adapter.feishu;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "feishu.directory")
public class FeishuDirectorySettings {
private boolean bootstrapSyncOnStartup = false;
// Increment whenever application visibility changes outside this system.
private String credentialRevision = "1";
private long maxStatusAgeSeconds = 86400;
private int maxPages = 2000;
private int maxUsers = 50000;
private int maxDepartments = 5000;
private long maxElapsedSeconds = 120;
private String departmentIdType = "open_department_id";
private int directoryConcurrency = 4;
private int maxRetries = 3;
private int requestsPerSecond = 45;
private int requestsPerMinute = 900;
public long statusAge() { return Math.max(1, Math.min(86400, maxStatusAgeSeconds)); }
public long elapsed() { return Math.max(1, Math.min(300, maxElapsedSeconds)); }
/** Contact v3 snapshots are keyed by the immutable open department id. */
public String departmentIdType() { return "open_department_id"; }
public String getDepartmentIdType() { return departmentIdType(); }
public int directoryConcurrency() { return Math.max(1, Math.min(8, directoryConcurrency)); }
public int getDirectoryConcurrency() { return directoryConcurrency(); }
/** Compatibility with the original setting name; both settings control the same bound. */
@Deprecated public int userFetchConcurrency() { return directoryConcurrency(); }
@Deprecated public int getUserFetchConcurrency() { return directoryConcurrency(); }
@Deprecated public void setUserFetchConcurrency(int value) { this.directoryConcurrency = value; }
public int maxRetries() { return Math.max(0, Math.min(5, maxRetries)); }
public int getMaxRetries() { return maxRetries(); }
public int requestsPerSecond() { return Math.max(1, Math.min(50, requestsPerSecond)); }
public int getRequestsPerSecond() { return requestsPerSecond(); }
public int requestsPerMinute() { return Math.max(1, Math.min(1000, requestsPerMinute)); }
public int getRequestsPerMinute() { return requestsPerMinute(); }
}
@@ -0,0 +1,96 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.service.FeishuDirectoryLock;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Objects;
/** Login's commit point. Never merge an account loaded before the remote OAuth exchange.
* Only profile, a missing counterpart of an EXACT open_id binding, and last-login
* columns can be written. Role/status and directory observations are never written here.
*/
@Service
public class FeishuLoginPersistenceService {
private final JdbcTemplate jdbc;
private final EntityManager em;
private final SysUserRepository users;
private final FeishuDirectoryAccessService access;
private final TransactionTemplate tx;
public FeishuLoginPersistenceService(JdbcTemplate jdbc, EntityManager em, SysUserRepository users,
FeishuDirectoryAccessService access, FeishuTenantTokenService tokens, PlatformTransactionManager manager) {
this.jdbc = jdbc; this.em = em; this.users = users; this.access = access;
tx = new TransactionTemplate(manager); tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tx.setTimeout(30);
tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
}
/**
* Complete OAuth login without consulting the directory snapshot. The
* three-argument overload remains for callers compiled against the former
* API; its context argument is intentionally ignored.
*/
public SysUser completeOAuth(Long id, FeishuUserInfo info) {
return tx.execute(s -> {
if (info == null || info.getOpenId() == null || info.getOpenId().trim().isEmpty()) throw denied();
String openId = info.getOpenId().trim();
validate(openId, 100);
// Serialize OAuth finalization with directory/configuration writes;
// the lock protects identity/profile consistency even though the
// OAuth admission decision no longer reads directory state.
FeishuDirectoryLock.acquire(jdbc);
SysUser fresh = locked(id);
// open_id is the only Feishu identity used for account matching.
// Never replace it or adopt an account using user_id alone.
if (!Objects.equals(fresh.getFeishuOpenId(), openId)) throw denied();
String counterpart = info.getUserId() == null ? null : info.getUserId().trim();
if (counterpart != null && counterpart.isEmpty()) counterpart = null;
String existingUserId = fresh.getFeishuUserId();
if (counterpart != null && existingUserId != null && !existingUserId.trim().isEmpty()
&& !counterpart.equals(existingUserId)) throw denied();
if (counterpart != null && jdbc.queryForObject("SELECT COUNT(*) FROM sys_user WHERE feishu_user_id=? AND id<>?", Integer.class, counterpart, id) != 0) throw denied();
String name = info.getName() == null || info.getName().trim().isEmpty() ? fresh.getRealName() : info.getName();
validate(name, 100); validate(info.getAvatarUrl(), 500); validate(info.getEmail(), 200); validate(info.getMobile(), 20); validate(counterpart, 100);
jdbc.update("UPDATE sys_user SET real_name=?,avatar_url=?,email=?,mobile=?,feishu_user_id=CASE WHEN feishu_user_id IS NULL OR TRIM(feishu_user_id)='' THEN ? ELSE feishu_user_id END,last_login_at=? WHERE id=?",
name, keepExisting(info.getAvatarUrl(), fresh.getAvatarUrl()),
keepExisting(info.getEmail(), fresh.getEmail()), keepExisting(info.getMobile(), fresh.getMobile()),
counterpart, Timestamp.valueOf(LocalDateTime.now()), id);
em.refresh(fresh); // return current role/status, NOT a stale pre-HTTP object
return fresh;
});
}
/** @deprecated Directory context is no longer part of OAuth admission. */
@Deprecated
public SysUser completeOAuth(Long id, FeishuUserInfo info, String verifiedContext) {
return completeOAuth(id, info);
}
public SysUser completeLocal(Long id) {
return tx.execute(s -> {
FeishuDirectoryLock.acquire(jdbc);
SysUser fresh = locked(id); access.requireAllowed(fresh);
jdbc.update("UPDATE sys_user SET last_login_at=? WHERE id=?", Timestamp.valueOf(LocalDateTime.now()), id);
em.refresh(fresh); return fresh;
});
}
private SysUser locked(Long id) {
SysUser fresh = users.findById(id).orElseThrow(FeishuLoginPersistenceService::denied);
em.refresh(fresh, LockModeType.PESSIMISTIC_WRITE);
if (!"ACTIVE".equalsIgnoreCase(fresh.getStatus())) throw denied();
return fresh;
}
private static void validate(String value, int length) { if (value != null && value.length() > length) throw denied(); }
private static String keepExisting(String incoming, String existing) {
return incoming == null || incoming.trim().isEmpty() ? existing : incoming;
}
private static BusinessException denied() { return new BusinessException("Active Feishu identity binding required", 403); }
}
@@ -0,0 +1,121 @@
package com.finance.system.adapter.feishu;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* 飞书消息服务
* 负责:发送审批待办通知、付款结果通知等消息
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class FeishuMessageService {
private final FeishuAuthService feishuAuthService;
private final SysUserRepository sysUserRepository;
private final RestTemplate restTemplate;
private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis";
/**
* 发送审批待办通知
*/
public void sendApprovalNotification(Long approverId, String applicationNo,
String title, String applicantName,
BigDecimal amount, String detailUrl) {
SysUser approver = sysUserRepository.findById(approverId).orElse(null);
if (approver == null || approver.getFeishuOpenId() == null) {
log.warn("审批人未绑定飞书,无法发送通知: userId={}", approverId);
return;
}
String content = buildApprovalCard(applicationNo, title, applicantName, amount, detailUrl);
sendMessage(approver.getFeishuOpenId(), "interactive", content);
}
/**
* 发送付款结果通知
*/
public void sendPaymentNotification(Long userId, String applicationNo,
BigDecimal amount, String paymentStatus, String detailUrl) {
SysUser user = sysUserRepository.findById(userId).orElse(null);
if (user == null || user.getFeishuOpenId() == null) {
log.warn("用户未绑定飞书,无法发送通知: userId={}", userId);
return;
}
String content = buildPaymentCard(applicationNo, amount, paymentStatus, detailUrl);
sendMessage(user.getFeishuOpenId(), "interactive", content);
}
/**
* 发送飞书消息
*/
private void sendMessage(String receiveId, String msgType, String content) {
String token = feishuAuthService.getTenantAccessToken();
String url = FEISHU_OPEN_API + "/im/v1/messages?receive_id_type=open_id";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("receive_id", receiveId);
requestBody.put("msg_type", msgType);
requestBody.put("content", content);
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<Map> response = restTemplate.exchange(
url, HttpMethod.POST, request, Map.class);
log.info("飞书消息发送成功: receiveId={}, msgType={}", receiveId, msgType);
} catch (Exception e) {
log.error("飞书消息发送失败: receiveId={}", receiveId, e);
throw new BusinessException("发送飞书消息失败");
}
}
/**
* 构建审批待办卡片消息
*/
private String buildApprovalCard(String applicationNo, String title,
String applicantName, BigDecimal amount, String detailUrl) {
return String.format("{\"config\":{\"wide_screen_mode\":true},"
+ "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"📋 报销审批待办\"},\"template\":\"blue\"},"
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您有一笔报销申请需要审批:\\n**单号**:%s\\n**标题**:%s\\n**申请人**:%s\\n**金额**:¥%.2f\"}},"
+ "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"去审批\"},\"type\":\"primary\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}",
applicationNo, title, applicantName, amount, detailUrl);
}
/**
* 构建付款结果卡片消息
*/
private String buildPaymentCard(String applicationNo, BigDecimal amount,
String paymentStatus, String detailUrl) {
String statusText;
switch (paymentStatus) {
case "PAID": statusText = "✅ 已付款"; break;
case "PARTIAL": statusText = "🔄 部分付款"; break;
case "FAILED": statusText = "❌ 付款失败"; break;
default: statusText = "⏳ 处理中";
}
return String.format("{\"config\":{\"wide_screen_mode\":true},"
+ "\"header\":{\"title\":{\"tag\":\"plain_text\",\"content\":\"💰 付款结果通知\"},\"template\":\"green\"},"
+ "\"elements\":[{\"tag\":\"div\",\"text\":{\"tag\":\"lark_md\",\"content\":\"您的报销申请已处理:\\n**单号**:%s\\n**金额**:¥%.2f\\n**状态**:%s\"}},"
+ "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"查看详情\"},\"type\":\"default\",\"multi_url\":{\"url\":\"%s\",\"pc_url\":\"\"}}]}]}",
applicationNo, amount, statusText, detailUrl);
}
}
@@ -0,0 +1,163 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.databind.JsonNode;
import com.finance.system.exception.BusinessException;
import com.finance.system.service.IntegrationConfigReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@Service
public class FeishuTenantTokenService {
static final String API = "https://open.feishu.cn/open-apis";
private static final BigInteger SUCCESS_CODE = BigInteger.ZERO;
private static final BigInteger MAX_DIAGNOSTIC_CODE = BigInteger.valueOf(999999999L);
private final IntegrationConfigReader config;
private final FeishuDirectorySettings settings;
private final RestTemplate http;
@Autowired
public FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings) {
this(config, settings, httpClient());
}
FeishuTenantTokenService(IntegrationConfigReader config, FeishuDirectorySettings settings, RestTemplate http) {
this.config = config; this.settings = settings; this.http = http;
}
private static RestTemplate httpClient() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(3000); factory.setReadTimeout(5000);
return new RestTemplate(factory);
}
public Context capture() {
Map<String,String> values;
try {
values = config.freshFeishu();
} catch (Exception ex) {
// Configuration readers may fail while decrypting persisted secrets. Do
// not let that exception (or its message) cross the adapter boundary.
throw diagnostic("CONFIGURATION_UNAVAILABLE");
}
if (values == null) throw diagnostic("CONFIGURATION_MISSING");
String app = values.get("appId"), secret = values.get("appSecret");
// A disabled integration is deliberately reported as configuration missing,
// while the independent directory-sync switch is reported as SYNC_DISABLED.
// Neither path exposes the configured values.
if (app == null || app.trim().isEmpty() || secret == null || secret.trim().isEmpty()
|| !Boolean.parseBoolean(values.get(IntegrationConfigReader.INTERNAL_ENABLED_KEY)))
throw diagnostic("CONFIGURATION_MISSING");
return new Context(app, secret, fingerprint(app + "\n" + secret
+ "\nroot=0;department_id_type=" + settings.departmentIdType()
+ ";employee_type=1;policy=1\n" + settings.getCredentialRevision()));
}
public boolean syncEnabled() {
Map<String,String> values;
try { values = config.freshFeishu(); }
catch (Exception ex) { throw diagnostic("CONFIGURATION_UNAVAILABLE"); }
return values != null && Boolean.parseBoolean(values.getOrDefault("syncOrgEnabled", "true"));
}
public String getTenantAccessToken() { return token(capture()); }
public String token(Context context) {
if (context == null) throw diagnostic("TOKEN_CONTEXT_MISSING");
Map<String,String> body = new HashMap<>(); body.put("app_id", context.app); body.put("app_secret", context.secret);
try {
JsonNode response = http.postForObject(API + "/auth/v3/tenant_access_token/internal", body, JsonNode.class);
BigInteger responseCode = responseCode(response);
if (responseCode == null) throw diagnostic("TOKEN_RESPONSE_INVALID");
if (!SUCCESS_CODE.equals(responseCode)) {
Long code = safeCode(response);
throw code == null ? diagnostic("TOKEN_RESPONSE_INVALID") : diagnostic("FEISHU_CODE_" + code);
}
if (!response.path("tenant_access_token").isTextual()
|| response.path("tenant_access_token").asText().trim().isEmpty())
throw diagnostic("TOKEN_RESPONSE_INVALID");
return response.path("tenant_access_token").asText();
} catch (DiagnosticFailure ex) {
throw ex;
} catch (org.springframework.web.client.HttpStatusCodeException ex) {
JsonNode response = null;
try { response = readErrorBody(ex.getResponseBodyAsString()); } catch (Exception ignored) { }
Long code = safeCode(response);
if (code != null) throw diagnostic("FEISHU_CODE_" + code);
int status = ex.getStatusCode().value();
if (status >= 100 && status <= 599) throw diagnostic("HTTP_STATUS_" + status);
throw diagnostic("TOKEN_REQUEST_FAILED");
} catch (Exception ex) {
// Never carry an upstream exception across the boundary. It may contain
// credentials, response content, or an arbitrary connector message.
throw diagnostic("TOKEN_REQUEST_FAILED");
}
}
static DiagnosticFailure diagnostic(String code) {
return new DiagnosticFailure(isSafeDiagnostic(code) ? code : "DIRECTORY_UNAVAILABLE");
}
static BusinessException unavailable() { return diagnostic("DIRECTORY_UNAVAILABLE"); }
static DiagnosticFailure syncDisabled() { return diagnostic("SYNC_DISABLED"); }
static DiagnosticFailure contextChanged() { return diagnostic("DIRECTORY_CONTEXT_CHANGED"); }
static DiagnosticFailure ownershipLost() { return diagnostic("DIRECTORY_OWNERSHIP_LOST"); }
private static JsonNode readErrorBody(String responseBody) throws java.io.IOException {
// Error text is never retained in a diagnostic. Bound parsing so a failed
// endpoint cannot make the error path consume an unbounded response.
if (responseBody == null || responseBody.length() > 16384) return null;
return new com.fasterxml.jackson.databind.ObjectMapper().readTree(responseBody);
}
private static Long safeCode(JsonNode body) {
BigInteger code = responseCode(body);
if (code == null || code.signum() <= 0 || code.compareTo(MAX_DIAGNOSTIC_CODE) > 0) return null;
return code.longValueExact();
}
private static BigInteger responseCode(JsonNode body) {
if (body == null) return null;
JsonNode value = body.path("code");
if (!value.isIntegralNumber()) return null;
try { return value.bigIntegerValue(); }
catch (RuntimeException ignored) { return null; }
}
private static boolean isSafeDiagnostic(String code) {
return code != null && (code.matches("CONFIGURATION_MISSING|CONFIGURATION_UNAVAILABLE|SYNC_DISABLED")
|| code.matches("FEISHU_CODE_[1-9][0-9]{0,8}")
|| code.matches("HTTP_STATUS_[1-5][0-9]{2}")
|| code.matches("(?:TOKEN|DIRECTORY)_[A-Z0-9_]{1,40}"));
}
/** Safe, bounded diagnostic that may cross connector and worker boundaries. */
public static class DiagnosticFailure extends BusinessException {
private final String diagnosticCode;
DiagnosticFailure(String diagnosticCode) {
super("Feishu directory operation failed: " + diagnosticCode, 503);
this.diagnosticCode = diagnosticCode;
}
public String getDiagnosticCode() { return diagnosticCode; }
}
private static String fingerprint(String input) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder out = new StringBuilder(); for (byte b : hash) out.append(String.format("%02x", b & 255)); return out.toString();
} catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable"); }
}
public static final class Context {
private final String app, secret;
public final String fingerprint;
Context(String app, String secret, String fingerprint) { this.app = app; this.secret = secret; this.fingerprint = fingerprint; }
// Deliberately no toString/getters for credentials.
}
}
@@ -0,0 +1,32 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FeishuTokenResponse {
private int code;
private String msg;
private TokenData data;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class TokenData {
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("expires_in")
private int expiresIn;
@JsonProperty("refresh_token")
private String refreshToken;
}
}
@@ -0,0 +1,13 @@
package com.finance.system.adapter.feishu;
import lombok.Data;
@Data
public class FeishuUserInfo {
private String openId;
private String userId;
private String name;
private String avatarUrl;
private String email;
private String mobile;
}
@@ -0,0 +1,33 @@
package com.finance.system.adapter.feishu;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FeishuUserResponse {
private int code;
private String msg;
private UserData data;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class UserData {
@JsonProperty("open_id")
private String openId;
@JsonProperty("user_id")
private String userId;
private String name;
private String email;
private String mobile;
@JsonProperty("avatar_url")
private String avatarUrl;
}
}
@@ -0,0 +1,206 @@
package com.finance.system.adapter.kingdee;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.system.exception.BusinessException;
import com.finance.system.service.IntegrationConfigReader;
import com.finance.system.service.IntegrationConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class KingdeeClient {
private final KingdeeConfig kingdeeConfig;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
private String sessionToken;
private long sessionExpireTime = 0;
private String sessionConfigFingerprint;
private IntegrationConfigReader integrationConfigReader;
private IntegrationConfigService integrationConfigService;
@Autowired(required = false)
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
this.integrationConfigReader = integrationConfigReader;
}
@Autowired(required = false)
public void setIntegrationConfigService(@Lazy IntegrationConfigService integrationConfigService) {
this.integrationConfigService = integrationConfigService;
}
public boolean isEnabled() {
return (integrationConfigReader == null ? kingdeeConfig.isEnabled() : integrationConfigReader.isEnabled("KINGDEE"))
&& hasText(baseUrl());
}
/**
* 登录金蝶云星空,获取Session
*/
public String login() {
if (!isEnabled()) throw new BusinessException("金蝶集成未启用或配置不完整");
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("acctID", dbId());
requestBody.put("username", clientId());
requestBody.put("password", clientSecret());
requestBody.put("lcid", 2052);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
Map<String, Object> body = response.getBody();
if (body != null && Boolean.TRUE.equals(body.get("IsSuccess"))) {
Map<String, Object> result = (Map<String, Object>) body.get("Result");
if (result != null) {
this.sessionToken = (String) result.get("SessionId");
this.sessionExpireTime = System.currentTimeMillis() + 3600000; // 1小时过期
this.sessionConfigFingerprint = configFingerprint();
return this.sessionToken;
}
}
throw new BusinessException("金蝶登录失败: " + (body != null ? body.get("Message") : "未知错误"));
} catch (Exception e) {
log.error("金蝶云星空登录失败", e);
throw new BusinessException("金蝶云星空连接失败");
}
}
/**
* 获取有效的Session
*/
private String getValidSession() {
if (!isEnabled()) throw new BusinessException("金蝶集成未启用");
if (sessionToken == null || System.currentTimeMillis() > sessionExpireTime
|| !configFingerprint().equals(sessionConfigFingerprint)) {
sessionToken = null;
return login();
}
return sessionToken;
}
/**
* 保存单据(创建/更新)
*/
public Map<String, Object> save(String formId, Map<String, Object> data) {
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc";
return executeKingdeeApi(url, formId, data);
}
/**
* 查看单据
*/
public Map<String, Object> view(String formId, String billNo) {
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc";
Map<String, Object> data = new HashMap<>();
data.put("FormId", formId);
data.put("Number", billNo);
HttpHeaders headers = buildHeaders();
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
return response.getBody();
} catch (Exception e) {
log.error("金蝶查看单据失败: formId={}, billNo={}", formId, billNo, e);
throw new BusinessException("金蝶单据查询失败");
}
}
/**
* 查询单据列表
*/
public List<Map<String, Object>> query(String formId, String filterString) {
String url = baseUrl() + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Query.common.kdsvc";
Map<String, Object> data = new HashMap<>();
data.put("FormId", formId);
data.put("FieldKeys", "*");
data.put("FilterString", filterString);
data.put("OrderString", "FDate DESC");
data.put("TopRowCount", 100);
HttpHeaders headers = buildHeaders();
HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
Map<String, Object> body = response.getBody();
if (body != null && body.containsKey("Result")) {
Object result = body.get("Result");
if (result instanceof List) {
return objectMapper.convertValue(result, new TypeReference<List<Map<String, Object>>>() {});
}
}
return java.util.Collections.emptyList();
} catch (Exception e) {
log.error("金蝶查询单据失败: formId={}", formId, e);
throw new BusinessException("金蝶单据查询失败");
}
}
/**
* 执行金蝶API调用
*/
private Map<String, Object> executeKingdeeApi(String url, String formId, Map<String, Object> data) {
Map<String, Object> requestData = new HashMap<>(data);
requestData.put("FormId", formId);
HttpHeaders headers = buildHeaders();
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestData, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
Map<String, Object> body = response.getBody();
if (body != null && Boolean.FALSE.equals(body.get("IsSuccess"))) {
throw new BusinessException("金蝶操作失败: " + body.get("Message"));
}
return body;
} catch (Exception e) {
log.error("金蝶API调用失败: formId={}", formId, e);
throw new BusinessException("金蝶云星空操作失败");
}
}
private HttpHeaders buildHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("SessionId", getValidSession());
return headers;
}
private String baseUrl() {
String raw = configured("baseUrl", kingdeeConfig.getBaseUrl());
if (!hasText(raw)) return raw;
if (integrationConfigService == null) {
throw new BusinessException("金蝶地址校验服务未配置,拒绝发起连接");
}
return integrationConfigService.validateAndNormalizeKingdeeBaseUrl(raw);
}
private String clientId() { return configured("clientId", kingdeeConfig.getClientId()); }
private String clientSecret() { return configured("clientSecret", kingdeeConfig.getClientSecret()); }
private String dbId() { return configured("dbId", kingdeeConfig.getDbId()); }
private String configured(String key, String fallback) { return integrationConfigReader == null ? fallback : integrationConfigReader.get("KINGDEE", key); }
private boolean hasText(String value) { return value != null && !value.trim().isEmpty(); }
private String configFingerprint() { return String.valueOf(baseUrl()) + "\u0000" + String.valueOf(clientId()) + "\u0000" + String.valueOf(clientSecret()) + "\u0000" + String.valueOf(dbId()); }
}
@@ -0,0 +1,16 @@
package com.finance.system.adapter.kingdee;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "kingdee")
public class KingdeeConfig {
private boolean enabled;
private String baseUrl;
private String clientId;
private String clientSecret;
private String dbId;
}
@@ -0,0 +1,118 @@
package com.finance.system.adapter.kingdee;
import com.finance.system.entity.ReimApplication;
import com.finance.system.entity.ReimPayment;
import com.finance.system.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class KingdeeSyncService {
private final KingdeeClient kingdeeClient;
/**
* 同步报销单到金蝶
*/
public void syncExpenseReimbursement(ReimApplication application) {
if (!kingdeeClient.isEnabled()) return;
try {
Map<String, Object> data = buildReimbursementData(application);
Map<String, Object> result = kingdeeClient.save("FIN_EXPENSE_REIMBURSEMENT", data);
log.info("金蝶同步报销单成功: applicationNo={}", application.getApplicationNo());
} catch (Exception e) {
log.error("金蝶同步报销单失败: applicationNo={}", application.getApplicationNo(), e);
throw new BusinessException("金蝶同步失败: " + e.getMessage());
}
}
/**
* 同步付款单到金蝶
*/
public void syncPayment(ReimPayment payment) {
if (!kingdeeClient.isEnabled()) return;
try {
Map<String, Object> data = buildPaymentData(payment);
Map<String, Object> result = kingdeeClient.save("FIN_PAYMENT", data);
log.info("金蝶同步付款单成功: paymentNo={}", payment.getPaymentNo());
} catch (Exception e) {
log.error("金蝶同步付款单失败: paymentNo={}", payment.getPaymentNo(), e);
throw new BusinessException("金蝶同步失败: " + e.getMessage());
}
}
/**
* 查询金蝶报销单状态
*/
public Map<String, Object> queryReimbursementStatus(String billNo) {
try {
return kingdeeClient.view("FIN_EXPENSE_REIMBURSEMENT", billNo);
} catch (Exception e) {
log.error("查询金蝶报销单状态失败: billNo={}", billNo, e);
Map<String, Object> result = new HashMap<>();
result.put("error", "金蝶查询失败");
return result;
}
}
/**
* 构建报销单数据
*/
private Map<String, Object> buildReimbursementData(ReimApplication app) {
Map<String, Object> data = new HashMap<>();
data.put("NeedReturnFields", new String[]{"FBillNo"});
data.put("FBillNo", app.getApplicationNo());
Map<String, Object> model = new HashMap<>();
model.put("FDate", app.getSubmitTime() != null ?
app.getSubmitTime().toString() : java.time.LocalDate.now().toString());
model.put("FBillTypeID", new MapBuilder()
.put("FNUMBER", "EXP_REIM").build());
model.put("FApplicationAmount", app.getTotalAmount());
model.put("FDescription", app.getDescription());
data.put("Model", model);
return data;
}
/**
* 构建付款单数据
*/
private Map<String, Object> buildPaymentData(ReimPayment payment) {
Map<String, Object> data = new HashMap<>();
data.put("NeedReturnFields", new String[]{"FBillNo"});
data.put("FBillNo", payment.getPaymentNo());
Map<String, Object> model = new HashMap<>();
model.put("FDate", java.time.LocalDate.now().toString());
model.put("FBillTypeID", new MapBuilder()
.put("FNUMBER", "PAYMENT").build());
model.put("FPaymentAmount", payment.getPaymentAmount());
model.put("FRemark", payment.getRemark());
data.put("Model", model);
return data;
}
/**
* 简易Map构建器
*/
private static class MapBuilder {
private final Map<String, Object> map = new HashMap<>();
public MapBuilder put(String key, Object value) {
map.put(key, value);
return this;
}
public Map<String, Object> build() {
return map;
}
}
}
@@ -0,0 +1,167 @@
package com.finance.system.config;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.SecretKey;
import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.nio.charset.StandardCharsets;
@Component
public class JwtConfig {
private static final int MIN_SECRET_BYTES = 32;
@Getter
@Value("${jwt.secret}")
private String secret;
@Getter
@Value("${jwt.expiration}")
private long expiration;
/**
* Time zone used to determine the next natural-day boundary for a token.
* This is deliberately a ZoneId rather than a fixed offset so that zones
* observing daylight-saving time are handled correctly.
*/
@Value("${auth.time-zone:Asia/Shanghai}")
private String timeZone = "Asia/Shanghai";
@PostConstruct
void validateConfiguration() {
validateSecretValue(secret);
validateExpirationValue(expiration);
getAuthZoneId();
}
static void validateSecretValue(String secret) {
if (!StringUtils.hasText(secret)
|| secret.getBytes(StandardCharsets.UTF_8).length < MIN_SECRET_BYTES) {
throw new IllegalStateException(
"JWT_SECRET must not be blank and must contain at least 32 UTF-8 bytes");
}
}
static void validateExpirationValue(long expiration) {
if (expiration <= 0) {
throw new IllegalStateException("JWT_EXPIRATION must be strictly positive");
}
}
private SecretKey getSigningKey() {
validateSecretValue(secret);
byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}
public String generateToken(Long userId, String employeeNo, String realName, String userType) {
return generateTokenWithTtl(userId, employeeNo, realName, userType).getToken();
}
/**
* Generates a token whose lifetime ends at the earlier of the next local
* midnight and jwt.expiration. Returning the lifetime together with the
* token keeps the API response in sync with the token that was generated.
*/
public GeneratedToken generateTokenWithTtl(Long userId, String employeeNo,
String realName, String userType) {
Instant issuedAt = Instant.now();
long ttl = calculateTokenTtlMillis(issuedAt, getAuthZoneId(), expiration);
Instant expiresAt = issuedAt.plusMillis(ttl);
String token = Jwts.builder()
.claim("userId", userId)
.claim("employeeNo", employeeNo)
.claim("realName", realName)
.claim("userType", userType)
.setSubject(String.valueOf(userId))
.setIssuedAt(Date.from(issuedAt))
.setExpiration(Date.from(expiresAt))
.signWith(getSigningKey(), io.jsonwebtoken.SignatureAlgorithm.HS256)
.compact();
return new GeneratedToken(token, ttl);
}
/** Returns the lifetime a token generated at this instant would receive. */
public long getTokenTtlMillis() {
return calculateTokenTtlMillis(Instant.now(), getAuthZoneId(), expiration);
}
public ZoneId getAuthZoneId() {
return ZoneId.of(timeZone);
}
/** Visible for focused tests and kept free of wall-clock dependencies. */
static Instant nextMidnight(Instant instant, ZoneId zoneId) {
ZonedDateTime localTime = instant.atZone(zoneId);
return localTime.toLocalDate().plusDays(1).atStartOfDay(zoneId).toInstant();
}
/**
* Calculates a positive TTL in milliseconds. The maximum expiration is
* retained as a hard upper bound even when the local day is longer than it.
*/
static long calculateTokenTtlMillis(Instant instant, ZoneId zoneId, long maximumExpiration) {
validateExpirationValue(maximumExpiration);
long untilMidnight = Duration.between(instant, nextMidnight(instant, zoneId)).toMillis();
return Math.min(maximumExpiration, Math.max(1L, untilMidnight));
}
public static final class GeneratedToken {
private final String token;
private final long expiresIn;
private GeneratedToken(String token, long expiresIn) {
this.token = token;
this.expiresIn = expiresIn;
}
public String getToken() {
return token;
}
public long getExpiresIn() {
return expiresIn;
}
}
public Claims parseToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build()
.parseClaimsJws(token)
.getBody();
}
public boolean validateToken(String token) {
try {
Claims claims = parseToken(token);
return !claims.getExpiration().before(new Date());
} catch (Exception e) {
return false;
}
}
public Long getUserIdFromToken(String token) {
Claims claims = parseToken(token);
Object value = claims.get("userId");
return value instanceof Number ? ((Number) value).longValue() : Long.valueOf(String.valueOf(value));
}
public String getUserTypeFromToken(String token) {
Claims claims = parseToken(token);
return claims.get("userType", String.class);
}
}
@@ -0,0 +1,104 @@
package com.finance.system.config;
import com.finance.system.entity.SysApprovalNode;
import com.finance.system.entity.SysBankAccount;
import com.finance.system.entity.SysDepartment;
import com.finance.system.entity.SysExpenseType;
import com.finance.system.entity.SysUser;
import com.finance.system.repository.SysApprovalNodeRepository;
import com.finance.system.repository.SysBankAccountRepository;
import com.finance.system.repository.SysDepartmentRepository;
import com.finance.system.repository.SysExpenseTypeRepository;
import com.finance.system.repository.SysUserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/** Safe, deterministic local-only seed data. Production never runs this component. */
@Component
@Profile("local")
public class LocalDataInitializer implements CommandLineRunner {
private final SysUserRepository users;
private final SysDepartmentRepository departments;
private final SysExpenseTypeRepository expenseTypes;
private final SysBankAccountRepository bankAccounts;
private final SysApprovalNodeRepository nodes;
private final PasswordEncoder passwordEncoder;
public LocalDataInitializer(SysUserRepository users, SysDepartmentRepository departments,
SysExpenseTypeRepository expenseTypes, SysBankAccountRepository bankAccounts,
SysApprovalNodeRepository nodes,
PasswordEncoder passwordEncoder) {
this.users = users;
this.departments = departments;
this.expenseTypes = expenseTypes;
this.bankAccounts = bankAccounts;
this.nodes = nodes;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String... args) {
if (users.findByEmployeeNo("E1001") != null) return;
SysDepartment department = new SysDepartment();
department.setDeptCode("FIN");
department.setDeptName("财务与行政部");
department.setSortOrder(1);
department.setStatus("ACTIVE");
department = departments.save(department);
SysUser employee = user("E1001", "本地员工", "EMPLOYEE", "员工", department.getId());
employee = users.save(employee);
users.save(user("E1002", "本地员工二", "EMPLOYEE", "员工", department.getId()));
users.save(user("F2001", "应付会计", "FINANCE", "应付会计", department.getId()));
users.save(user("M3001", "财务经理", "FINANCE", "财务经理", department.getId()));
users.save(user("A9001", "系统管理员", "ADMIN", "管理员", department.getId()));
SysExpenseType type = new SysExpenseType();
type.setTypeCode("TRAVEL");
type.setTypeName("差旅费");
type.setCategory("费用");
type.setSortOrder(1);
type.setStatus("ACTIVE");
expenseTypes.save(type);
SysBankAccount bank = new SysBankAccount();
bank.setUserId(employee.getId());
bank.setBankName("本地测试银行");
bank.setBranchName("测试支行");
bank.setAccountNo("6222000000001001");
bank.setAccountNoMask("************1001");
bank.setAccountName(employee.getRealName());
bank.setIsDefault(true);
bank.setStatus("ACTIVE");
bankAccounts.save(bank);
nodes.save(node("NODE_AP", "应付会计审核", "ACCOUNTS_PAYABLE", 1));
nodes.save(node("NODE_MANAGER", "财务经理审批", "FINANCE_MANAGER", 2));
}
private SysUser user(String number, String name, String type, String position, Long departmentId) {
SysUser user = new SysUser();
user.setEmployeeNo(number);
user.setRealName(name);
user.setUserType(type);
user.setPosition(position);
user.setDepartmentId(departmentId);
user.setPasswordHash(passwordEncoder.encode("local-password"));
user.setStatus("ACTIVE");
return user;
}
private SysApprovalNode node(String code, String name, String role, int order) {
SysApprovalNode node = new SysApprovalNode();
node.setNodeCode(code);
node.setNodeName(name);
node.setApproverType("ROLE");
node.setApproverRole(role);
node.setSortOrder(order);
node.setStatus("ACTIVE");
return node;
}
}
@@ -0,0 +1,76 @@
package com.finance.system.config;
import com.finance.system.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.servlet.http.HttpServletResponse;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final Environment environment;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, com.fasterxml.jackson.databind.ObjectMapper mapper) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> {})
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> {
if (isLocalProfile()) {
auth.antMatchers("/api/auth/login").permitAll();
}
auth
.antMatchers("/api/auth/feishu-login").permitAll()
.antMatchers("/api/feishu/auth-url", "/api/feishu/callback", "/api/feishu/webhook", "/api/feishu/login").permitAll()
.antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll();
})
.exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(
(request, response, exception) -> {
if (request.getServletPath().startsWith("/api/feishu/directory/")) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
mapper.writeValue(response.getOutputStream(), com.finance.system.dto.ApiResponse.error(401, "Authentication required"));
} else response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录或登录已过期");
}
))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()));
return http.build();
}
private boolean isLocalProfile() {
for (String profile : environment.getActiveProfiles()) {
if ("local".equalsIgnoreCase(profile)) {
return true;
}
}
return false;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,49 @@
package com.finance.system.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.Collections;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${app.frontend-url:http://localhost:5173}")
private String frontendUrl;
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
if (frontendUrl != null && !frontendUrl.trim().isEmpty()) {
config.setAllowedOrigins(Collections.singletonList(frontendUrl.trim()));
} else {
// An empty origin configuration disables cross-origin requests;
// never weaken this to a wildcard when credentials are enabled.
config.setAllowedOrigins(Collections.<String>emptyList());
}
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return new CorsFilter(source);
}
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000);
factory.setReadTimeout(10000);
return new RestTemplate(factory);
}
}
@@ -0,0 +1,64 @@
package com.finance.system.controller;
import com.finance.system.dto.*;
import com.finance.system.service.ReimApplicationService;
import com.finance.system.service.ReimApprovalService;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/accounts-payable")
@RequiredArgsConstructor
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public class AccountsPayableController {
private final ReimApplicationService reimApplicationService;
private final ReimApprovalService reimApprovalService;
@GetMapping("/tasks")
public ResponseEntity<ApiResponse<PageResponse<ReimApplicationSummary>>> getTasks(
@RequestParam(defaultValue = "PENDING") String status,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
Pageable pageable = PageRequest.of(page, size);
Page<ReimApplicationSummary> tasks = reimApplicationService.getAccountsPayableTasks(status, pageable);
return ResponseEntity.ok(ApiResponse.success(PageResponse.of(
tasks.getContent(), tasks.getTotalElements(), page, size)));
}
@GetMapping("/tasks/{id}")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getTaskDetail(@PathVariable Long id) {
ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success(detail));
}
@PostMapping("/approve")
public ResponseEntity<ApiResponse<Void>> approve(@RequestBody ApprovalActionRequest request) {
Long userId = AuditUtil.getCurrentUserId();
reimApprovalService.approve(request.getApplicationId(), userId, request.getComment());
return ResponseEntity.ok(ApiResponse.success());
}
@PostMapping("/reject")
public ResponseEntity<ApiResponse<Void>> reject(@RequestBody ApprovalActionRequest request) {
Long userId = AuditUtil.getCurrentUserId();
reimApprovalService.reject(request.getApplicationId(), userId,
request.getComment(), request.getReturnReason());
return ResponseEntity.ok(ApiResponse.success());
}
@GetMapping("/history")
public ResponseEntity<ApiResponse<List<ApprovalRecordDto>>> getHistory() {
Long userId = AuditUtil.getCurrentUserId();
List<ApprovalRecordDto> history = reimApprovalService.getApprovalHistoryByUser(userId);
return ResponseEntity.ok(ApiResponse.success(history));
}
}
@@ -0,0 +1,268 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/api/applications")
@RequiredArgsConstructor
public class ApplicationController {
/**
* Mock数据 - 付款申请列表
* 对应原型中的员工报销数据(员工报销类)
*/
private static final List<Map<String, Object>> MOCK_APPLICATIONS = new ArrayList<>();
static {
Map<String, Object> a1 = new LinkedHashMap<>();
a1.put("id", 1L);
a1.put("applicationNo", "BX20260812001");
a1.put("date", "2026-08-12");
a1.put("title", "上海客户现场技术交流差旅");
a1.put("type", "费用报销");
a1.put("subtype", "差旅交通");
a1.put("payee", "李志豪");
a1.put("amount", new BigDecimal("3286.50"));
a1.put("owner", "李志豪");
a1.put("department", "销售中心");
a1.put("applicationStatus", "退回");
a1.put("receiptStatus", "未触发");
a1.put("paymentStatus", "未付款");
a1.put("budgetStatus", "已占用");
a1.put("approvalNode", "申请人补充材料");
a1.put("approver", "李志豪");
a1.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a1);
Map<String, Object> a2 = new LinkedHashMap<>();
a2.put("id", 2L);
a2.put("applicationNo", "BX20260809003");
a2.put("date", "2026-08-09");
a2.put("title", "八月客户拜访交通费");
a2.put("type", "费用报销");
a2.put("subtype", "交通费");
a2.put("payee", "李志豪");
a2.put("amount", new BigDecimal("1260.00"));
a2.put("owner", "李志豪");
a2.put("department", "销售中心");
a2.put("applicationStatus", "审批中");
a2.put("receiptStatus", "未触发");
a2.put("paymentStatus", "未付款");
a2.put("budgetStatus", "已占用");
a2.put("approvalNode", "应付会计审核");
a2.put("approver", "刘雅");
a2.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a2);
Map<String, Object> a3 = new LinkedHashMap<>();
a3.put("id", 3L);
a3.put("applicationNo", "BX20260808006");
a3.put("date", "2026-08-08");
a3.put("title", "研发现场餐费报销");
a3.put("type", "费用报销");
a3.put("subtype", "业务招待");
a3.put("payee", "王忠辉");
a3.put("amount", new BigDecimal("680.00"));
a3.put("owner", "王忠辉");
a3.put("department", "数字化中心");
a3.put("applicationStatus", "审批中");
a3.put("receiptStatus", "未触发");
a3.put("paymentStatus", "未付款");
a3.put("budgetStatus", "已占用");
a3.put("approvalNode", "财务经理审批");
a3.put("approver", "周岚");
a3.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a3);
Map<String, Object> a4 = new LinkedHashMap<>();
a4.put("id", 4L);
a4.put("applicationNo", "BX20260802011");
a4.put("date", "2026-08-02");
a4.put("title", "苏州园区客户拜访费用");
a4.put("type", "费用报销");
a4.put("subtype", "交通费");
a4.put("payee", "赵海峰");
a4.put("amount", new BigDecimal("2180.00"));
a4.put("owner", "赵海峰");
a4.put("department", "供应链中心");
a4.put("applicationStatus", "审批通过");
a4.put("receiptStatus", "待收单");
a4.put("paymentStatus", "未付款");
a4.put("budgetStatus", "已转执行");
a4.put("approvalNode", "流程已完成");
a4.put("approver", "—");
a4.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a4);
Map<String, Object> a5 = new LinkedHashMap<>();
a5.put("id", 5L);
a5.put("applicationNo", "BX20260801009");
a5.put("date", "2026-08-01");
a5.put("title", "七月云资源差旅补贴");
a5.put("type", "费用报销");
a5.put("subtype", "差旅补贴");
a5.put("payee", "王忠辉");
a5.put("amount", new BigDecimal("3200.00"));
a5.put("owner", "王忠辉");
a5.put("department", "数字化中心");
a5.put("applicationStatus", "审批通过");
a5.put("receiptStatus", "已收单");
a5.put("paymentStatus", "未付款");
a5.put("budgetStatus", "已转执行");
a5.put("approvalNode", "流程已完成");
a5.put("approver", "—");
a5.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a5);
Map<String, Object> a6 = new LinkedHashMap<>();
a6.put("id", 6L);
a6.put("applicationNo", "BX20260728004");
a6.put("date", "2026-07-28");
a6.put("title", "上海项目住宿费");
a6.put("type", "费用报销");
a6.put("subtype", "住宿费");
a6.put("payee", "赵海峰");
a6.put("amount", new BigDecimal("4100.00"));
a6.put("owner", "赵海峰");
a6.put("department", "供应链中心");
a6.put("applicationStatus", "审批通过");
a6.put("receiptStatus", "已收单");
a6.put("paymentStatus", "部分付款");
a6.put("budgetStatus", "已转执行");
a6.put("approvalNode", "流程已完成");
a6.put("approver", "—");
a6.put("expenseType", "员工报销类");
MOCK_APPLICATIONS.add(a6);
}
/**
* 获取付款申请列表(应付会计B视图,过滤 expenseType=员工报销类)
*/
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listApplications(
@RequestParam(required = false) String status,
@RequestParam(required = false) String expenseType) {
try {
List<Map<String, Object>> result = new ArrayList<>(MOCK_APPLICATIONS);
// 默认过滤 expenseType=员工报销类
if (expenseType != null && !expenseType.isEmpty()) {
result.removeIf(app -> !expenseType.equals(app.get("expenseType")));
} else {
result.removeIf(app -> !"员工报销类".equals(app.get("expenseType")));
}
// 按状态过滤
if (status != null && !status.isEmpty()) {
result.removeIf(app -> !status.equals(app.get("applicationStatus")));
}
return ResponseEntity.ok(ApiResponse.success(result));
} catch (Exception e) {
log.error("获取付款申请列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取付款申请列表失败: " + e.getMessage()));
}
}
/**
* 获取付款申请详情
*/
@GetMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<Map<String, Object>>> getApplicationDetail(@PathVariable Long id) {
try {
Map<String, Object> application = MOCK_APPLICATIONS.stream()
.filter(a -> id.equals(a.get("id")))
.findFirst()
.orElse(null);
if (application == null) {
return ResponseEntity.status(404)
.body(ApiResponse.error(404, "申请单不存在: " + id));
}
// 追加详细信息
Map<String, Object> detail = new LinkedHashMap<>(application);
detail.put("bankName", "中国工商银行苏州新区支行");
detail.put("bankAccount", "6222 **** 0086 0728");
detail.put("description", getDescriptionById(id));
detail.put("invoices", getInvoicesById(id));
detail.put("attachments", getAttachmentsById(id));
detail.put("returnReason", getReturnReasonById(id));
detail.put("lastUpdated", "2026-08-12 10:24");
return ResponseEntity.ok(ApiResponse.success(detail));
} catch (Exception e) {
log.error("获取申请详情失败: id={}", id, e);
return ResponseEntity.ok(ApiResponse.error(500, "获取申请详情失败: " + e.getMessage()));
}
}
private String getDescriptionById(Long id) {
if (id == 1L) return "上海客户现场技术交流产生的交通及住宿费用。";
if (id == 2L) return "客户拜访交通费用。";
if (id == 3L) return "研发现场支持期间的工作餐费用。";
if (id == 4L) return "园区客户拜访交通与停车费用。";
if (id == 5L) return "七月现场支持差旅补贴。";
if (id == 6L) return "上海项目住宿费用。";
return "";
}
private List<Map<String, Object>> getInvoicesById(Long id) {
List<Map<String, Object>> invoices = new ArrayList<>();
if (id == 2L) {
Map<String, Object> inv = new LinkedHashMap<>();
inv.put("number", "03300260011142888901");
inv.put("amount", new BigDecimal("1260.00"));
inv.put("file", "出租车发票_08月.pdf");
invoices.add(inv);
}
if (id == 4L) {
Map<String, Object> inv = new LinkedHashMap<>();
inv.put("number", "03300260011142887771");
inv.put("amount", new BigDecimal("2180.00"));
inv.put("file", "停车及交通发票.pdf");
invoices.add(inv);
}
if (id == 6L) {
Map<String, Object> inv = new LinkedHashMap<>();
inv.put("number", "03300260011142885550");
inv.put("amount", new BigDecimal("4100.00"));
inv.put("file", "住宿发票.pdf");
invoices.add(inv);
}
return invoices;
}
private List<Map<String, Object>> getAttachmentsById(Long id) {
List<Map<String, Object>> attachments = new ArrayList<>();
if (id == 1L) {
Map<String, Object> att1 = new LinkedHashMap<>();
att1.put("type", "出差申请");
att1.put("name", "出差申请_上海客户现场.pdf");
attachments.add(att1);
Map<String, Object> att2 = new LinkedHashMap<>();
att2.put("type", "行程证明");
att2.put("name", "高铁行程单.pdf");
attachments.add(att2);
}
return attachments;
}
private String getReturnReasonById(Long id) {
if (id == 1L) return "请补充住宿发票影像,并说明住宿日期。";
return null;
}
}
@@ -0,0 +1,332 @@
package com.finance.system.controller;
import com.finance.system.adapter.feishu.FeishuAuthService;
import com.finance.system.adapter.feishu.FeishuTokenResponse;
import com.finance.system.adapter.feishu.FeishuUserInfo;
import com.finance.system.config.JwtConfig;
import com.finance.system.dto.*;
import com.finance.system.entity.SysUser;
import com.finance.system.entity.SysDepartment;
import com.finance.system.enums.UserType;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.repository.SysDepartmentRepository;
import com.finance.system.security.UserPrincipal;
import com.finance.system.service.RoleService;
import com.finance.system.util.AuditUtil;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final SysUserRepository sysUserRepository;
private final SysDepartmentRepository sysDepartmentRepository;
private final JwtConfig jwtConfig;
private final FeishuAuthService feishuAuthService;
private final Environment environment;
private final PasswordEncoder passwordEncoder;
private RoleService roleService;
@Autowired
private com.finance.system.adapter.feishu.FeishuDirectoryAccessService directoryAccess;
@Autowired
private com.finance.system.adapter.feishu.FeishuLoginPersistenceService loginPersistence;
@Autowired(required = false)
public void setRoleService(RoleService roleService) {
this.roleService = roleService;
}
@PostMapping("/login")
public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest request) {
if (!isLocalProfile()) {
return ResponseEntity.status(403)
.body(ApiResponse.error(403, "生产环境必须使用飞书登录,密码登录仅允许 local 环境"));
}
SysUser user = sysUserRepository.findByEmployeeNo(request.getEmployeeNo());
if (user == null) {
return ResponseEntity.status(401)
.body(ApiResponse.error(401, "用户不存在"));
}
if (request.getPassword() == null || request.getPassword().trim().isEmpty()
|| user.getPasswordHash() == null
|| user.getPasswordHash().trim().isEmpty()
|| !passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
return ResponseEntity.status(401)
.body(ApiResponse.error(401, "员工编号或密码错误"));
}
if (!"ACTIVE".equalsIgnoreCase(user.getStatus())) {
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
}
directoryAccess.requireAllowed(user);
user = loginPersistence.completeLocal(user.getId());
JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl(
user.getId(), user.getEmployeeNo(),
user.getRealName(), RoleService.normalize(user.getUserType()));
UserProfile profile = buildUserProfile(user);
LoginResponse loginResponse = LoginResponse.builder()
.token(generatedToken.getToken())
.tokenType("Bearer")
.expiresIn(generatedToken.getExpiresIn())
.user(profile)
.build();
return ResponseEntity.ok(ApiResponse.success(loginResponse));
}
private boolean isLocalProfile() {
for (String profile : environment.getActiveProfiles()) {
if ("local".equalsIgnoreCase(profile)) return true;
}
return false;
}
@PostMapping("/feishu-login")
public ResponseEntity<ApiResponse<LoginResponse>> feishuLogin(
@RequestBody Map<String, String> request,
@CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) {
String code = request.get("code");
String state = request.get("state");
if (code == null || code.isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "授权码不能为空"));
}
feishuAuthService.validateCallbackState(state, browserState, true);
FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code);
FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(
tokenResponse.getData().getAccessToken());
SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo);
if (!isActive(user)) {
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
}
JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl(
user.getId(), user.getEmployeeNo(),
user.getRealName(), RoleService.normalize(user.getUserType()));
UserProfile profile = buildUserProfile(user);
LoginResponse loginResponse = LoginResponse.builder()
.token(generatedToken.getToken())
.tokenType("Bearer")
.expiresIn(generatedToken.getExpiresIn())
.user(profile)
.build();
return ResponseEntity.ok(ApiResponse.success(loginResponse));
}
@GetMapping("/me")
public ResponseEntity<ApiResponse<UserProfile>> getCurrentUser() {
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null) {
return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录"));
}
SysUser user = sysUserRepository.findById(principal.getId())
.orElse(null);
if (user == null) {
return ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在"));
}
return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user)));
}
@PostMapping("/refresh")
public ResponseEntity<ApiResponse<LoginResponse>> refreshToken() {
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null) {
return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录"));
}
SysUser user = sysUserRepository.findById(principal.getId()).orElse(null);
if (user == null) {
return ResponseEntity.status(401).body(ApiResponse.error(401, "用户不存在"));
}
if (!isActive(user)) {
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
}
JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl(
user.getId(), user.getEmployeeNo(),
user.getRealName(), RoleService.normalize(user.getUserType()));
LoginResponse loginResponse = LoginResponse.builder()
.token(generatedToken.getToken())
.tokenType("Bearer")
.expiresIn(generatedToken.getExpiresIn())
.user(buildUserProfile(user))
.build();
return ResponseEntity.ok(ApiResponse.success(loginResponse));
}
@PostMapping("/logout")
public ResponseEntity<ApiResponse<Void>> logout() {
return ResponseEntity.ok(ApiResponse.success());
}
/**
* 获取所有用户列表
*/
@GetMapping("/users")
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:view')")
public ResponseEntity<ApiResponse<List<UserProfile>>> listUsers() {
List<SysUser> users = sysUserRepository.findAll();
List<UserProfile> profiles = users.stream()
.map(this::buildUserProfile)
.collect(Collectors.toList());
return ResponseEntity.ok(ApiResponse.success(profiles));
}
/**
* 更新用户角色
*/
@PutMapping("/users/{id}/role")
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
public ResponseEntity<ApiResponse<UserProfile>> updateUserRole(
@PathVariable Long id,
@RequestBody Map<String, String> request) {
String newRole = request.get("userType");
if (newRole == null || newRole.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "角色不能为空"));
}
String normalizedRole = newRole.trim().toUpperCase(Locale.ROOT);
try {
// SUPER_ADMIN is a valid legacy compatibility value even though
// it is intentionally not exposed by the ordinary user-type enum.
if (!RoleService.SUPER_ADMIN.equals(normalizedRole)) {
normalizedRole = UserType.valueOf(normalizedRole).name();
}
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "角色必须是 EMPLOYEE、FINANCE、ADMIN 或 SUPER_ADMIN"));
}
SysUser user = sysUserRepository.findById(id).orElse(null);
if (user == null) {
return ResponseEntity.status(404)
.body(ApiResponse.error(404, "用户不存在"));
}
// Keep the legacy endpoint's historical 400 contract for an
// unsupported delegation request made by a non-super administrator;
// the service remains the authoritative actor-aware security check.
if (RoleService.SUPER_ADMIN.equals(normalizedRole) && roleService != null
&& !roleService.isSuperAdmin(AuditUtil.getCurrentUserId())) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "只有超级管理员可以授予 SUPER_ADMIN"));
}
if (roleService != null) roleService.syncLegacyRole(id, normalizedRole, AuditUtil.getCurrentUserId());
user.setUserType(normalizedRole);
sysUserRepository.save(user);
return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user)));
}
/**
* 切换用户状态
*/
@PutMapping("/users/{id}/status")
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
public ResponseEntity<ApiResponse<UserProfile>> toggleUserStatus(
@PathVariable Long id,
@RequestBody Map<String, String> request) {
String newStatus = request.get("status");
if (newStatus == null || newStatus.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "状态不能为空"));
}
String normalizedStatus = newStatus.trim().toUpperCase(Locale.ROOT);
if (!"ACTIVE".equals(normalizedStatus) && !"INACTIVE".equals(normalizedStatus)) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "状态必须是 ACTIVE 或 INACTIVE"));
}
if (id.equals(AuditUtil.getCurrentUserId()) && "INACTIVE".equals(normalizedStatus)) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "不能停用当前登录账号"));
}
SysUser user = sysUserRepository.findById(id).orElse(null);
if (user == null) {
return ResponseEntity.status(404)
.body(ApiResponse.error(404, "用户不存在"));
}
user.setStatus(normalizedStatus);
sysUserRepository.save(user);
return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user)));
}
/** Replaces direct role assignments; groups are intentionally managed by the group API. */
@PutMapping("/users/{id}/roles")
@PreAuthorize("@permissionChecker.has(authentication, 'system:user:manage')")
public ResponseEntity<ApiResponse<UserProfile>> updateUserRoles(@PathVariable Long id,
@RequestBody Map<String, Object> request) {
if (roleService == null) return ResponseEntity.status(503).body(ApiResponse.error(503, "RBAC 服务未就绪"));
Object ids = request == null ? null : request.get("roleIds");
if (!(ids instanceof List)) return ResponseEntity.badRequest().body(ApiResponse.error(400, "roleIds 必须是数组"));
roleService.replaceUserRoles(id, (List<?>) ids, AuditUtil.getCurrentUserId());
SysUser user = sysUserRepository.findById(id).orElse(null);
if (user == null) return ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在"));
return ResponseEntity.ok(ApiResponse.success(buildUserProfile(user)));
}
private UserProfile buildUserProfile(SysUser user) {
String deptName = null;
if (user.getDepartmentId() != null) {
SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null);
if (dept != null) {
deptName = dept.getDeptName();
}
}
return UserProfile.builder()
.id(user.getId())
.employeeNo(user.getEmployeeNo())
.realName(user.getRealName())
.avatarUrl(user.getAvatarUrl())
.email(user.getEmail())
.departmentName(deptName)
.position(user.getPosition())
.userType(RoleService.normalize(user.getUserType()))
.status(user.getStatus())
.feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定")
.lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null)
.roleCodes(roleService == null ? Collections.singletonList(RoleService.normalize(user.getUserType())) : roleService.userRoleCodes(user.getId()))
.groupNames(roleService == null ? Collections.emptyList() : roleService.userGroupNames(user.getId()))
.build();
}
private boolean isActive(SysUser user) {
return user != null && "ACTIVE".equalsIgnoreCase(user.getStatus());
}
}
@@ -0,0 +1,93 @@
package com.finance.system.controller;
import com.finance.system.dto.*;
import com.finance.system.exception.BusinessException;
import com.finance.system.service.ReimPaymentService;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/cashier")
@RequiredArgsConstructor
@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')")
public class CashierController {
private final ReimPaymentService reimPaymentService;
@GetMapping("/tasks")
public ResponseEntity<ApiResponse<PageResponse<PaymentTaskDto>>> getTasks(
@RequestParam(defaultValue = "UNPAID") String status,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
Long userId = AuditUtil.getCurrentUserId();
Pageable pageable = PageRequest.of(page, size);
Page<PaymentTaskDto> tasks = reimPaymentService.getPendingPayments(userId, pageable);
return ResponseEntity.ok(ApiResponse.success(PageResponse.of(
tasks.getContent(), tasks.getTotalElements(), page, size)));
}
@GetMapping("/tasks/{id}")
public ResponseEntity<ApiResponse<PaymentDetailDto>> getTaskDetail(@PathVariable Long id) {
PaymentDetailDto detail = reimPaymentService.getPaymentDetail(id, AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success(detail));
}
@PostMapping("/pay")
public ResponseEntity<ApiResponse<PaymentResultDto>> executePayment(
@RequestBody CreatePaymentRequest request,
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
Long userId = AuditUtil.getCurrentUserId();
String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey());
PaymentResultDto result = reimPaymentService.executePayment(request.getApplicationId(),
request.getPaymentAmount(), userId, request.getPaymentMethod(), request.getReferenceNo(),
request.getRemark(), resolvedIdempotencyKey);
return ResponseEntity.ok(ApiResponse.success(result));
}
@PostMapping("/partial-pay")
public ResponseEntity<ApiResponse<PaymentResultDto>> processPartialPayment(
@RequestBody CreatePaymentRequest request,
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey) {
Long applicationId = request.getApplicationId();
BigDecimal amount = request.getPaymentAmount();
Long userId = AuditUtil.getCurrentUserId();
String resolvedIdempotencyKey = resolveIdempotencyKey(idempotencyKey, request.getIdempotencyKey());
PaymentResultDto result = reimPaymentService.processPartialPayment(applicationId, amount, userId,
request.getPaymentMethod(), request.getReferenceNo(), request.getRemark(), resolvedIdempotencyKey);
return ResponseEntity.ok(ApiResponse.success(result));
}
@GetMapping("/history")
public ResponseEntity<ApiResponse<List<PaymentRecordDto>>> getPaymentHistory() {
Long userId = AuditUtil.getCurrentUserId();
List<PaymentRecordDto> history = reimPaymentService.getPaymentHistoryByOperator(userId);
return ResponseEntity.ok(ApiResponse.success(history));
}
@GetMapping("/payments/{paymentNo}")
public ResponseEntity<ApiResponse<PaymentRecordDto>> getPaymentByNo(@PathVariable String paymentNo) {
PaymentRecordDto payment = reimPaymentService.getPaymentByNo(paymentNo, AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success(payment));
}
private String resolveIdempotencyKey(String headerValue, String bodyValue) {
boolean hasHeader = StringUtils.hasText(headerValue);
boolean hasBody = StringUtils.hasText(bodyValue);
if (hasHeader && hasBody && !headerValue.trim().equals(bodyValue.trim())) {
throw new BusinessException("Header 与 body 的幂等键不一致", 409);
}
if (hasHeader) return headerValue.trim();
return hasBody ? bodyValue.trim() : null;
}
}
@@ -0,0 +1,38 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.dto.DashboardStats;
import com.finance.system.dto.ReimApplicationSummary;
import com.finance.system.service.DashboardService;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/dashboard")
@RequiredArgsConstructor
public class DashboardController {
private final DashboardService dashboardService;
@GetMapping("/stats")
@PreAuthorize("@permissionChecker.has(authentication, 'dashboard')")
public ResponseEntity<ApiResponse<DashboardStats>> getStats() {
Long userId = AuditUtil.getCurrentUserId();
DashboardStats stats = dashboardService.getDashboardStats(userId);
return ResponseEntity.ok(ApiResponse.success(stats));
}
@GetMapping("/recent")
@PreAuthorize("@permissionChecker.has(authentication, 'dashboard')")
public ResponseEntity<ApiResponse<List<ReimApplicationSummary>>> getRecent(
@RequestParam(defaultValue = "5") int limit) {
Long userId = AuditUtil.getCurrentUserId();
List<ReimApplicationSummary> recent = dashboardService.getRecentApplications(userId, limit);
return ResponseEntity.ok(ApiResponse.success(recent));
}
}
@@ -0,0 +1,298 @@
package com.finance.system.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.system.adapter.feishu.FeishuApprovalService;
import com.finance.system.adapter.feishu.FeishuAuthService;
import com.finance.system.adapter.feishu.FeishuApprovalResponse;
import com.finance.system.dto.ApiResponse;
import com.finance.system.entity.SysWebhookEvent;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysWebhookEventRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Optional;
import java.time.Instant;
@Slf4j
@RestController
@RequestMapping("/api/feishu")
@RequiredArgsConstructor
public class FeishuAuthController {
private final FeishuAuthService feishuAuthService;
private final FeishuApprovalService feishuApprovalService;
private final ObjectMapper objectMapper;
private final SysWebhookEventRepository webhookEventRepository;
@Value("${app.frontend-url:http://localhost:5173}")
private String frontendUrl;
@GetMapping("/auth-url")
public ResponseEntity<ApiResponse<Map<String, String>>> getAuthUrl(HttpServletRequest request) {
FeishuAuthService.AuthUrl auth = feishuAuthService.buildAuthUrlWithState();
Map<String, String> result = new HashMap<>();
result.put("authUrl", auth.getAuthUrl());
String state = auth.getState();
String cookie = "FEISHU_OAUTH_STATE=" + state
+ "; Max-Age=300; Path=/api; HttpOnly; SameSite=Lax"
+ (request.isSecure() ? "; Secure" : "");
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.SET_COOKIE, cookie);
return new ResponseEntity<>(ApiResponse.success(result), headers, HttpStatus.OK);
}
/**
* 飞书OAuth回调。
* 只转交一次性授权码,JWT 在后端的登录接口中生成,避免把 bearer token 放进 URL。
*/
@GetMapping("/callback")
public ResponseEntity<Void> callback(
@RequestParam("code") String code,
@RequestParam(value = "state", required = false) String state) {
log.info("收到飞书OAuth回调");
try {
feishuAuthService.validateCallbackState(state);
String redirectUrl = frontendUrl + "/login?code=" + encodeUrl(code)
+ "&state=" + encodeUrl(state);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(redirectUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND);
} catch (BusinessException e) {
log.warn("飞书登录失败: {}", e.getMessage());
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败: " + e.getMessage());
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(errorUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND);
} catch (Exception e) {
log.error("飞书登录失败", e);
String errorUrl = frontendUrl + "/login?error=" + encodeUrl("飞书登录失败: " + e.getMessage());
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(errorUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
}
private String encodeUrl(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (Exception e) {
return value;
}
}
/**
* 飞书审批回调Webhook
* 处理审批实例状态变更、审批任务变更等事件
*/
@PostMapping("/webhook")
@Transactional
public ResponseEntity<Map<String, Object>> handleWebhook(
@RequestBody String rawBody,
@RequestHeader(value = "X-Lark-Signature", required = false) String signature,
@RequestHeader(value = "X-Lark-Request-Timestamp", required = false) String timestamp,
@RequestHeader(value = "X-Lark-Request-Nonce", required = false) String nonce) {
Map<String, Object> body;
try {
body = objectMapper.readValue(rawBody, Map.class);
} catch (Exception e) {
return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook body"));
}
log.info("收到飞书Webhook请求: eventType={}", body.get("event_type"));
if (!feishuAuthService.isWebhookAuthorized(body, signature, timestamp, nonce, rawBody)) {
return ResponseEntity.status(401).body(responseMap(1, "invalid webhook signature"));
}
// 处理URL验证(飞书首次配置事件订阅时会发送验证请求)
if (body.containsKey("challenge")) {
String challenge = (String) body.get("challenge");
log.info("飞书Webhook URL验证: challenge={}", challenge);
Map<String, Object> result = new HashMap<>();
result.put("challenge", challenge);
return ResponseEntity.ok(result);
}
if (!isFreshTimestamp(timestamp)) {
return ResponseEntity.badRequest().body(responseMap(1, "invalid webhook timestamp"));
}
// Feishu v2 wraps the event in event/header. Flatten only the
// compatibility fields consumed by the existing approval adapter;
// the raw body is still used for signature verification above.
Map<String, Object> normalized = normalizeEvent(body);
// 处理审批事件
String eventId = eventId(normalized);
if (eventId == null) {
return ResponseEntity.badRequest().body(responseMap(1, "event_id is required"));
}
return processWebhookEvent(eventId, normalized);
}
private boolean isFreshTimestamp(String value) {
if (value == null || value.trim().isEmpty()) return false;
try {
long supplied = Long.parseLong(value.trim());
long now = Instant.now().getEpochSecond();
return Math.abs(now - supplied) <= 300L;
} catch (Exception e) {
return false;
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> normalizeEvent(Map<String, Object> body) {
Map<String, Object> normalized = new LinkedHashMap<>(body);
Object eventValue = body.get("event");
if (eventValue instanceof Map) {
Map<String, Object> event = (Map<String, Object>) eventValue;
for (Map.Entry<String, Object> entry : event.entrySet()) {
if (!normalized.containsKey(entry.getKey())) normalized.put(entry.getKey(), entry.getValue());
}
if (!normalized.containsKey("event_id") && event.get("event_id") != null) {
normalized.put("event_id", event.get("event_id"));
}
if (!normalized.containsKey("event_type") && event.get("event_type") != null) {
normalized.put("event_type", event.get("event_type"));
}
}
Object headerValue = body.get("header");
if (headerValue instanceof Map) {
Map<String, Object> header = (Map<String, Object>) headerValue;
if (!normalized.containsKey("event_id") && header.get("event_id") != null) {
normalized.put("event_id", header.get("event_id"));
}
if (!normalized.containsKey("event_type") && header.get("event_type") != null) {
normalized.put("event_type", header.get("event_type"));
}
}
return normalized;
}
private String eventId(Map<String, Object> body) {
Object value = body.get("event_id");
if ((value == null || String.valueOf(value).trim().isEmpty()) && body.get("event") instanceof Map) {
value = ((Map<?, ?>) body.get("event")).get("event_id");
}
if ((value == null || String.valueOf(value).trim().isEmpty()) && body.get("header") instanceof Map) {
value = ((Map<?, ?>) body.get("header")).get("event_id");
}
return value == null || String.valueOf(value).trim().isEmpty() ? null : String.valueOf(value).trim();
}
private ResponseEntity<Map<String, Object>> processWebhookEvent(
String eventId, Map<String, Object> body) {
SysWebhookEvent event = null;
try {
webhookEventRepository.insertIfAbsent(eventId);
Optional<SysWebhookEvent> locked = webhookEventRepository.findById(eventId);
if (!locked.isPresent()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(responseMap(1, "webhook inbox unavailable"));
}
event = locked.get();
if (SysWebhookEvent.PROCESSED.equals(event.getStatus())) {
return ResponseEntity.ok(responseMap(0, "success"));
}
event.setStatus(SysWebhookEvent.PROCESSING);
feishuApprovalService.handleApprovalEvent(body);
event.setStatus(SysWebhookEvent.PROCESSED);
return ResponseEntity.ok(responseMap(0, "success"));
} catch (Exception e) {
if (event != null) {
event.setStatus(SysWebhookEvent.FAILED);
}
log.error("处理飞书Webhook失败: eventId={}", eventId, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(responseMap(1, "webhook processing failed"));
}
}
private Map<String, Object> responseMap(int code, String message) {
Map<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", message);
return result;
}
/**
* 获取审批定义(审批节点信息)
*/
@GetMapping("/approval/definition")
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public ResponseEntity<ApiResponse<Object>> getApprovalDefinition() {
try {
FeishuApprovalResponse definition = feishuApprovalService.getApprovalDefinition();
return ResponseEntity.ok(ApiResponse.success(definition));
} catch (Exception e) {
log.error("获取审批定义失败", e);
return ResponseEntity.ok(ApiResponse.error(500, e.getMessage()));
}
}
/**
* 获取审批节点列表
*/
@GetMapping("/approval/nodes")
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public ResponseEntity<ApiResponse<Object>> getApprovalNodes() {
try {
java.util.List<FeishuApprovalResponse.ApprovalNode> nodes = feishuApprovalService.getApprovalNodes();
return ResponseEntity.ok(ApiResponse.success(nodes));
} catch (Exception e) {
log.error("获取审批节点失败", e);
return ResponseEntity.ok(ApiResponse.error(500, e.getMessage()));
}
}
/**
* 获取审批实例进度
*/
@GetMapping("/approval/instance/{instanceCode}")
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public ResponseEntity<ApiResponse<Object>> getApprovalInstanceDetail(
@PathVariable String instanceCode) {
try {
FeishuApprovalResponse detail = feishuApprovalService.getApprovalInstanceDetail(instanceCode);
return ResponseEntity.ok(ApiResponse.success(detail));
} catch (Exception e) {
log.error("获取审批实例详情失败: instanceCode={}", instanceCode, e);
return ResponseEntity.ok(ApiResponse.error(500, e.getMessage()));
}
}
/**
* 根据报销单ID获取审批进度
*/
@GetMapping("/approval/application/{applicationId}")
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public ResponseEntity<ApiResponse<Object>> getApprovalTimelineByApplication(
@PathVariable Long applicationId) {
try {
java.util.List<FeishuApprovalResponse.TimelineNode> timeline = feishuApprovalService.getApprovalTimelineByApplication(applicationId);
return ResponseEntity.ok(ApiResponse.success(timeline));
} catch (Exception e) {
log.error("获取报销审批进度失败: applicationId={}", applicationId, e);
return ResponseEntity.ok(ApiResponse.error(500, e.getMessage()));
}
}
}
@@ -0,0 +1,175 @@
package com.finance.system.controller;
import com.finance.system.adapter.feishu.FeishuAuthService;
import com.finance.system.adapter.feishu.FeishuTokenResponse;
import com.finance.system.adapter.feishu.FeishuUserInfo;
import com.finance.system.config.JwtConfig;
import com.finance.system.dto.ApiResponse;
import com.finance.system.dto.LoginResponse;
import com.finance.system.dto.UserProfile;
import com.finance.system.entity.SysDepartment;
import com.finance.system.entity.SysUser;
import com.finance.system.exception.BusinessException;
import com.finance.system.repository.SysDepartmentRepository;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.service.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/feishu")
@RequiredArgsConstructor
public class FeishuCallbackController {
private final FeishuAuthService feishuAuthService;
private final JwtConfig jwtConfig;
private final SysUserRepository sysUserRepository;
private final SysDepartmentRepository sysDepartmentRepository;
/**
* 飞书登录接口 - 返回JSON而非重定向
* 前端先获取authUrl,用户授权后回调到前端,前端再调用此接口交换token
*/
@PostMapping("/login")
public ResponseEntity<ApiResponse<LoginResponse>> feishuLogin(
@RequestBody Map<String, String> request,
@CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) {
String code = request.get("code");
String state = request.get("state");
if (code == null || code.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "授权码不能为空"));
}
try {
feishuAuthService.validateCallbackState(state, browserState, true);
// 1. 交换access_token
FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code);
String accessToken = tokenResponse.getData().getAccessToken();
log.info("飞书access_token获取成功");
// 2. 获取用户信息
FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken);
log.info("飞书用户信息获取成功: name={}, openId={}", feishuUserInfo.getName(), feishuUserInfo.getOpenId());
// 3. 查找已绑定的本地用户
SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo);
log.info("用户绑定成功: userId={}, realName={}", user.getId(), user.getRealName());
if (!isActive(user)) {
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
}
// 4. 生成JWT token
JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl(
user.getId(),
user.getEmployeeNo(),
user.getRealName(),
RoleService.normalize(user.getUserType()));
// Profile/binding/lastLogin were committed by the shared locked login finalizer.
// 6. 构建用户档案
UserProfile profile = buildUserProfile(user);
LoginResponse loginResponse = LoginResponse.builder()
.token(generatedToken.getToken())
.tokenType("Bearer")
.expiresIn(generatedToken.getExpiresIn())
.user(profile)
.build();
return ResponseEntity.ok(ApiResponse.success(loginResponse));
} catch (BusinessException e) {
log.warn("飞书登录失败: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(e.getStatusCode(), e.getMessage()));
} catch (Exception e) {
log.error("飞书登录失败", e);
return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试"));
}
}
/**
* GET方式也支持(通过查询参数传递code)
*/
@GetMapping("/login")
public ResponseEntity<ApiResponse<LoginResponse>> feishuLoginGet(
@RequestParam("code") String code,
@RequestParam("state") String state,
@CookieValue(value = "FEISHU_OAUTH_STATE", required = false) String browserState) {
if (code == null || code.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "授权码不能为空"));
}
try {
feishuAuthService.validateCallbackState(state, browserState, true);
FeishuTokenResponse tokenResponse = feishuAuthService.getAccessToken(code);
String accessToken = tokenResponse.getData().getAccessToken();
FeishuUserInfo feishuUserInfo = feishuAuthService.getUserInfo(accessToken);
SysUser user = feishuAuthService.findOrCreateUser(feishuUserInfo);
if (!isActive(user)) {
return ResponseEntity.status(403).body(ApiResponse.error(403, "用户已停用"));
}
JwtConfig.GeneratedToken generatedToken = jwtConfig.generateTokenWithTtl(
user.getId(),
user.getEmployeeNo(),
user.getRealName(),
RoleService.normalize(user.getUserType()));
UserProfile profile = buildUserProfile(user);
LoginResponse loginResponse = LoginResponse.builder()
.token(generatedToken.getToken())
.tokenType("Bearer")
.expiresIn(generatedToken.getExpiresIn())
.user(profile)
.build();
return ResponseEntity.ok(ApiResponse.success(loginResponse));
} catch (BusinessException e) {
log.warn("飞书登录失败: {}", e.getMessage());
return ResponseEntity.status(e.getStatusCode())
.body(ApiResponse.error(e.getStatusCode(), e.getMessage()));
} catch (Exception e) {
log.error("飞书登录失败", e);
return ResponseEntity.status(500).body(ApiResponse.error(500, "飞书登录失败,请稍后重试"));
}
}
private UserProfile buildUserProfile(SysUser user) {
String deptName = null;
if (user.getDepartmentId() != null) {
SysDepartment dept = sysDepartmentRepository.findById(user.getDepartmentId()).orElse(null);
if (dept != null) {
deptName = dept.getDeptName();
}
}
return UserProfile.builder()
.id(user.getId())
.employeeNo(user.getEmployeeNo())
.realName(user.getRealName())
.avatarUrl(user.getAvatarUrl())
.email(user.getEmail())
.departmentName(deptName)
.position(user.getPosition())
.userType(RoleService.normalize(user.getUserType()))
.status(user.getStatus())
.feishuStatus(user.getFeishuOpenId() != null ? "已授权" : "未绑定")
.lastLoginAt(user.getLastLoginAt() != null ? user.getLastLoginAt().toString().replace("T", " ") : null)
.build();
}
private boolean isActive(SysUser user) {
return user != null && "ACTIVE".equalsIgnoreCase(user.getStatus());
}
}
@@ -0,0 +1,32 @@
package com.finance.system.controller;
import com.finance.system.adapter.feishu.FeishuDirectoryService;
import com.finance.system.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/feishu/directory")
public class FeishuDirectoryController {
private final FeishuDirectoryService directory;
@PostMapping("/sync")
@PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync')")
public ResponseEntity<ApiResponse<FeishuDirectoryService.Run>> sync() {
FeishuDirectoryService.Run run = directory.sync("MANUAL");
return ResponseEntity.status(run.isApplied() ? 200 : 503).body(run.isApplied() ? ApiResponse.success(run)
: ApiResponse.error(503, run.getErrorMessage(), run));
}
@GetMapping("/status")
@PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync') or @permissionChecker.has(authentication, 'system:feishu:bind')")
public ApiResponse<Map<String,Object>> status() { return ApiResponse.success(directory.status()); }
@GetMapping("/organization")
@PreAuthorize("@permissionChecker.has(authentication, 'system:feishu:sync') or @permissionChecker.has(authentication, 'system:feishu:bind')")
public ApiResponse<Map<String,Object>> organization() {
return ApiResponse.success(directory.organization());
}
}
@@ -0,0 +1,31 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.service.IntegrationConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/integrations/config")
@RequiredArgsConstructor
public class IntegrationConfigController {
private final IntegrationConfigService service;
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:integration:view')")
public ResponseEntity<ApiResponse<Map<String, Object>>> get() { return ResponseEntity.ok(ApiResponse.success(service.view())); }
@PutMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:integration:manage')")
public ResponseEntity<ApiResponse<Void>> put(@RequestBody Map<String, Object> body) { service.update(body); return ResponseEntity.ok(ApiResponse.success()); }
@PostMapping("/test")
@PreAuthorize("@permissionChecker.has(authentication, 'system:integration:test')")
public ResponseEntity<ApiResponse<Map<String, Object>>> test(@RequestBody Map<String, Object> body) {
Object provider = body == null ? null : body.get("provider"); return ResponseEntity.ok(ApiResponse.success(service.test(provider == null ? null : String.valueOf(provider))));
}
}
@@ -0,0 +1,98 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/api/logs")
@RequiredArgsConstructor
public class LogController {
/**
* Mock数据 - 操作日志
*/
private static final List<Map<String, Object>> MOCK_LOGS = new ArrayList<>();
static {
addLog("系统", "飞书审批同步", "审批实例 20260801001 同步完成", "审批同步");
addLog("李志豪", "提交报销", "报销单 BX20260812001 已提交审批", "报销申请");
addLog("刘雅", "应付会计审核", "报销单 BX20260809003 审核通过", "审批操作");
addLog("周岚", "财务经理审批", "报销单 BX20260808006 审批通过", "审批操作");
addLog("周敏", "登记付款", "报销单 BX20260728004 登记付款 ¥1,800.00", "付款操作");
addLog("系统", "金蝶同步", "来源单据 TRIP2026072804 同步完成", "数据同步");
addLog("李志豪", "补充材料", "报销单 BX20260812001 补充材料并重新提交", "报销申请");
addLog("刘雅", "收单确认", "报销单 BX20260801009 财务收单完成", "收单操作");
}
private static void addLog(String operator, String action, String detail, String category) {
Map<String, Object> logEntry = new LinkedHashMap<>();
logEntry.put("id", (long) (MOCK_LOGS.size() + 1));
logEntry.put("operator", operator);
logEntry.put("action", action);
logEntry.put("detail", detail);
logEntry.put("category", category);
logEntry.put("time", getLogTime(MOCK_LOGS.size()));
MOCK_LOGS.add(logEntry);
}
private static String getLogTime(int index) {
String[] times = {
"2026-08-12 14:30:00",
"2026-08-12 10:24:00",
"2026-08-10 09:16:00",
"2026-08-09 14:08:00",
"2026-08-03 15:24:00",
"2026-08-03 14:00:00",
"2026-08-01 09:42:00",
"2026-07-28 16:00:00"
};
return index < times.length ? times[index] : java.time.LocalDateTime.now().toString().replace("T", " ");
}
/**
* 获取操作日志列表
*/
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'approval:view')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listLogs(
@RequestParam(required = false) String category,
@RequestParam(required = false) String operator,
@RequestParam(defaultValue = "50") int limit) {
try {
List<Map<String, Object>> result = new ArrayList<>(MOCK_LOGS);
if (category != null && !category.isEmpty()) {
result.removeIf(log -> !category.equals(log.get("category")));
}
if (operator != null && !operator.isEmpty()) {
result.removeIf(log -> !operator.equals(log.get("operator")));
}
// 按时间倒序排列
result.sort((a, b) -> {
String timeA = (String) a.get("time");
String timeB = (String) b.get("time");
return timeB.compareTo(timeA);
});
// 限制数量
if (result.size() > limit) {
result = result.subList(0, limit);
}
return ResponseEntity.ok(ApiResponse.success(result));
} catch (Exception e) {
log.error("获取操作日志列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取操作日志列表失败: " + e.getMessage()));
}
}
}
@@ -0,0 +1,158 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/api/metadata")
@RequiredArgsConstructor
public class MetadataController {
/**
* Mock数据 - 费用类型
*/
private static final List<Map<String, Object>> EXPENSE_TYPES = new ArrayList<>();
static {
Map<String, Object> et1 = new LinkedHashMap<>();
et1.put("id", 1);
et1.put("code", "EMPLOYEE_REIMBURSEMENT");
et1.put("name", "员工报销类");
et1.put("category", "员工报销");
et1.put("description", "员工因公产生的差旅、交通、招待等费用报销");
EXPENSE_TYPES.add(et1);
Map<String, Object> et2 = new LinkedHashMap<>();
et2.put("id", 2);
et2.put("code", "TRAVEL_TRANSPORTATION");
et2.put("name", "差旅交通");
et2.put("category", "差旅交通");
et2.put("description", "出差期间产生的交通费用");
EXPENSE_TYPES.add(et2);
Map<String, Object> et3 = new LinkedHashMap<>();
et3.put("id", 3);
et3.put("code", "ACCOMMODATION");
et3.put("name", "住宿费");
et3.put("category", "住宿费");
et3.put("description", "出差期间住宿费用");
EXPENSE_TYPES.add(et3);
Map<String, Object> et4 = new LinkedHashMap<>();
et4.put("id", 4);
et4.put("code", "BUSINESS_ENTERTAINMENT");
et4.put("name", "业务招待");
et4.put("category", "业务招待");
et4.put("description", "客户招待、商务用餐等费用");
EXPENSE_TYPES.add(et4);
Map<String, Object> et5 = new LinkedHashMap<>();
et5.put("id", 5);
et5.put("code", "TRAVEL_ALLOWANCE");
et5.put("name", "差旅补贴");
et5.put("category", "差旅补贴");
et5.put("description", "出差补贴费用");
EXPENSE_TYPES.add(et5);
Map<String, Object> et6 = new LinkedHashMap<>();
et6.put("id", 6);
et6.put("code", "OFFICE_EXPENSE");
et6.put("name", "办公费用");
et6.put("category", "办公费用");
et6.put("description", "办公用品、耗材等费用");
EXPENSE_TYPES.add(et6);
}
/**
* Mock数据 - 收款人
*/
private static final List<Map<String, Object>> PAYEES = new ArrayList<>();
static {
Map<String, Object> p1 = new LinkedHashMap<>();
p1.put("id", 1);
p1.put("name", "李志豪");
p1.put("employeeNo", "EMP000086");
p1.put("department", "销售中心");
p1.put("bankName", "中国工商银行苏州新区支行");
p1.put("bankAccount", "6222 0200 0086 0728");
PAYEES.add(p1);
Map<String, Object> p2 = new LinkedHashMap<>();
p2.put("id", 2);
p2.put("name", "王忠辉");
p2.put("employeeNo", "EMP000087");
p2.put("department", "数字化中心");
p2.put("bankName", "招商银行苏州分行");
p2.put("bankAccount", "6222 **** 3402");
PAYEES.add(p2);
Map<String, Object> p3 = new LinkedHashMap<>();
p3.put("id", 3);
p3.put("name", "赵海峰");
p3.put("employeeNo", "EMP000088");
p3.put("department", "供应链中心");
p3.put("bankName", "招商银行苏州工业园区支行");
p3.put("bankAccount", "6214 **** 8001");
PAYEES.add(p3);
}
/**
* 获取费用类型列表
*/
@GetMapping("/expense-types")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExpenseTypes() {
try {
return ResponseEntity.ok(ApiResponse.success(EXPENSE_TYPES));
} catch (Exception e) {
log.error("获取费用类型列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取费用类型列表失败: " + e.getMessage()));
}
}
/**
* 获取收款人列表
*/
@GetMapping("/payees")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getPayees(
@RequestParam(required = false) String keyword) {
try {
List<Map<String, Object>> result = PAYEES.stream().map(payee -> {
Map<String, Object> safe = new LinkedHashMap<>(payee);
Object rawAccount = safe.remove("bankAccount");
if (rawAccount != null) safe.put("bankAccountMask", maskAccount(String.valueOf(rawAccount)));
return safe;
}).collect(Collectors.toList());
if (keyword != null && !keyword.isEmpty()) {
String lowerKeyword = keyword.toLowerCase();
result.removeIf(p -> {
String name = (String) p.get("name");
String empNo = (String) p.get("employeeNo");
return !(name != null && name.toLowerCase().contains(lowerKeyword))
&& !(empNo != null && empNo.toLowerCase().contains(lowerKeyword));
});
}
return ResponseEntity.ok(ApiResponse.success(result));
} catch (Exception e) {
log.error("获取收款人列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取收款人列表失败: " + e.getMessage()));
}
}
private static String maskAccount(String value) {
String digits = value.replaceAll("\\s+", "");
if (digits.length() <= 4) return "已脱敏";
return "**** " + digits.substring(digits.length() - 4);
}
}
@@ -0,0 +1,200 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.security.UserPrincipal;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/api/payments")
@RequiredArgsConstructor
public class PaymentController {
/**
* Mock数据 - 付款记录
*/
private static final List<Map<String, Object>> MOCK_PAYMENTS = new ArrayList<>();
static {
Map<String, Object> p1 = new LinkedHashMap<>();
p1.put("id", "PAY-20260803-01");
p1.put("applicationId", "BX20260728004");
p1.put("applicationNo", "BX20260728004");
p1.put("title", "上海项目住宿费");
p1.put("payee", "赵海峰");
p1.put("amount", new BigDecimal("1800.00"));
p1.put("paidAmount", new BigDecimal("1800.00"));
p1.put("unpaidAmount", new BigDecimal("2300.00"));
p1.put("time", "2026-08-03 15:24");
p1.put("method", "银行转账");
p1.put("account", "招商银行 · 9032");
p1.put("reference", "FLOW202608030883");
p1.put("operator", "周敏");
p1.put("status", "有效");
p1.put("expenseType", "员工报销类");
MOCK_PAYMENTS.add(p1);
}
/**
* Mock数据 - 付款申请列表(带付款信息)
*/
private static final List<Map<String, Object>> MOCK_PAYMENT_APPLICATIONS = new ArrayList<>();
static {
Map<String, Object> a1 = new LinkedHashMap<>();
a1.put("id", "BX20260728004");
a1.put("date", "2026-07-28");
a1.put("title", "上海项目住宿费");
a1.put("payee", "赵海峰");
a1.put("owner", "赵海峰");
a1.put("department", "供应链中心");
a1.put("amount", new BigDecimal("4100.00"));
a1.put("paidAmount", new BigDecimal("1800.00"));
a1.put("unpaidAmount", new BigDecimal("2300.00"));
a1.put("receiptStatus", "已收单");
a1.put("paymentStatus", "部分付款");
a1.put("expenseType", "员工报销类");
MOCK_PAYMENT_APPLICATIONS.add(a1);
Map<String, Object> a2 = new LinkedHashMap<>();
a2.put("id", "BX20260801009");
a2.put("date", "2026-08-01");
a2.put("title", "七月云资源差旅补贴");
a2.put("payee", "王忠辉");
a2.put("owner", "王忠辉");
a2.put("department", "数字化中心");
a2.put("amount", new BigDecimal("3200.00"));
a2.put("paidAmount", new BigDecimal("0.00"));
a2.put("unpaidAmount", new BigDecimal("3200.00"));
a2.put("receiptStatus", "已收单");
a2.put("paymentStatus", "未付款");
a2.put("expenseType", "员工报销类");
MOCK_PAYMENT_APPLICATIONS.add(a2);
Map<String, Object> a3 = new LinkedHashMap<>();
a3.put("id", "BX20260802011");
a3.put("date", "2026-08-02");
a3.put("title", "苏州园区客户拜访费用");
a3.put("payee", "赵海峰");
a3.put("owner", "赵海峰");
a3.put("department", "供应链中心");
a3.put("amount", new BigDecimal("2180.00"));
a3.put("paidAmount", new BigDecimal("0.00"));
a3.put("unpaidAmount", new BigDecimal("2180.00"));
a3.put("receiptStatus", "待收单");
a3.put("paymentStatus", "未付款");
a3.put("expenseType", "员工报销类");
MOCK_PAYMENT_APPLICATIONS.add(a3);
Map<String, Object> a4 = new LinkedHashMap<>();
a4.put("id", "BX20260809003");
a4.put("date", "2026-08-09");
a4.put("title", "八月客户拜访交通费");
a4.put("payee", "李志豪");
a4.put("owner", "李志豪");
a4.put("department", "销售中心");
a4.put("amount", new BigDecimal("1260.00"));
a4.put("paidAmount", new BigDecimal("0.00"));
a4.put("unpaidAmount", new BigDecimal("1260.00"));
a4.put("receiptStatus", "未触发");
a4.put("paymentStatus", "未付款");
a4.put("expenseType", "员工报销类");
MOCK_PAYMENT_APPLICATIONS.add(a4);
}
/**
* 获取付款列表(资金出纳B视图,过滤 expenseType=员工报销类)
*/
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')")
public ResponseEntity<ApiResponse<Map<String, Object>>> listPayments(
@RequestParam(required = false) String status,
@RequestParam(required = false) String expenseType) {
try {
List<Map<String, Object>> applications = new ArrayList<>(MOCK_PAYMENT_APPLICATIONS);
// 默认过滤 expenseType=员工报销类
if (expenseType != null && !expenseType.isEmpty()) {
applications.removeIf(app -> !expenseType.equals(app.get("expenseType")));
} else {
applications.removeIf(app -> !"员工报销类".equals(app.get("expenseType")));
}
// 按付款状态过滤
if (status != null && !status.isEmpty()) {
applications.removeIf(app -> !status.equals(app.get("paymentStatus")));
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("applications", applications);
result.put("payments", new ArrayList<>(MOCK_PAYMENTS));
result.put("total", applications.size());
return ResponseEntity.ok(ApiResponse.success(result));
} catch (Exception e) {
log.error("获取付款列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取付款列表失败: " + e.getMessage()));
}
}
/**
* 登记付款
*/
@PostMapping("/register")
@PreAuthorize("@permissionChecker.has(authentication, 'payment:register')")
public ResponseEntity<ApiResponse<Map<String, Object>>> registerPayment(@RequestBody Map<String, Object> request) {
try {
UserPrincipal principal = AuditUtil.getCurrentUser();
String applicationNo = (String) request.get("applicationNo");
Object amountObj = request.get("amount");
BigDecimal amount;
if (amountObj instanceof Number) {
amount = new BigDecimal(((Number) amountObj).toString());
} else {
amount = new BigDecimal(String.valueOf(amountObj));
}
String method = (String) request.getOrDefault("method", "银行转账");
String account = (String) request.getOrDefault("account", "招商银行 · 9032");
String reference = (String) request.getOrDefault("reference", "FLOW-" + System.currentTimeMillis());
if (applicationNo == null || applicationNo.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "申请单号不能为空"));
}
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(400, "付款金额必须大于0"));
}
// 创建付款记录
Map<String, Object> payment = new LinkedHashMap<>();
payment.put("id", "PAY-" + java.time.LocalDate.now().toString().replace("-", "") + "-" + String.format("%02d", MOCK_PAYMENTS.size() + 1));
payment.put("applicationNo", applicationNo);
payment.put("amount", amount);
payment.put("time", java.time.LocalDateTime.now().toString().replace("T", " "));
payment.put("method", method);
payment.put("account", account);
payment.put("reference", reference);
payment.put("operator", principal != null ? principal.getRealName() : "系统");
payment.put("status", "有效");
// 添加到mock列表
MOCK_PAYMENTS.add(payment);
log.info("付款登记成功: applicationNo={}, amount={}", applicationNo, amount);
return ResponseEntity.ok(ApiResponse.success(payment));
} catch (Exception e) {
log.error("登记付款失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "登记付款失败: " + e.getMessage()));
}
}
}
@@ -0,0 +1,102 @@
package com.finance.system.controller;
import com.finance.system.dto.*;
import com.finance.system.service.ReimApplicationService;
import com.finance.system.util.AuditUtil;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/reimbursements")
@RequiredArgsConstructor
public class ReimApplicationController {
private final ReimApplicationService reimApplicationService;
@GetMapping("/workbench")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')")
public ResponseEntity<ApiResponse<WorkbenchDto>> getWorkbench() {
Long userId = AuditUtil.getCurrentUserId();
WorkbenchDto workbench = reimApplicationService.getWorkbench(userId);
return ResponseEntity.ok(ApiResponse.success(workbench));
}
@GetMapping("/my")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own')")
public ResponseEntity<ApiResponse<PageResponse<ReimApplicationSummary>>> getMyApplications(
@RequestParam(required = false) String status,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
Long userId = AuditUtil.getCurrentUserId();
Pageable pageable = PageRequest.of(page, size);
Page<ReimApplicationSummary> applications = reimApplicationService.getMyApplications(userId, status, pageable);
return ResponseEntity.ok(ApiResponse.success(PageResponse.of(
applications.getContent(), applications.getTotalElements(), page, size)));
}
@GetMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getDetail(@PathVariable Long id) {
Long userId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.getApplicationDetail(id, userId);
return ResponseEntity.ok(ApiResponse.success(detail));
}
@GetMapping("/no/{applicationNo}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-own') || @permissionChecker.has(authentication, 'application:view-own') || @permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> getByApplicationNo(
@PathVariable String applicationNo) {
Long userId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.getByApplicationNo(applicationNo, userId);
return ResponseEntity.ok(ApiResponse.success(detail));
}
@PostMapping
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> create(
@Valid @RequestBody CreateApplicationRequest request) {
Long userId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.createApplication(request, userId);
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(detail));
}
@PutMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> update(
@PathVariable Long id,
@RequestBody CreateApplicationRequest request) {
Long userId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.updateApplication(id, request, userId);
return ResponseEntity.ok(ApiResponse.success(detail));
}
@PostMapping("/{id}/submit")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> submit(@PathVariable Long id) {
Long userId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.submitApplication(id, userId);
return ResponseEntity.ok(ApiResponse.success(detail));
}
@PostMapping("/{id}/receive")
@PreAuthorize("@permissionChecker.has(authentication, 'receipt:manage')")
public ResponseEntity<ApiResponse<ReimApplicationDetail>> receive(@PathVariable Long id) {
Long operatorId = AuditUtil.getCurrentUserId();
ReimApplicationDetail detail = reimApplicationService.receiveApplication(id, operatorId);
return ResponseEntity.ok(ApiResponse.success(detail));
}
@DeleteMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:create') || @permissionChecker.has(authentication, 'application:create')")
public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) {
reimApplicationService.deleteApplication(id, AuditUtil.getCurrentUserId());
return ResponseEntity.ok(ApiResponse.success());
}
}
@@ -0,0 +1,104 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.entity.SysRole;
import com.finance.system.entity.SysUser;
import com.finance.system.repository.SysUserRepository;
import com.finance.system.security.UserPrincipal;
import com.finance.system.service.RoleService;
import com.finance.system.util.AuditUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/roles")
public class RoleController {
private final SysUserRepository sysUserRepository;
private RoleService roleService;
public RoleController(SysUserRepository sysUserRepository) { this.sysUserRepository = sysUserRepository; }
@Autowired(required = false)
public void setRoleService(RoleService roleService) { this.roleService = roleService; }
private static final List<Map<String, Object>> ROLE_PROFILES = new ArrayList<>();
static {
ROLE_PROFILES.add(profile(1, "SUPER_ADMIN", "超级管理员", "历史兼容角色 - 全功能访问", "*"));
ROLE_PROFILES.add(profile(2, "FINANCE", "财务人员", "财务人员 - 收单管理、付款登记、审批查看、基础数据",
"reimbursement:view-all", "receipt:manage", "payment:register", "approval:view", "master-data:manage"));
ROLE_PROFILES.add(profile(3, "EMPLOYEE", "员工", "普通员工 - 发起报销、查看个人报销进度",
"reimbursement:create", "reimbursement:view-own"));
}
private static Map<String, Object> profile(int id, String code, String name, String description, String... permissions) {
Map<String, Object> value = new LinkedHashMap<>(); value.put("id", id); value.put("code", code);
value.put("name", name); value.put("description", description); value.put("permissions", Arrays.asList(permissions)); return value;
}
/** Kept for the existing login page contract. */
@GetMapping("/profiles")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getRoleProfiles() { return ResponseEntity.ok(ApiResponse.success(ROLE_PROFILES)); }
/** Kept for the existing role drawer contract. */
@GetMapping("/current")
public ResponseEntity<ApiResponse<Map<String, Object>>> getCurrentRole() {
UserPrincipal principal = AuditUtil.getCurrentUser();
if (principal == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录"));
SysUser user = sysUserRepository.findById(principal.getId()).orElse(null);
if (user == null) return ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在"));
String userType = RoleService.normalize(user.getUserType());
Map<String, Object> result = new LinkedHashMap<>(); result.put("userId", user.getId()); result.put("employeeNo", user.getEmployeeNo());
result.put("realName", user.getRealName()); result.put("userType", userType); result.put("roleName", display(userType));
Map<String, Object> profile = findProfile(userType);
if (roleService != null) result.put("permissions", roleService.currentPermissionsMap(user.getId()).get("permissionCodes"));
else result.put("permissions", profile == null ? Collections.emptyList() : profile.get("permissions"));
return ResponseEntity.ok(ApiResponse.success(result));
}
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listRoles())); }
@PostMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')")
public ResponseEntity<ApiResponse<Map<String, Object>>> create(@RequestBody Map<String, Object> body) {
return ResponseEntity.status(201).body(ApiResponse.success(toMap(roleService.saveRole(null, body))));
}
@PutMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')")
public ResponseEntity<ApiResponse<Map<String, Object>>> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
return ResponseEntity.ok(ApiResponse.success(toMap(roleService.saveRole(id, body))));
}
@DeleteMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')")
public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) { roleService.deleteRole(id); return ResponseEntity.ok(ApiResponse.success()); }
@GetMapping("/permissions")
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> catalog() { return ResponseEntity.ok(ApiResponse.success(roleService.permissionCatalog())); }
@GetMapping("/{id}/permissions")
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:view')")
public ResponseEntity<ApiResponse<Map<String, Object>>> getPermissions(@PathVariable Long id) { return ResponseEntity.ok(ApiResponse.success(roleService.rolePermissions(id))); }
@PutMapping("/{id}/permissions")
@PreAuthorize("@permissionChecker.has(authentication, 'system:role:manage')")
public ResponseEntity<ApiResponse<Void>> setPermissions(@PathVariable Long id, @RequestBody Map<String, Object> body) {
roleService.replaceRolePermissions(id, body, AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success());
}
@GetMapping("/current-permissions")
public ResponseEntity<ApiResponse<Map<String, Object>>> currentPermissions() {
Long userId = AuditUtil.getCurrentUserId(); if (userId == null) return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录"));
return ResponseEntity.ok(ApiResponse.success(roleService.currentPermissionsMap(userId)));
}
private Map<String, Object> findProfile(String code) { for (Map<String, Object> x : ROLE_PROFILES) if (code.equals(x.get("code"))) return x; return null; }
private String display(String code) { if ("SUPER_ADMIN".equals(code)) return "超级管理员"; if ("FINANCE".equals(code)) return "财务人员"; return "员工"; }
private Map<String, Object> toMap(SysRole role) { Map<String, Object> x = new LinkedHashMap<>(); x.put("id", role.getId()); x.put("roleCode", role.getRoleCode()); x.put("roleName", role.getRoleName()); x.put("description", role.getDescription()); x.put("status", role.getStatus()); x.put("builtIn", role.getBuiltIn()); return x; }
}
@@ -0,0 +1,203 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/api/sources")
@RequiredArgsConstructor
public class SourceDocumentController {
/**
* Mock数据 - 业务单据(来源单据)
*/
private static final List<Map<String, Object>> MOCK_SOURCES = new ArrayList<>();
static {
Map<String, Object> s1 = new LinkedHashMap<>();
s1.put("id", 1L);
s1.put("sourceDocNo", "TRIP2026072804");
s1.put("sourceDocType", "费用报销单");
s1.put("sourceSystem", "金蝶 ERP");
s1.put("sourceDate", "2026-07-28");
s1.put("sourceStatus", "已同步");
s1.put("title", "上海项目住宿费");
s1.put("amount", new BigDecimal("4100.00"));
s1.put("payee", "赵海峰");
s1.put("department", "供应链中心");
s1.put("bankName", "招商银行苏州工业园区支行");
s1.put("bankAccount", "6214 **** 8001");
s1.put("description", "上海项目住宿费用。");
s1.put("lastSyncTime", "2026-08-03 15:24");
MOCK_SOURCES.add(s1);
Map<String, Object> s2 = new LinkedHashMap<>();
s2.put("id", 2L);
s2.put("sourceDocNo", "TRIP2026080106");
s2.put("sourceDocType", "费用报销单");
s2.put("sourceSystem", "金蝶 ERP");
s2.put("sourceDate", "2026-08-01");
s2.put("sourceStatus", "已同步");
s2.put("title", "苏州园区客户拜访费用");
s2.put("amount", new BigDecimal("2180.00"));
s2.put("payee", "赵海峰");
s2.put("department", "供应链中心");
s2.put("bankName", "招商银行苏州工业园区支行");
s2.put("bankAccount", "6214 **** 8001");
s2.put("description", "园区客户拜访交通与停车费用。");
s2.put("lastSyncTime", "2026-08-03 15:24");
MOCK_SOURCES.add(s2);
Map<String, Object> s3 = new LinkedHashMap<>();
s3.put("id", 3L);
s3.put("sourceDocNo", "TRIP2026073108");
s3.put("sourceDocType", "费用报销单");
s3.put("sourceSystem", "金蝶 ERP");
s3.put("sourceDate", "2026-07-31");
s3.put("sourceStatus", "已同步");
s3.put("title", "七月云资源差旅补贴");
s3.put("amount", new BigDecimal("3200.00"));
s3.put("payee", "王忠辉");
s3.put("department", "数字化中心");
s3.put("bankName", "招商银行苏州分行");
s3.put("bankAccount", "6222 **** 3402");
s3.put("description", "七月现场支持差旅补贴。");
s3.put("lastSyncTime", "2026-08-03 15:24");
MOCK_SOURCES.add(s3);
Map<String, Object> s4 = new LinkedHashMap<>();
s4.put("id", 4L);
s4.put("sourceDocNo", "TRIP2026080903");
s4.put("sourceDocType", "费用报销单");
s4.put("sourceSystem", "金蝶 ERP");
s4.put("sourceDate", "2026-08-09");
s4.put("sourceStatus", "已同步");
s4.put("title", "八月客户拜访交通费");
s4.put("amount", new BigDecimal("1260.00"));
s4.put("payee", "李志豪");
s4.put("department", "销售中心");
s4.put("bankName", "中国工商银行苏州新区支行");
s4.put("bankAccount", "6222 0200 0086 0728");
s4.put("description", "客户拜访交通费用。");
s4.put("lastSyncTime", "2026-08-10 09:16");
MOCK_SOURCES.add(s4);
Map<String, Object> s5 = new LinkedHashMap<>();
s5.put("id", 5L);
s5.put("sourceDocNo", "TRIP2026072602");
s5.put("sourceDocType", "费用报销单");
s5.put("sourceSystem", "金蝶 ERP");
s5.put("sourceDate", "2026-07-26");
s5.put("sourceStatus", "已同步");
s5.put("title", "上海项目住宿费");
s5.put("amount", new BigDecimal("4100.00"));
s5.put("payee", "赵海峰");
s5.put("department", "供应链中心");
s5.put("bankName", "招商银行苏州工业园区支行");
s5.put("bankAccount", "6214 **** 8001");
s5.put("description", "上海项目住宿费用。");
s5.put("lastSyncTime", "2026-08-03 15:24");
MOCK_SOURCES.add(s5);
Map<String, Object> s6 = new LinkedHashMap<>();
s6.put("id", 6L);
s6.put("sourceDocNo", "TRIP2026072804");
s6.put("sourceDocType", "费用报销单");
s6.put("sourceSystem", "金蝶 ERP");
s6.put("sourceDate", "2026-07-28");
s6.put("sourceStatus", "已同步");
s6.put("title", "上海客户现场技术交流差旅");
s6.put("amount", new BigDecimal("3286.50"));
s6.put("payee", "李志豪");
s6.put("department", "销售中心");
s6.put("bankName", "中国工商银行苏州新区支行");
s6.put("bankAccount", "6222 0200 0086 0728");
s6.put("description", "上海客户现场技术交流产生的交通及住宿费用。");
s6.put("lastSyncTime", "2026-08-12 10:24");
MOCK_SOURCES.add(s6);
}
/**
* 获取业务单据列表
*/
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listSources(
@RequestParam(required = false) String sourceSystem,
@RequestParam(required = false) String sourceStatus) {
try {
List<Map<String, Object>> result = MOCK_SOURCES.stream()
.map(this::safeSource)
.collect(java.util.stream.Collectors.toList());
if (sourceSystem != null && !sourceSystem.isEmpty()) {
result.removeIf(s -> !sourceSystem.equals(s.get("sourceSystem")));
}
if (sourceStatus != null && !sourceStatus.isEmpty()) {
result.removeIf(s -> !sourceStatus.equals(s.get("sourceStatus")));
}
return ResponseEntity.ok(ApiResponse.success(result));
} catch (Exception e) {
log.error("获取业务单据列表失败", e);
return ResponseEntity.ok(ApiResponse.error(500, "获取业务单据列表失败: " + e.getMessage()));
}
}
/**
* 获取业务单据详情
*/
@GetMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'reimbursement:view-all')")
public ResponseEntity<ApiResponse<Map<String, Object>>> getSourceDetail(@PathVariable Long id) {
try {
Map<String, Object> source = MOCK_SOURCES.stream()
.filter(s -> id.equals(s.get("id")))
.findFirst()
.orElse(null);
if (source == null) {
return ResponseEntity.status(404)
.body(ApiResponse.error(404, "业务单据不存在: " + id));
}
// 追加详细信息
Map<String, Object> detail = safeSource(source);
detail.put("remarks", "金蝶来源单据由外部系统同步,平台不允许修改抬头、收款账户或来源金额。");
detail.put("syncStatus", "已同步");
detail.put("relatedApplications", getRelatedApplications((String) source.get("sourceDocNo")));
return ResponseEntity.ok(ApiResponse.success(detail));
} catch (Exception e) {
log.error("获取业务单据详情失败: id={}", id, e);
return ResponseEntity.ok(ApiResponse.error(500, "获取业务单据详情失败: " + e.getMessage()));
}
}
private List<Map<String, String>> getRelatedApplications(String sourceDocNo) {
List<Map<String, String>> related = new ArrayList<>();
Map<String, String> app = new LinkedHashMap<>();
app.put("applicationNo", "BX20260728004");
app.put("title", "上海项目住宿费");
related.add(app);
return related;
}
private Map<String, Object> safeSource(Map<String, Object> source) {
Map<String, Object> safe = new LinkedHashMap<>(source);
Object rawAccount = safe.remove("bankAccount");
if (rawAccount != null) {
String digits = String.valueOf(rawAccount).replaceAll("\\s+", "");
safe.put("bankAccountMask", digits.length() > 4 ? "**** " + digits.substring(digits.length() - 4) : "已脱敏");
}
return safe;
}
}
@@ -0,0 +1,79 @@
package com.finance.system.controller;
import com.finance.system.dto.ApiResponse;
import com.finance.system.entity.SysUserGroup;
import com.finance.system.service.RoleService;
import com.finance.system.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/user-groups")
@RequiredArgsConstructor
public class UserGroupController {
private final RoleService roleService;
@GetMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list() { return ResponseEntity.ok(ApiResponse.success(roleService.listGroups())); }
@PostMapping
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
public ResponseEntity<ApiResponse<Map<String, Object>>> create(@RequestBody Map<String, Object> body) {
return ResponseEntity.status(201).body(ApiResponse.success(groupMap(roleService.saveGroup(null, body))));
}
@PutMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
public ResponseEntity<ApiResponse<Map<String, Object>>> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
return ResponseEntity.ok(ApiResponse.success(groupMap(roleService.saveGroup(id, body))));
}
@DeleteMapping("/{id}")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) { roleService.deleteGroup(id); return ResponseEntity.ok(ApiResponse.success()); }
@GetMapping("/{id}/roles")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
public ResponseEntity<ApiResponse<Map<String, Object>>> roles(@PathVariable Long id) {
Map<String, Object> result = new LinkedHashMap<>(); result.put("roleIds", roleService.groupRoleIds(id)); return ResponseEntity.ok(ApiResponse.success(result));
}
@PutMapping("/{id}/roles")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
public ResponseEntity<ApiResponse<Void>> setRoles(@PathVariable Long id, @RequestBody Map<String, Object> body) {
roleService.replaceGroupRoles(id, requiredList(body, "roleIds"), AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success());
}
@GetMapping("/{id}/members")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
public ResponseEntity<ApiResponse<Map<String, Object>>> members(@PathVariable Long id) {
Map<String, Object> result = new LinkedHashMap<>(); result.put("userIds", roleService.groupMemberIds(id)); return ResponseEntity.ok(ApiResponse.success(result));
}
@PutMapping("/{id}/members")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:manage')")
public ResponseEntity<ApiResponse<Void>> setMembers(@PathVariable Long id, @RequestBody Map<String, Object> body) {
roleService.replaceGroupMembers(id, requiredList(body, "userIds"), AuditUtil.getCurrentUserId()); return ResponseEntity.ok(ApiResponse.success());
}
@GetMapping("/candidates")
@PreAuthorize("@permissionChecker.has(authentication, 'system:group:view')")
public ResponseEntity<ApiResponse<List<Map<String, Object>>>> candidates() { return ResponseEntity.ok(ApiResponse.success(roleService.candidates())); }
@SuppressWarnings("unchecked")
private List<?> requiredList(Map<String, Object> body, String key) {
Object value = body == null ? null : body.get(key);
if (!(value instanceof List)) throw new com.finance.system.exception.BadRequestException(key + " 必须是数组");
return (List<?>) value;
}
private Map<String, Object> groupMap(SysUserGroup group) {
Map<String, Object> result = new LinkedHashMap<>(); result.put("id", group.getId()); result.put("groupCode", group.getGroupCode());
result.put("groupName", group.getGroupName()); result.put("description", group.getDescription()); result.put("status", group.getStatus()); return result;
}
}
@@ -0,0 +1,56 @@
package com.finance.system.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResponse<T> {
private int code;
private String message;
private T data;
private LocalDateTime timestamp;
public static <T> ApiResponse<T> success(T data) {
return ApiResponse.<T>builder()
.code(200)
.message("success")
.data(data)
.timestamp(LocalDateTime.now())
.build();
}
public static <T> ApiResponse<T> success() {
return ApiResponse.<T>builder()
.code(200)
.message("success")
.timestamp(LocalDateTime.now())
.build();
}
public static <T> ApiResponse<T> error(int code, String message) {
return ApiResponse.<T>builder()
.code(code)
.message(message)
.timestamp(LocalDateTime.now())
.build();
}
public static <T> ApiResponse<T> error(int code, String message, T data) {
return ApiResponse.<T>builder()
.code(code)
.message(message)
.data(data)
.timestamp(LocalDateTime.now())
.build();
}
}
@@ -0,0 +1,10 @@
package com.finance.system.dto;
import lombok.Data;
@Data
public class ApprovalActionRequest {
private Long applicationId;
private String comment;
private String returnReason;
}
@@ -0,0 +1,20 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApprovalRecordDto {
private Long id;
private String nodeName;
private String approverName;
private String action;
private String comment;
private LocalDateTime actionTime;
}
@@ -0,0 +1,17 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AttachmentDto {
private Long id;
private String fileName;
private String fileType;
private String fileUrl;
}
@@ -0,0 +1,18 @@
package com.finance.system.dto;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
@Data
public class CreateApplicationRequest {
private String title;
private Long expenseTypeId;
private String category;
private BigDecimal totalAmount;
private String description;
private String payeeName;
private Long payeeBankId;
private List<ExpenseItemDto> items;
}
@@ -0,0 +1,16 @@
package com.finance.system.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class CreatePaymentRequest {
private Long applicationId;
private BigDecimal paymentAmount;
private String paymentMethod;
private String bankAccountNo;
private String referenceNo;
/** Optional body fallback; the HTTP Idempotency-Key header takes precedence. */
private String idempotencyKey;
private String remark;
}
@@ -0,0 +1,24 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DashboardStats {
private long totalApplications;
private long pendingApproval;
private long approved;
private long rejected;
private long pendingPayment;
private long unpaid;
private BigDecimal totalAmount;
private BigDecimal paidAmount;
private BigDecimal pendingAmount;
}
@@ -0,0 +1,21 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ExpenseItemDto {
private Long id;
private Integer seqNo;
private LocalDate expenseDate;
private String category;
private String description;
private BigDecimal amount;
}
@@ -0,0 +1,22 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class InvoiceDto {
private Long id;
private String invoiceNo;
private String invoiceType;
private LocalDate issueDate;
private BigDecimal amount;
private String sellerName;
private String verifyStatus;
}
@@ -0,0 +1,11 @@
package com.finance.system.dto;
import javax.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class LoginRequest {
@NotBlank(message = "员工编号不能为空")
private String employeeNo;
private String password;
}
@@ -0,0 +1,17 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LoginResponse {
private String token;
private String tokenType;
private long expiresIn;
private UserProfile user;
}
@@ -0,0 +1,31 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageResponse<T> {
private List<T> content;
private long totalElements;
private int totalPages;
private int currentPage;
private int pageSize;
public static <T> PageResponse<T> of(List<T> content, long totalElements, int currentPage, int pageSize) {
return PageResponse.<T>builder()
.content(content)
.totalElements(totalElements)
.totalPages((int) Math.ceil((double) totalElements / pageSize))
.currentPage(currentPage)
.pageSize(pageSize)
.build();
}
}
@@ -0,0 +1,30 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PaymentDetailDto {
private Long id;
private String applicationNo;
private String title;
private String payeeName;
private String departmentName;
private BigDecimal totalAmount;
private BigDecimal paidAmount;
private BigDecimal remainingAmount;
private String paymentStatus;
private String bankName;
private String branchName;
private String bankAccountMask;
private String accountName;
private List<PaymentRecordDto> paymentHistory;
private List<ApprovalRecordDto> approvalRecords;
}
@@ -0,0 +1,27 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PaymentRecordDto {
private Long id;
private String paymentNo;
private BigDecimal paymentAmount;
private BigDecimal totalAmount;
private BigDecimal paidAmount;
private BigDecimal remainingAmount;
private String paymentMethod;
private String referenceNo;
private String paymentStatus;
private String operatorName;
private LocalDateTime paymentTime;
private String remark;
}
@@ -0,0 +1,18 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PaymentResultDto {
private String paymentNo;
private BigDecimal amount;
private String paymentStatus;
private String message;
}
@@ -0,0 +1,32 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PaymentTaskDto {
private Long id;
private String applicationNo;
private String title;
private String payeeName;
private String departmentName;
private String expenseTypeName;
private BigDecimal totalAmount;
private BigDecimal paidAmount;
private BigDecimal remainingAmount;
private String paymentStatus;
private String receiptStatus;
private String approvalStatus;
private String bankName;
private String bankAccountMask;
private LocalDateTime submitTime;
private LocalDateTime createdAt;
}
@@ -0,0 +1,57 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReimApplicationDetail {
private Long id;
private String applicationNo;
private String title;
private Long applicantId;
private String applicantName;
private String applicantEmployeeNo;
private Long departmentId;
private String departmentName;
private Long expenseTypeId;
private String expenseTypeName;
private String category;
private BigDecimal totalAmount;
private String description;
private String applicationStatus;
private String approvalStatus;
private String currentApprovalNode;
private Long currentApproverId;
private String currentApproverName;
private String receiptStatus;
private String paymentStatus;
private String budgetStatus;
private String sourceDocNo;
private String sourceDocType;
private String sourceSystem;
private LocalDate sourceDocDate;
private String sourceStatus;
private String payeeName;
private Long payeeBankId;
private String bankName;
private String bankAccountMask;
private String returnReason;
private LocalDateTime submitTime;
private LocalDateTime approveTime;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private List<ExpenseItemDto> expenseItems;
private List<InvoiceDto> invoices;
private List<AttachmentDto> attachments;
private List<ApprovalRecordDto> approvalRecords;
private List<PaymentRecordDto> payments;
}
@@ -0,0 +1,34 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReimApplicationSummary {
private Long id;
private String applicationNo;
private String title;
private String applicantName;
private String departmentName;
private String expenseTypeName;
private String category;
private BigDecimal totalAmount;
private String applicationStatus;
private String approvalStatus;
private String currentApprovalNode;
private String receiptStatus;
private String paymentStatus;
private String budgetStatus;
private String sourceDocNo;
private String sourceStatus;
private String returnReason;
private LocalDateTime submitTime;
private LocalDateTime createdAt;
}
@@ -0,0 +1,28 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserProfile {
private Long id;
private String employeeNo;
private String realName;
private String avatarUrl;
private String email;
private String departmentName;
private String position;
private String userType;
private String status;
private String feishuStatus;
private String lastLoginAt;
private List<String> roleCodes;
private List<String> groupNames;
}
@@ -0,0 +1,18 @@
package com.finance.system.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WorkbenchDto {
private UserProfile user;
private List<ReimApplicationSummary> reimbursements;
private List<PaymentRecordDto> payments;
private DashboardStats stats;
}
@@ -0,0 +1,22 @@
package com.finance.system.entity;
import javax.persistence.*;
import java.time.Instant;
/** Mapping also supports the explicitly local Hibernate-created database. Mutated with fenced SQL. */
@Entity
@Table(name = "feishu_directory_state")
public class FeishuDirectoryState {
@Id private Integer id;
@Column(length = 36) private String owner;
private Instant leaseUntil;
@Column(length = 64) private String context;
@Column(columnDefinition = "TEXT") private String lastRun;
@Column(length = 36) private String lastSuccessfulRunId;
private Instant lastSuccessfulAt;
@Column(length = 64) private String successfulContext;
@Column(name = "last_snapshot", columnDefinition = "TEXT") private String lastSnapshot;
public String getLastSnapshot() { return lastSnapshot; }
public void setLastSnapshot(String lastSnapshot) { this.lastSnapshot = lastSnapshot; }
}
@@ -0,0 +1,52 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.time.LocalDateTime;
/**
* 飞书审批同步表
* 记录审批实例与报销单的关联关系
*/
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "int_feishu_approval")
public class IntFeishuApproval {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/** 关联报销申请ID */
@Column(name = "application_id", nullable = false)
private Long applicationId;
/** 飞书审批实例编码 */
@Column(name = "feishu_instance_code", length = 200)
private String feishuInstanceCode;
/** 飞书审批定义编码 */
@Column(name = "feishu_approval_code", length = 200)
private String feishuApprovalCode;
/** 审批状态: PENDING / APPROVED / REJECTED / CANCELLED */
@Column(name = "status", length = 30)
private String status = "PENDING";
/** 回调数据(原始JSON) */
@Column(name = "callback_data", columnDefinition = "TEXT")
private String callbackData;
/** 最后同步时间 */
@Column(name = "synced_at")
private LocalDateTime syncedAt;
/** 创建时间 */
@Column(name = "created_at")
private LocalDateTime createdAt;
}
@@ -0,0 +1,126 @@
package com.finance.system.entity;
import javax.persistence.*;
import org.hibernate.annotations.Where;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_application")
@Where(clause = "deleted = false")
public class ReimApplication {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "application_no", length = 50, nullable = false, unique = true)
private String applicationNo;
@Column(length = 500, nullable = false)
private String title;
@Column(name = "applicant_id", nullable = false)
private Long applicantId;
@Column(name = "department_id", nullable = false)
private Long departmentId;
@Column(name = "expense_type_id", nullable = false)
private Long expenseTypeId;
@Column(length = 100)
private String category;
@Column(name = "total_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal totalAmount;
@Column(columnDefinition = "TEXT")
private String description;
@Column(name = "application_status", length = 30, nullable = false)
private String applicationStatus;
@Column(name = "approval_status", length = 30)
private String approvalStatus;
@Column(name = "current_approval_node", length = 100)
private String currentApprovalNode;
@Column(name = "current_approver_id")
private Long currentApproverId;
@Column(name = "receipt_status", length = 30)
private String receiptStatus;
@Column(name = "payment_status", length = 30)
private String paymentStatus;
@Column(name = "budget_status", length = 30)
private String budgetStatus;
@Column(name = "source_doc_no", length = 100)
private String sourceDocNo;
@Column(name = "source_doc_type", length = 100)
private String sourceDocType;
@Column(name = "source_system", length = 50)
private String sourceSystem;
@Column(name = "source_doc_date")
private LocalDate sourceDocDate;
@Column(name = "source_status", length = 30)
private String sourceStatus;
@Column(name = "payee_name", length = 200)
private String payeeName;
@Column(name = "payee_bank_id")
private Long payeeBankId;
@Column(name = "return_reason", columnDefinition = "TEXT")
private String returnReason;
@Column(name = "submit_time")
private LocalDateTime submitTime;
@Column(name = "approve_time")
private LocalDateTime approveTime;
@Version
private Integer version;
@Builder.Default
@Column(nullable = false)
private Boolean deleted = false;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,51 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_approval_record")
public class ReimApprovalRecord {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "application_id", nullable = false)
private Long applicationId;
@Column(name = "node_name", length = 200, nullable = false)
private String nodeName;
@Column(name = "approver_id", nullable = false)
private Long approverId;
@Column(length = 30, nullable = false)
private String action;
@Column(columnDefinition = "TEXT")
private String comment;
@Column(length = 500)
private String signature;
@Column(name = "action_time")
private LocalDateTime actionTime;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
@@ -0,0 +1,51 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_attachment")
public class ReimAttachment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "application_id", nullable = false)
private Long applicationId;
@Column(name = "file_name", length = 500, nullable = false)
private String fileName;
@Column(name = "file_type", length = 100)
private String fileType;
@Column(name = "file_url", length = 500, nullable = false)
private String fileUrl;
@Column(name = "file_size")
private Long fileSize;
@Column(name = "content_type", length = 100)
private String contentType;
@Column(name = "uploader_id", nullable = false)
private Long uploaderId;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
@@ -0,0 +1,56 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_expense_item")
public class ReimExpenseItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "application_id", nullable = false)
private Long applicationId;
@Column(name = "seq_no", nullable = false)
private Integer seqNo;
@Column(name = "expense_date", nullable = false)
private LocalDate expenseDate;
@Column(length = 100, nullable = false)
private String category;
@Column(length = 500)
private String description;
@Column(nullable = false, precision = 18, scale = 2)
private BigDecimal amount;
@Column(length = 10)
private String currency;
@Column(name = "invoice_count")
private Integer invoiceCount;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
@@ -0,0 +1,71 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_invoice")
public class ReimInvoice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "application_id", nullable = false)
private Long applicationId;
@Column(name = "expense_item_id")
private Long expenseItemId;
@Column(name = "invoice_no", length = 100, nullable = false)
private String invoiceNo;
@Column(name = "invoice_code", length = 100)
private String invoiceCode;
@Column(name = "invoice_type", length = 50)
private String invoiceType;
@Column(name = "issue_date")
private LocalDate issueDate;
@Column(precision = 18, scale = 2)
private BigDecimal amount;
@Column(name = "tax_amount", precision = 18, scale = 2)
private BigDecimal taxAmount;
@Column(name = "seller_name", length = 500)
private String sellerName;
@Column(name = "seller_tax_no", length = 100)
private String sellerTaxNo;
@Column(name = "file_url", length = 500)
private String fileUrl;
@Column(name = "ocr_result", columnDefinition = "TEXT")
private String ocrResult;
@Column(name = "verify_status", length = 30)
private String verifyStatus;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
@@ -0,0 +1,98 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_payment")
public class ReimPayment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "payment_no", length = 50, nullable = false, unique = true)
private String paymentNo;
@Column(name = "application_id", nullable = false)
private Long applicationId;
@Column(name = "payee_id", nullable = false)
private Long payeeId;
@Column(name = "payee_bank_id")
private Long payeeBankId;
@Column(name = "total_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal totalAmount;
@Column(name = "payment_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal paymentAmount;
@Column(name = "paid_amount", precision = 18, scale = 2)
private BigDecimal paidAmount;
@Column(name = "remaining_amount", precision = 18, scale = 2)
private BigDecimal remainingAmount;
@Column(name = "payment_method", length = 50)
private String paymentMethod;
@Column(name = "bank_account_no", length = 100)
private String bankAccountNo;
@Column(name = "bank_account_name", length = 200)
private String bankAccountName;
@Column(name = "reference_no", length = 100)
private String referenceNo;
@Column(name = "operator_id", nullable = false)
private Long operatorId;
@Column(name = "payment_status", length = 30)
private String paymentStatus;
@Column(name = "payment_time")
private LocalDateTime paymentTime;
@Column(name = "idempotency_key", length = 100, unique = true)
private String idempotencyKey;
@Column(columnDefinition = "TEXT")
private String remark;
@Version
private Integer version;
@Builder.Default
@Column(nullable = false)
private Boolean deleted = false;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,58 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "reim_payment_installment")
public class ReimPaymentInstallment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "payment_id", nullable = false)
private Long paymentId;
@Column(name = "seq_no", nullable = false)
private Integer seqNo;
@Column(nullable = false, precision = 18, scale = 2)
private BigDecimal amount;
@Column(name = "payment_method", length = 50)
private String paymentMethod;
@Column(name = "reference_no", length = 100)
private String referenceNo;
@Column(length = 30)
private String status;
@Column(name = "operated_by")
private Long operatedBy;
@Column(name = "operated_at")
private LocalDateTime operatedAt;
@Column(length = 500)
private String remark;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
@@ -0,0 +1,63 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_approval_node")
public class SysApprovalNode {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "node_code", length = 50, nullable = false, unique = true)
private String nodeCode;
@Column(name = "node_name", length = 200, nullable = false)
private String nodeName;
@Column(name = "approver_type", length = 50, nullable = false)
private String approverType;
@Column(name = "approver_id")
private Long approverId;
@Column(name = "approver_role", length = 50)
private String approverRole;
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@Column(name = "timeout_hours")
private Integer timeoutHours;
@Column(length = 20)
private String status;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,64 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_bank_account")
public class SysBankAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id", nullable = false)
private Long userId;
@Column(name = "bank_name", length = 200, nullable = false)
private String bankName;
@Column(name = "branch_name", length = 200)
private String branchName;
@Column(name = "account_no", length = 100, nullable = false)
private String accountNo;
@Column(name = "account_no_mask", length = 50)
private String accountNoMask;
@Column(name = "account_name", length = 200, nullable = false)
private String accountName;
@Column(name = "is_default")
private Boolean isDefault;
@Column(length = 20)
private String status;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,64 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_budget")
public class SysBudget {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "dept_id", nullable = false)
private Long deptId;
@Column(name = "expense_type_id", nullable = false)
private Long expenseTypeId;
@Column(name = "fiscal_year", nullable = false)
private Integer fiscalYear;
@Column(name = "fiscal_month")
private Integer fiscalMonth;
@Column(name = "total_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal totalAmount;
@Column(name = "used_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal usedAmount;
@Column(name = "frozen_amount", nullable = false, precision = 18, scale = 2)
private BigDecimal frozenAmount;
@Column(length = 20)
private String status;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,54 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_department")
public class SysDepartment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "dept_code", length = 50, nullable = false, unique = true)
private String deptCode;
@Column(name = "dept_name", length = 200, nullable = false)
private String deptName;
@Column(name = "parent_id")
private Long parentId;
@Column(name = "sort_order")
private Integer sortOrder;
@Column(length = 20)
private String status;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,60 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_expense_type")
public class SysExpenseType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "type_code", length = 50, nullable = false, unique = true)
private String typeCode;
@Column(name = "type_name", length = 200, nullable = false)
private String typeName;
@Column(length = 50, nullable = false)
private String category;
@Column(name = "parent_id")
private Long parentId;
@Column(name = "sort_order")
private Integer sortOrder;
@Column(length = 20)
private String status;
@Column(name = "kingdee_form_id", length = 100)
private String kingdeeFormId;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,25 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data @Builder @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name = "sys_integration_config", uniqueConstraints = @UniqueConstraint(columnNames = {"provider", "config_key"}))
public class SysIntegrationConfig {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@Column(nullable = false, length = 20) private String provider;
@Column(name = "config_key", nullable = false, length = 80) private String configKey;
@Column(name = "config_value", length = 2000) private String configValue;
@Column(nullable = false) private Boolean secret;
@Column(nullable = false) private Boolean enabled;
@Column(name = "created_at") private LocalDateTime createdAt;
@Column(name = "updated_at") private LocalDateTime updatedAt;
@PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); }
@PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); }
}
@@ -0,0 +1,26 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/** A short-lived, one-time Feishu OAuth state shared by all application instances. */
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_oauth_state")
public class SysOauthState {
@Id
@Column(name = "state", length = 128, nullable = false)
private String state;
@Column(name = "expires_at", nullable = false)
private Long expiresAt;
}
@@ -0,0 +1,42 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_permission")
public class SysPermission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "permission_code", nullable = false, length = 120, unique = true)
private String permissionCode;
@Column(name = "permission_name", nullable = false, length = 200)
private String permissionName;
@Column(name = "permission_type", nullable = false, length = 20)
private String permissionType;
@Column(name = "parent_code", length = 120)
private String parentCode;
@Column(length = 200)
private String resource;
@Column(name = "default_access", length = 20)
private String defaultAccess;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); }
@PreUpdate
protected void onUpdate() { updatedAt = LocalDateTime.now(); }
}
@@ -0,0 +1,41 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_role")
public class SysRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "role_code", nullable = false, length = 80, unique = true)
private String roleCode;
@Column(name = "role_name", nullable = false, length = 200)
private String roleName;
@Column(length = 500)
private String description;
@Column(length = 20)
private String status;
@Column(name = "built_in", nullable = false)
private Boolean builtIn;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); }
@PreUpdate
protected void onUpdate() { updatedAt = LocalDateTime.now(); }
}
@@ -0,0 +1,33 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_role_permission", uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", "permission_id"}))
public class SysRolePermission {
@EmbeddedId
private SysRolePermissionId id;
@Column(name = "access_level", nullable = false, length = 20)
private String accessLevel;
public SysRolePermission(Long roleId, Long permissionId, String accessLevel) {
this.id = new SysRolePermissionId(roleId, permissionId);
this.accessLevel = accessLevel;
}
@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class SysRolePermissionId implements java.io.Serializable {
@Column(name = "role_id") private Long roleId;
@Column(name = "permission_id") private Long permissionId;
}
}
@@ -0,0 +1,90 @@
package com.finance.system.entity;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_user")
@org.hibernate.annotations.DynamicUpdate
public class SysUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "feishu_open_id", length = 100, unique = true)
private String feishuOpenId;
@Column(name = "feishu_user_id", length = 100, unique = true)
private String feishuUserId;
@Column(name = "employee_no", length = 50, unique = true)
private String employeeNo;
@Column(name = "real_name", length = 100, nullable = false)
private String realName;
@Column(name = "avatar_url", length = 500)
private String avatarUrl;
@Column(length = 200)
private String email;
@Column(length = 20)
private String mobile;
@Column(name = "department_id")
private Long departmentId;
@Column(length = 200)
private String position;
@Column(name = "user_type", length = 30)
private String userType;
/** Only used by the explicitly local password-login flow. */
@Column(name = "password_hash", length = 100)
private String passwordHash;
@Column(length = 20)
private String status;
@Builder.Default
@Column(name = "directory_status", nullable = false, length = 20, updatable = false)
private String directoryStatus = "UNKNOWN";
@Column(name = "directory_context", length = 64, updatable = false)
private String directoryContext;
@Column(name = "directory_verified_at", updatable = false)
private java.time.Instant directoryVerifiedAt;
@Column(name = "directory_last_seen_run_id", length = 36, updatable = false)
private String directoryLastSeenRunId;
@Column(name = "last_login_at")
private LocalDateTime lastLoginAt;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,30 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_user_group")
public class SysUserGroup {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "group_code", nullable = false, length = 80, unique = true)
private String groupCode;
@Column(name = "group_name", nullable = false, length = 200)
private String groupName;
@Column(length = 500) private String description;
@Column(length = 20) private String status;
@Column(name = "created_at") private LocalDateTime createdAt;
@Column(name = "updated_at") private LocalDateTime updatedAt;
@PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); updatedAt = LocalDateTime.now(); }
@PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); }
}
@@ -0,0 +1,22 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_user_group_member", uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "user_id"}))
public class SysUserGroupMember {
@EmbeddedId private SysUserGroupMemberId id;
public SysUserGroupMember(Long groupId, Long userId) { this.id = new SysUserGroupMemberId(groupId, userId); }
@Embeddable @Data @NoArgsConstructor @AllArgsConstructor
public static class SysUserGroupMemberId implements java.io.Serializable {
@Column(name = "group_id") private Long groupId;
@Column(name = "user_id") private Long userId;
}
}
@@ -0,0 +1,22 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_user_group_role", uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "role_id"}))
public class SysUserGroupRole {
@EmbeddedId private SysUserGroupRoleId id;
public SysUserGroupRole(Long groupId, Long roleId) { this.id = new SysUserGroupRoleId(groupId, roleId); }
@Embeddable @Data @NoArgsConstructor @AllArgsConstructor
public static class SysUserGroupRoleId implements java.io.Serializable {
@Column(name = "group_id") private Long groupId;
@Column(name = "role_id") private Long roleId;
}
}
@@ -0,0 +1,28 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sys_user_role", uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "role_id"}))
public class SysUserRole {
@EmbeddedId
private SysUserRoleId id;
public SysUserRole(Long userId, Long roleId) { this.id = new SysUserRoleId(userId, roleId); }
@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class SysUserRoleId implements java.io.Serializable {
@Column(name = "user_id") private Long userId;
@Column(name = "role_id") private Long roleId;
}
}
@@ -0,0 +1,42 @@
package com.finance.system.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import java.time.LocalDateTime;
/** Shared inbox record used to make Feishu webhook delivery idempotent. */
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "sys_webhook_event")
public class SysWebhookEvent {
public static final String PROCESSING = "PROCESSING";
public static final String PROCESSED = "PROCESSED";
public static final String FAILED = "FAILED";
@Id
@Column(name = "event_id", length = 200, nullable = false)
private String eventId;
@Column(name = "status", length = 20, nullable = false)
private String status;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
if (createdAt == null) {
createdAt = LocalDateTime.now();
}
}
}
@@ -0,0 +1,6 @@
package com.finance.system.enums;
public enum ApplicationStatus {
DRAFT,
SUBMITTED
}
@@ -0,0 +1,8 @@
package com.finance.system.enums;
public enum ApprovalAction {
APPROVE,
REJECT,
TRANSFER,
ADD_SIGN
}
@@ -0,0 +1,8 @@
package com.finance.system.enums;
public enum ApprovalStatus {
PENDING,
APPROVED,
REJECTED,
CANCELLED
}
@@ -0,0 +1,7 @@
package com.finance.system.enums;
public enum BudgetStatus {
PENDING,
OCCUPIED,
EXECUTED
}
@@ -0,0 +1,7 @@
package com.finance.system.enums;
public enum PaymentStatus {
UNPAID,
PARTIAL,
PAID
}
@@ -0,0 +1,6 @@
package com.finance.system.enums;
public enum ReceiptStatus {
UNRECEIVED,
RECEIVED
}
@@ -0,0 +1,7 @@
package com.finance.system.enums;
public enum SyncStatus {
PENDING,
SYNCED,
FAILED
}
@@ -0,0 +1,7 @@
package com.finance.system.enums;
public enum UserType {
EMPLOYEE,
FINANCE,
ADMIN
}
@@ -0,0 +1,7 @@
package com.finance.system.exception;
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
@@ -0,0 +1,18 @@
package com.finance.system.exception;
public class BusinessException extends RuntimeException {
private final int statusCode;
public BusinessException(String message) {
this(message, 409);
}
public BusinessException(String message, int statusCode) {
super(message);
this.statusCode = statusCode;
}
public int getStatusCode() {
return statusCode;
}
}
@@ -0,0 +1,75 @@
package com.finance.system.exception;
import com.finance.system.dto.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleResourceNotFound(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(404, e.getMessage()));
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ApiResponse<Void>> handleBadRequest(BadRequestException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.error(400, e.getMessage()));
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ApiResponse<Void>> handleUnauthorized(UnauthorizedException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(ApiResponse.error(401, e.getMessage()));
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ApiResponse<Void>> handleAccessDenied(AccessDeniedException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiResponse.error(403, "权限不足,无法访问"));
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ApiResponse<Void>> handleBusiness(BusinessException e) {
int statusCode = e.getStatusCode();
HttpStatus status = HttpStatus.resolve(statusCode);
if (status == null) {
status = HttpStatus.CONFLICT;
statusCode = status.value();
}
return ResponseEntity.status(status)
.body(ApiResponse.error(statusCode, e.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResponse<Map<String, String>>> handleValidation(
MethodArgumentNotValidException e) {
Map<String, String> errors = new HashMap<>();
e.getBindingResult().getAllErrors().forEach(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.error(400, "参数校验失败", errors));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleGeneral(Exception e) {
log.error("Unexpected error", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error(500, "服务器内部错误"));
}
}
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.