diff --git a/README.md b/README.md
index 5ded15d..59a71ad 100644
--- a/README.md
+++ b/README.md
@@ -4,3 +4,29 @@ 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`.
+
+For rollout and operations of asynchronous Feishu directory synchronization,
+see [`../docs/feishu-directory-sync.md`](../docs/feishu-directory-sync.md).
+
+## Database contract
+
+[`../database/init_schema.sql`](../database/init_schema.sql) is the only schema
+and bootstrap source. Run it with a MySQL 5.7 client only when
+`finance_system` does not yet exist. It intentionally fails against an existing
+or partial installation. The application keeps Hibernate `ddl-auto: validate`
+and never changes the application-owned schema during startup. The optional,
+explicitly authorized Kingdee table-preparation feature can create or alter only
+its configured target tables; use a narrowly scoped DDL account for that action
+or have a DBA pre-create those tables and keep the runtime account DML-only.
+Existing installations require a separately reviewed DBA release script and
+procedure for every in-place upgrade; never run the clean-install script against
+them.
+
+The sole script intentionally seeds exactly one environment-specific Feishu
+identity and binds it to the built-in `SUPER_ADMIN_GROUP`. Treat the script as an
+access-controlled deployment asset, verify that the identity is the intended
+operator, and edit it before installing another tenant. The seed has no local
+password, mobile, email, or avatar URL; it receives `SUPER_ADMIN` only through
+group membership, while `DEFAULT_EMPLOYEE` has no materialized member. Default
+passwords, local-profile bootstrap, and first-user auto-promotion remain
+prohibited.
diff --git a/pom.xml b/pom.xml
index 5e5140a..eaf8e51 100644
--- a/pom.xml
+++ b/pom.xml
@@ -50,19 +50,10 @@
- org.postgresql
- postgresql
+ com.mysql
+ mysql-connector-j
runtime
-
- com.h2database
- h2
- runtime
-
-
- org.flywaydb
- flyway-core
-
@@ -121,17 +112,6 @@
jackson-datatype-jsr310
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
- org.springframework.security
- spring-security-test
- test
-
diff --git a/src/main/java/com/finance/system/FinanceSystemApplication.java b/src/main/java/com/finance/system/FinanceSystemApplication.java
index 30795e6..9110f53 100644
--- a/src/main/java/com/finance/system/FinanceSystemApplication.java
+++ b/src/main/java/com/finance/system/FinanceSystemApplication.java
@@ -3,12 +3,14 @@ package com.finance.system;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableConfigurationProperties
+@EnableScheduling
public class FinanceSystemApplication {
public static void main(String[] args) {
SpringApplication.run(FinanceSystemApplication.class, args);
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java
new file mode 100644
index 0000000..58468fd
--- /dev/null
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalEventStateService.java
@@ -0,0 +1,153 @@
+package com.finance.system.adapter.feishu;
+
+import com.finance.system.entity.*;
+import com.finance.system.enums.*;
+import com.finance.system.exception.BusinessException;
+import com.finance.system.repository.*;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import java.time.LocalDateTime;
+import java.util.*;
+
+@Service
+@RequiredArgsConstructor
+public class FeishuApprovalEventStateService {
+ private final IntFeishuApprovalRepository approvals;
+ private final ReimApplicationRepository applications;
+ private final FeishuInstanceTimelineNodeRepository timeline;
+ private final IntFeishuApprovalAttemptRepository attempts;
+
+ @Transactional
+ public void applyInstanceStatus(String instanceCode, String status, LocalDateTime eventTime) {
+ String normalized = normalizeApprovalStatus(status);
+ if (normalized == null) throw retryable("飞书审批状态无效");
+ LocalDateTime trustedTime = eventTime == null ? LocalDateTime.now() : eventTime;
+ IntFeishuApproval candidate = approvals.findByFeishuInstanceCode(instanceCode).orElse(null);
+ if (candidate == null) {
+ applyHistoricalStatus(instanceCode, normalized, trustedTime);
+ return;
+ }
+ // Global lock order: application first, then current mapping.
+ ReimApplication app = applications.findByIdForUpdate(candidate.getApplicationId())
+ .orElseThrow(() -> retryable("报销申请尚未就绪"));
+ IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId())
+ .orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
+ if (!Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) {
+ applyHistoricalStatus(instanceCode, normalized, trustedTime);
+ return;
+ }
+ if ("CREATING".equals(mapping.getStatus()) || "CREATED".equals(mapping.getStatus())
+ || "CREATE_OUTCOME_UNKNOWN".equals(mapping.getStatus())) {
+ if (isTerminal(mapping.getDeferredStatus()) && ApprovalStatus.PENDING.name().equals(normalized)) return;
+ if (mapping.getDeferredEventAt() == null || !trustedTime.isBefore(mapping.getDeferredEventAt())) {
+ mapping.setDeferredStatus(normalized); mapping.setDeferredEventAt(trustedTime);
+ mapping.setSyncedAt(LocalDateTime.now()); approvals.save(mapping);
+ }
+ return;
+ }
+ if (mapping.getEventUpdatedAt() != null && trustedTime.isBefore(mapping.getEventUpdatedAt())) return;
+ String previous = normalizeApprovalStatus(mapping.getStatus());
+ if (isTerminal(previous) && ApprovalStatus.PENDING.name().equals(normalized)) return;
+ mapping.setStatus(normalized); mapping.setSyncedAt(LocalDateTime.now()); mapping.setEventUpdatedAt(trustedTime);
+ approvals.save(mapping);
+ app.setApprovalStatus(normalized);
+ if (ApprovalStatus.PENDING.name().equals(normalized)) {
+ app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setCurrentApprovalNode("飞书审批");
+ app.setCurrentApproverId(null); app.setApproveTime(null);
+ } else {
+ app.setCurrentApproverId(null); app.setCurrentApprovalNode(null);
+ if (ApprovalStatus.APPROVED.name().equals(normalized)) {
+ app.setApplicationStatus(ApplicationStatus.SUBMITTED.name()); app.setApproveTime(LocalDateTime.now());
+ } else {
+ app.setApplicationStatus(ApplicationStatus.DRAFT.name()); app.setApproveTime(null);
+ }
+ }
+ applications.save(app);
+ }
+
+ @Transactional
+ public void applyTask(Map task) {
+ String instanceCode = bounded(text(task, "instance_code", "instanceCode"), 200);
+ if (!StringUtils.hasText(instanceCode)) throw retryable("飞书任务缺少实例标识");
+ IntFeishuApproval candidate = approvals.findByFeishuInstanceCode(instanceCode).orElse(null);
+ Long approvalId;
+ if (candidate != null) {
+ applications.findByIdForUpdate(candidate.getApplicationId())
+ .orElseThrow(() -> retryable("报销申请尚未就绪"));
+ IntFeishuApproval mapping = approvals.findByApplicationIdForUpdate(candidate.getApplicationId())
+ .orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
+ if (Objects.equals(instanceCode, mapping.getFeishuInstanceCode())) approvalId = mapping.getId();
+ else approvalId = historicalApprovalId(instanceCode);
+ } else approvalId = historicalApprovalId(instanceCode);
+ String taskId = bounded(text(task, "task_id", "taskId", "id"), 300);
+ String nodeKey = bounded(text(task, "node_id", "nodeId", "node_key", "approval_node_id"), 300);
+ String key = StringUtils.hasText(taskId) ? "TASK:" + taskId : "ACTUAL:" + (nodeKey == null ? "unknown" : nodeKey);
+ key = bounded(key, 400);
+ FeishuInstanceTimelineNode row = timeline
+ .findByFeishuApprovalIdAndInstanceCodeAndTimelineKey(approvalId, instanceCode, key).orElse(null);
+ if (row == null && StringUtils.hasText(taskId)) row = timeline
+ .findByFeishuApprovalIdAndInstanceCodeAndTaskId(approvalId, instanceCode, taskId).orElse(null);
+ if (row == null && StringUtils.hasText(nodeKey)) {
+ FeishuInstanceTimelineNode planned = timeline
+ .findFirstByFeishuApprovalIdAndInstanceCodeAndNodeKeyOrderByIdAsc(approvalId, instanceCode, nodeKey)
+ .orElse(null);
+ if (planned != null && !StringUtils.hasText(planned.getTaskId())) row = planned;
+ }
+ LocalDateTime eventTime = parseTime(first(task, "action_time", "end_time", "update_time", "create_time"));
+ String incoming = normalizeTaskStatus(text(task, "status", "task_status", "taskStatus"));
+ if (row != null && row.getActionTime() != null && eventTime != null && eventTime.isBefore(row.getActionTime())) return;
+ if (row != null && isTerminalTask(row.getStatus()) && !isTerminalTask(incoming)) return;
+ LocalDateTime now = LocalDateTime.now();
+ if (row == null) row = FeishuInstanceTimelineNode.builder().feishuApprovalId(approvalId)
+ .instanceCode(instanceCode).timelineKey(key).nodeKey(nodeKey).planned(false).createdAt(now).build();
+ if (incoming != null) row.setStatus(incoming);
+ row.setTaskId(taskId); row.setPlanned(false);
+ String nodeName = bounded(text(task, "node_name", "nodeName", "name"), 300);
+ if (StringUtils.hasText(nodeName)) row.setNodeName(nodeName);
+ String approver = text(task, "approver_name", "user_name", "approver", "operator_name");
+ Map user = map(task.get("user"));
+ if (!StringUtils.hasText(approver) && user != null) approver = text(user, "name", "en_name");
+ if (StringUtils.hasText(approver)) row.setApproverLabel(bounded(approver, 300));
+ String comment = text(task, "comment", "opinion", "reason");
+ if (comment != null) row.setComment(bounded(comment, 2000));
+ if (eventTime != null) row.setActionTime(eventTime);
+ row.setUpdatedAt(now); timeline.save(row);
+ }
+
+ private void applyHistoricalStatus(String instanceCode, String normalized, LocalDateTime eventTime) {
+ IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode)
+ .orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
+ applications.findByIdForUpdate(known.getApplicationId())
+ .orElseThrow(() -> retryable("报销申请尚未就绪"));
+ IntFeishuApprovalAttempt attempt = attempts.findByInstanceCodeForUpdate(instanceCode)
+ .orElseThrow(() -> retryable("飞书历史审批映射尚未就绪"));
+ if (attempt.getEventUpdatedAt() != null && eventTime.isBefore(attempt.getEventUpdatedAt())) return;
+ String previous = normalizeApprovalStatus(attempt.getStatus());
+ if (isTerminal(previous) && ApprovalStatus.PENDING.name().equals(normalized)) return;
+ attempt.setStatus(normalized); attempt.setEventUpdatedAt(eventTime); attempt.setUpdatedAt(LocalDateTime.now());
+ attempts.save(attempt);
+ }
+
+ private Long historicalApprovalId(String instanceCode) {
+ IntFeishuApprovalAttempt known = attempts.findByInstanceCode(instanceCode)
+ .orElseThrow(() -> retryable("飞书审批映射尚未就绪"));
+ applications.findByIdForUpdate(known.getApplicationId())
+ .orElseThrow(() -> retryable("报销申请尚未就绪"));
+ return attempts.findByInstanceCodeForUpdate(instanceCode)
+ .orElseThrow(() -> retryable("飞书历史审批映射尚未就绪")).getFeishuApprovalId();
+ }
+
+ private Object first(Map map, String... keys) { for (String k:keys) if(map.get(k)!=null)return map.get(k); return null; }
+ private String text(Map map,String...keys){Object v=first(map,keys);return v==null?null:String.valueOf(v);}
+ @SuppressWarnings("unchecked") private Map map(Object v){return v instanceof Map?(Map)v:null;}
+ private String bounded(String v,int max){return v==null?null:v.substring(0,Math.min(max,v.length()));}
+ private String normalizeTaskStatus(String s){if(!StringUtils.hasText(s))return null;String v=s.trim().toUpperCase(Locale.ROOT);if("CANCELED".equals(v))v="CANCELLED";if("DONE".equals(v)||"COMPLETED".equals(v)||"PASS".equals(v))v="APPROVED";return v.length()<=50?v:null;}
+ private String normalizeApprovalStatus(String s){if(!StringUtils.hasText(s))return null;String v=s.trim().toUpperCase(Locale.ROOT);if("CANCELED".equals(v))v="CANCELLED";for(ApprovalStatus x:ApprovalStatus.values())if(x.name().equals(v))return v;return null;}
+ private boolean isTerminal(String s){return "APPROVED".equals(s)||"REJECTED".equals(s)||"CANCELLED".equals(s);}
+ private boolean isTerminalTask(String s){return "APPROVED".equals(s)||"REJECTED".equals(s)||"CANCELLED".equals(s)||"TRANSFERRED".equals(s);}
+ private LocalDateTime parseTime(Object v){if(v==null)return null;try{String s=String.valueOf(v);if(s.matches("\\d+")){long e=Long.parseLong(s);if(e>100000000000L)e/=1000;return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(e),java.time.ZoneOffset.UTC);}return LocalDateTime.parse(s);}catch(Exception e){return null;}}
+ private BusinessException retryable(String message){return new BusinessException(message,503);}
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java
index b4b0926..ddbb872 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalFormBuilder.java
@@ -7,7 +7,7 @@ import com.finance.system.entity.SysDepartment;
import com.finance.system.entity.SysExpenseType;
import java.math.BigDecimal;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -24,7 +24,7 @@ public class FeishuApprovalFormBuilder {
public static Map buildForm(ReimApplication app, SysUser applicant,
SysDepartment department, SysExpenseType expenseType,
List items) {
- Map form = new HashMap<>();
+ Map form = new LinkedHashMap<>();
// 基本字段
form.put("application_no", app.getApplicationNo());
@@ -38,7 +38,7 @@ public class FeishuApprovalFormBuilder {
// 费用明细(多行文本展示)
if (items != null && !items.isEmpty()) {
- String itemDetail = items.stream()
+ String itemDetail = ReimbursementCanonicalizer.orderedItems(items).stream()
.map(item -> String.format("%s | %s | ¥%.2f",
item.getExpenseDate() != null ? item.getExpenseDate().toString() : "",
item.getDescription() != null ? item.getDescription() : "",
@@ -79,4 +79,4 @@ public class FeishuApprovalFormBuilder {
.replace("\r", "\\r")
.replace("\t", "\\t");
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java
index 1b4331d..c219de1 100644
--- a/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java
+++ b/src/main/java/com/finance/system/adapter/feishu/FeishuApprovalService.java
@@ -1,9 +1,13 @@
package com.finance.system.adapter.feishu;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
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.exception.FeishuCreateOutcomeUnknownException;
import com.finance.system.repository.*;
import com.finance.system.service.IntegrationConfigReader;
import lombok.RequiredArgsConstructor;
@@ -13,6 +17,7 @@ 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.web.client.RestClientResponseException;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
@@ -27,6 +32,7 @@ import java.util.*;
@Service
@RequiredArgsConstructor
public class FeishuApprovalService {
+ private static final ObjectMapper JSON = new ObjectMapper();
private final FeishuConfig feishuConfig;
private final FeishuAuthService feishuAuthService;
@@ -38,12 +44,24 @@ public class FeishuApprovalService {
private final ReimApplicationRepository reimApplicationRepository;
private final RestTemplate restTemplate;
private IntegrationConfigReader integrationConfigReader;
+ private FeishuInstanceTimelineNodeRepository timelineNodeRepository;
+ private FeishuApprovalEventStateService eventStateService;
@Autowired(required = false)
public void setIntegrationConfigReader(IntegrationConfigReader integrationConfigReader) {
this.integrationConfigReader = integrationConfigReader;
}
+ @Autowired(required = false)
+ public void setTimelineNodeRepository(FeishuInstanceTimelineNodeRepository timelineNodeRepository) {
+ this.timelineNodeRepository = timelineNodeRepository;
+ }
+
+ @Autowired(required = false)
+ public void setEventStateService(FeishuApprovalEventStateService eventStateService) {
+ this.eventStateService = eventStateService;
+ }
+
private static final String FEISHU_OPEN_API = "https://open.feishu.cn/open-apis";
/**
@@ -94,6 +112,34 @@ public class FeishuApprovalService {
}
}
+ /** Raw transport response for server-side normalization only. Never expose this from a controller. */
+ public JsonNode fetchApprovalDefinitionJson() {
+ String token = feishuAuthService.getTenantAccessToken();
+ HttpHeaders headers = new HttpHeaders();
+ headers.setBearerAuth(token);
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ Map body = Collections.singletonMap("approval_code", approvalCode());
+ try {
+ ResponseEntity response = restTemplate.exchange(
+ FEISHU_OPEN_API + "/approval/openapi/v2/approval/get", HttpMethod.POST,
+ new HttpEntity<>(body, headers), JsonNode.class);
+ JsonNode value = response.getBody();
+ if (value == null || value.path("code").asInt(-1) != 0) {
+ throw new BusinessException("飞书审批定义同步失败", 502);
+ }
+ return value;
+ } catch (BusinessException e) {
+ throw e;
+ } catch (Exception e) {
+ log.warn("飞书审批定义请求失败: {}", e.getClass().getSimpleName());
+ throw new BusinessException("飞书审批定义同步失败,请稍后重试", 502);
+ }
+ }
+
+ public String getConfiguredApprovalCode() {
+ return approvalCode();
+ }
+
/**
* 获取审批节点列表(用于前端展示审批流程)
*/
@@ -107,110 +153,78 @@ public class FeishuApprovalService {
// ==================== 2. 创建审批实例 ====================
- /**
- * 创建飞书审批实例
- *
- * @param application 报销申请
- * @return 飞书审批实例编码
- */
- @Transactional
- public String createApprovalInstance(ReimApplication application) {
- if (application == null || application.getId() == null) {
- throw new BusinessException("报销申请不存在,无法创建飞书审批", 400);
- }
- Optional 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("该申请已有未完成的飞书同步记录,请稍后重试");
- }
- }
+ /** Performs only the remote create. The durable CREATING intent is managed by the coordinator. */
+ public String createApprovalInstanceRemote(Long applicationId, String requestUuid, String intendedApprovalCode) {
+ if (applicationId == null || !StringUtils.hasText(requestUuid) || !StringUtils.hasText(intendedApprovalCode))
+ throw new BusinessException("飞书审批创建参数无效", 400);
+ return createApprovalInstanceRemote(buildCreatePayload(applicationId, requestUuid, intendedApprovalCode), requestUuid);
+ }
- 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())) {
+ /** Built in Phase A while the application row is locked, then persisted verbatim. */
+ public String buildCreatePayload(Long applicationId, String requestUuid, String intendedApprovalCode) {
+ ReimApplication application = reimApplicationRepository.findById(applicationId)
+ .orElseThrow(() -> new BusinessException("报销申请不存在,无法创建飞书审批", 400));
+ SysUser applicant = application.getApplicantId() == null ? null
+ : sysUserRepository.findById(application.getApplicantId()).orElse(null);
+ if (applicant == null || (!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 items = reimExpenseItemRepository.findByApplicationId(application.getId());
-
- // 构建表单数据
- Map formData = FeishuApprovalFormBuilder.buildForm(
- application, applicant, department, expenseType, items);
- String formJson = FeishuApprovalFormBuilder.buildFormJson(formData);
-
- // 构建请求体
- Map 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